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
sequencelengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
sequencelengths
8
8
3 seconds
["5", "6", "17"]
7fe380a1848eae621c734cc9a3e463e0
NoteFor the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red): The second and the third examples can be seen below:
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!Each grid (main and reserve) has a head node (its number is $$$1$$$). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly $$$n$$$ nodes, which do not spread electricity further.In other words, every grid is a rooted directed tree on $$$n$$$ leaves with a root in the node, which number is $$$1$$$. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.Also, the palace has $$$n$$$ electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device. In this example the main grid contains $$$6$$$ nodes (the top tree) and the reserve grid contains $$$4$$$ nodes (the lower tree). There are $$$3$$$ devices with numbers colored in blue. It is guaranteed that the whole grid (two grids and $$$n$$$ devices) can be shown in this way (like in the picture above): main grid is a top tree, whose wires are directed 'from the top to the down', reserve grid is a lower tree, whose wires are directed 'from the down to the top', devices — horizontal row between two grids, which are numbered from $$$1$$$ to $$$n$$$ from the left to the right, wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number $$$1$$$, that visits leaves in order of connection to devices $$$1, 2, \dots, n$$$ (firstly, the node, that is connected to the device $$$1$$$, then the node, that is connected to the device $$$2$$$, etc.).Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
Print a single integer — the maximal amount of wires that can be cut so that each device is powered.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of devices in the palace. The next line contains an integer $$$a$$$ ($$$1 + n \le a \le 1000 + n$$$) — the amount of nodes in the main grid. Next line contains $$$a - 1$$$ integers $$$p_i$$$ ($$$1 \le p_i \le a$$$). Each integer $$$p_i$$$ means that the main grid contains a wire from $$$p_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$x_i$$$ ($$$1 \le x_i \le a$$$) — the number of a node in the main grid that is connected to the $$$i$$$-th device. The next line contains an integer $$$b$$$ ($$$1 + n \le b \le 1000 + n$$$) — the amount of nodes in the reserve grid. Next line contains $$$b - 1$$$ integers $$$q_i$$$ ($$$1 \le q_i \le b$$$). Each integer $$$q_i$$$ means that the reserve grid contains a wire from $$$q_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$y_i$$$ ($$$1 \le y_i \le b$$$) — the number of a node in the reserve grid that is connected to the $$$i$$$-th device. It is guaranteed that each grid is a tree, which has exactly $$$n$$$ leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node $$$1$$$, that visits leaves in order of connection to devices.
standard output
standard input
PyPy 2
Python
2,400
train_044.jsonl
b5e68b9714fb97a7e4327dcd0705e70c
256 megabytes
["3\n6\n4 1 1 4 2\n6 5 3\n4\n1 1 1\n3 4 2", "4\n6\n4 4 1 1 1\n3 2 6 5\n6\n6 6 1 1 1\n5 4 3 2", "5\n14\n1 1 11 2 14 14 13 7 12 2 5 6 1\n9 8 3 10 4\n16\n1 1 9 9 2 5 10 1 14 3 7 11 6 12 2\n8 16 13 4 15"]
PASSED
from __future__ import print_function,division import sys#log min est tolérable n=int(input()) def f(): global n co=[[0]*n for k in range(n)] a=int(input()) p=[0]+list(map(int,raw_input().split())) d=[0]*a s=[1]*a s[0]=0 mi=[n]*a#plus peit ma=[-1]*a#le plus tard for k in p[1:]: d[k-1]+=1 x=list(map(int,raw_input().split())) for k in range(n): mi[x[k]-1]=k ma[x[k]-1]=k pi=[k for k in range(a) if d[k]==0] for k in range(a-1): v=pi.pop() p[v]-=1 d[p[v]]-=1 if d[p[v]]==0: pi.append(p[v]) s[p[v]]+=s[v] ma[p[v]] =max(ma[p[v]],ma[v]) mi[p[v]] =min(mi[p[v]],mi[v]) for v in range(a): co[ma[v]][mi[v]]=max(s[v],co[ma[v]][mi[v]]) return co l1=f() l2=f() be=[0]*(n+1) for k in range(n): be[k]=max([be[k-1],max(be[i-1]+l1[k][i] for i in range(k+1)),max(be[i-1]+l2[k][i] for i in range(k+1))]) print(be[n-1])
1575038100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
4 seconds
["0 98 49 25 114", "0 -1 9"]
abee4d188bb59d82fcf4579c7416a343
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
standard output
standard input
PyPy 3
Python
2,200
train_110.jsonl
d80aa438141545f138a8bcab4be1f6c2
512 megabytes
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
PASSED
from heapq import heappush, heappop n, m = map(int, input().split()) adj = [[] for i in range(n + 1)] md = 10**9; dist = [md] * (51 * (n+1)); dist[51] = 0 for i in range(m): u, v, w = map(int, input().split()); adj[u].append((v, w)); adj[v].append((u, w)) gr = [(0, 51 * 1)] while gr: ol_d, c = heappop(gr) if dist[c] == ol_d: c, last_w = divmod(c, 51) for ne, w in adj[c]: if last_w: ne_d = ol_d + (w + last_w) ** 2 if dist[51 * ne] > ne_d: dist[51 * ne] = ne_d; heappush(gr, (ne_d, 51 * ne)) elif dist[51 * ne + w] > ol_d: dist[51 * ne + w] = ol_d ;heappush(gr, (ol_d, 51 * ne + w)) print(*(dist[51*i] if dist[51 * i] != md else -1 for i in range(1, n+1)), sep=' ')
1613658900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nNO\nYES"]
b132bf94af4352c4a690316eb610ebe1
NoteIn the first test case, you can stop the algorithm before the $$$0$$$-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add $$$k^0$$$ to $$$v_1$$$ and stop the algorithm.In the third test case, you can't make two $$$1$$$ in the array $$$v$$$.In the fifth test case, you can skip $$$9^0$$$ and $$$9^1$$$, then add $$$9^2$$$ and $$$9^3$$$ to $$$v_3$$$, skip $$$9^4$$$ and finally, add $$$9^5$$$ to $$$v_2$$$.
Suppose you are performing the following algorithm. There is an array $$$v_1, v_2, \dots, v_n$$$ filled with zeroes at start. The following operation is applied to the array several times — at $$$i$$$-th step ($$$0$$$-indexed) you can: either choose position $$$pos$$$ ($$$1 \le pos \le n$$$) and increase $$$v_{pos}$$$ by $$$k^i$$$; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $$$v$$$ equal to the given array $$$a$$$ ($$$v_j = a_j$$$ for each $$$j$$$) after some step?
For each test case print YES (case insensitive) if you can achieve the array $$$a$$$ after some step or NO (case insensitive) otherwise.
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30$$$, $$$2 \le k \le 100$$$) — the size of arrays $$$v$$$ and $$$a$$$ and value $$$k$$$ used in the algorithm. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{16}$$$) — the array you'd like to achieve.
standard output
standard input
Python 3
Python
1,400
train_000.jsonl
29be1ad0f126e5a3e6d36c2f864393f5
256 megabytes
["5\n4 100\n0 0 0 0\n1 2\n1\n3 4\n1 4 1\n3 2\n0 1 3\n3 9\n0 59049 810"]
PASSED
def giveb(num, k): l = [] while num > 0: if num%k not in [0,1]: return 'notvalid' else: l.append(str(num%k)) num = num//k return ''.join(l[::-1]) for _ in range(int(input())): n, k = map(int, input().split()) l = list(map(int, input().split())) ans = [] used = set() valid = True for i in l: ans.append(giveb(i, k)) for i in ans: for idx, j in enumerate(i[::-1]): if j == '0': continue if j != '1' or idx in used: valid = False break else: used.add(idx) #print(ans,used) if valid: print("YES") else: print('NO')
1583764500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["0 12 3 3", "0 1 1 254 254"]
deed251d324f7bbe53eefa94f92c3bbc
NoteOne possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here.
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.
Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq k \leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \leq p_i \leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.
standard output
standard input
Python 3
Python
1,700
train_042.jsonl
8fc1de325280aed985db6b16cde07317
256 megabytes
["4 3\n2 14 3 4", "5 2\n0 2 1 255 254"]
PASSED
n, k = map(int, input().split()) P = map(int, input().split()) parent = list(range(256)) sz = [1] * 256 def rt(x): if x != parent[x]: parent[x] = rt(parent[x]) return parent[x] def u(rx, ry): parent[ry] = rx sz[rx] += sz[ry] ans = [0] * n for i, p in enumerate(P): rx = rt(p) while rx > 0 and sz[rx] + sz[rt(rx - 1)] <= k: u(rt(rx - 1), rx) rx = rt(p) ans[i] = rt(p) print(' '.join(map(str, ans)))
1525791900
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["YES 2\n2\n1 2\n2 3", "YES 2\n4\n1 2\n3 2\n4 2\n5 2", "NO"]
69ee6170d9f1480647d1a3fed4d1f77b
NoteHere are the graphs for the first two example cases. Both have diameter of $$$2$$$. $$$d_1 = 1 \le a_1 = 2$$$$$$d_2 = 2 \le a_2 = 2$$$$$$d_3 = 1 \le a_3 = 2$$$ $$$d_1 = 1 \le a_1 = 1$$$$$$d_2 = 4 \le a_2 = 4$$$$$$d_3 = 1 \le a_3 = 1$$$$$$d_4 = 1 \le a_4 = 1$$$
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.The graph is connected if and only if there exists a path between every pair of vertices.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.The degree of a vertex is the number of edges incident to it.Given a sequence of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ construct a connected undirected graph of $$$n$$$ vertices such that: the graph contains no self-loops and no multiple edges; the degree $$$d_i$$$ of the $$$i$$$-th vertex doesn't exceed $$$a_i$$$ (i.e. $$$d_i \le a_i$$$); the diameter of the graph is maximum possible. Output the resulting graph or report that no solution exists.
Print "NO" if no graph can be constructed under the given conditions. Otherwise print "YES" and the diameter of the resulting graph in the first line. The second line should contain a single integer $$$m$$$ — the number of edges in the resulting graph. The $$$i$$$-th of the next $$$m$$$ lines should contain two integers $$$v_i, u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \neq u_i$$$) — the description of the $$$i$$$-th edge. The graph should contain no multiple edges — for each pair $$$(x, y)$$$ you output, you should output no more pairs $$$(x, y)$$$ or $$$(y, x)$$$.
The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) — the number of vertices in the graph. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n - 1$$$) — the upper limits to vertex degrees.
standard output
standard input
Python 3
Python
1,800
train_009.jsonl
b5bc1656bdb063e417cabb09569185cc
256 megabytes
["3\n2 2 2", "5\n1 4 1 1 1", "3\n1 1 1"]
PASSED
a = [] n = 0 Ones = [] def solution (): s = 0 for item in a : s = s + item if s < 2*(n-1) : print("NO") return for i in range(n): if a[i] == 1 : a[i] = 0 Ones.append(i) t = len(Ones) d = (n-t) - 1 + min(2,t) print("YES " + str(d) + "\n" + str(n-1) ) l = -1 if len(Ones) != 0 : l = Ones[len(Ones)-1] Ones.remove(l) for i in range (n): if a[i] > 1 : if l !=-1: a[l] = a[l] -1 a[i] = a[i] -1 print (str (l+1) + " " + str(i+1)) l=i i = n-1 while i >=0 : while len(Ones) > 0 and a[i] > 0 : a[i] = a[i] -1 u = Ones[len(Ones)-1] print(str(i+1) + " " + str (u +1) ) Ones.remove(u) i = i -1 if __name__ == "__main__": line = int(input()) n = int(line) line = str(input()).split() for i in range (n): a.append(int(line[i])) solution()
1543415700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["4\n4\n2\n3\n4"]
3ca37d1209b487a383b56ba4b7c1e872
NoteThe image depicts the tree from the first test case during each second.A vertex is black if it is not infected. A vertex is blue if it is infected by injection during the previous second. A vertex is green if it is infected by spreading during the previous second. A vertex is red if it is infected earlier than the previous second. Note that you are able to choose which vertices are infected by spreading and by injections.
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.You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex $$$v$$$, if at least one child of $$$v$$$ is infected, you can spread the disease by infecting at most one other child of $$$v$$$ of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
For each test case you should output a single integer — the minimal number of seconds needed to infect the whole tree.
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. The second line of each test case contains $$$n - 1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the ancestor of the $$$i$$$-th vertex 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
1,600
train_096.jsonl
3daf6d2ec16b1db183b9346ba63f6de0
256 megabytes
["5\n7\n1 1 1 2 2 4\n5\n5 5 1 4\n2\n1\n3\n3 1\n6\n1 1 1 1 1"]
PASSED
import sys input=sys.stdin.readline def get_rid_of_zeros(): while len(number_of_children) and number_of_children[-1]<=0: number_of_children.pop() for _ in range(int(input())): n=int(input()) x=list(map(int,input().split())) number_of_children=[0]*n for i in x: number_of_children[i-1]+=1 number_of_children.append(1) number_of_children.sort(reverse=True) get_rid_of_zeros() ans=0 temp=1 for i in range(len(number_of_children)-1,-1,-1): if number_of_children[i]>0: number_of_children[i]-=temp temp+=1 ans+=1 number_of_children.sort(reverse=True) get_rid_of_zeros() while len(number_of_children) and number_of_children[0]>0: ans+=1 last=0 temp=number_of_children[0] for i in range(len(number_of_children)): if number_of_children[i]==temp: last=i number_of_children[i]-=1 number_of_children[last] -= 1 get_rid_of_zeros() print(ans) # 1 # 17 # 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
1649428500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1.5 seconds
["2\n-1\n1\n2\n5"]
af40a0de6d3c0ff7bcd2c1b077b05d6e
NoteIn the first example, we will understand chapters $$$\{2, 4\}$$$ in the first reading and chapters $$$\{1, 3\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\{2, 3, 4\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$.
You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.
For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \le k_i \le n-1$$$) — number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l}$$$ for $$$j \ne l$$$) follow — the chapters required to understand the $$$i$$$-th chapter. It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_094.jsonl
bd9707c575d230e94cb38c7b9453c41b
256 megabytes
["5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 2\n1 3\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 5\n0"]
PASSED
for _ in range(int(input())): n = int(input()) adj = [[] for i in range(n)] in_degree= [[] for i in range(n)] for i in range(n): l = list(map(int,input().split())) for j in range(1,len(l)): adj[l[j]-1].append(i) in_degree[i] = l[0] count= 0 from collections import deque q=deque() for i,val in enumerate(in_degree): if(val==0): q.append(i) dp = [1 for i in range(n)] while(q): count+= 1 temp = q.popleft() for item in adj[temp]: if(item<temp): if(dp[item]<dp[temp]+1): dp[item] = dp[temp]+1 else: if(dp[item]<dp[temp]): dp[item]= dp[temp] in_degree[item]-=1 if(in_degree[item]==0): q.append(item) if(count==n): print(max(dp)) else: print(-1)
1631975700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["5 3", "1 7", "2999999987 2", "12 13"]
ca7de8440f5bbbe75e8b93654ce75cd3
NoteIn the first example the minimum value of $$$y$$$ equals to $$$5$$$, i.e. the minimum number of people who could have broken into the basement, is $$$5$$$. Each of them has taken $$$3$$$ swords: three of them have taken $$$3$$$ swords of the first type, and two others have taken $$$3$$$ swords of the third type.In the second example the minimum value of $$$y$$$ is $$$1$$$, i.e. the minimum number of people who could have broken into the basement, equals to $$$1$$$. He has taken $$$7$$$ swords of the first type.
There were $$$n$$$ types of swords in the theater basement which had been used during the plays. Moreover there were exactly $$$x$$$ swords of each type. $$$y$$$ people have broken into the theater basement and each of them has taken exactly $$$z$$$ swords of some single type. Note that different people might have taken different types of swords. Note that the values $$$x, y$$$ and $$$z$$$ are unknown for you.The next morning the director of the theater discovers the loss. He counts all swords — exactly $$$a_i$$$ swords of the $$$i$$$-th type are left untouched.The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.For example, if $$$n=3$$$, $$$a = [3, 12, 6]$$$ then one of the possible situations is $$$x=12$$$, $$$y=5$$$ and $$$z=3$$$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $$$x, y$$$ and $$$z$$$ beforehand but know values of $$$n$$$ and $$$a$$$.Thus he seeks for your help. Determine the minimum number of people $$$y$$$, which could have broken into the theater basement, and the number of swords $$$z$$$ each of them has taken.
Print two integers $$$y$$$ and $$$z$$$ — the minimum number of people which could have broken into the basement and the number of swords each of them has taken.
The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of types of swords. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^{9})$$$, where $$$a_i$$$ equals to the number of swords of the $$$i$$$-th type, which have remained in the basement after the theft. It is guaranteed that there exists at least one such pair of indices $$$(j, k)$$$ that $$$a_j \neq a_k$$$.
standard output
standard input
Python 3
Python
1,300
train_022.jsonl
2a8d299d7cd11a758738717f92c2786d
256 megabytes
["3\n3 12 6", "2\n2 9", "7\n2 1000000000 4 6 8 4 2", "6\n13 52 0 13 26 52"]
PASSED
from math import gcd n = int(input()) d1 = [int(i) for i in input().split()] mn = min(d1) mx = max(d1) d2 = [mx - i for i in d1] g = d2[0] for i in range(1, n): g = gcd(g, d2[i]) sm = sum(d2) am = sm // g print(am, g)
1569049500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 1 2", "1 1 1 2 3"]
291bfc61026dddf6c53f4cd9a8aa2baa
NoteIn the first example for $$$k = 1$$$ and $$$k = 2$$$ we can use only one color: the junctions $$$2$$$ and $$$3$$$ will be happy. For $$$k = 3$$$ you have to put the bulbs of different colors to make all the junctions happy.In the second example for $$$k = 4$$$ you can, for example, put the bulbs of color $$$1$$$ in junctions $$$2$$$ and $$$4$$$, and a bulb of color $$$2$$$ into junction $$$5$$$. The happy junctions are the ones with indices $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ then.
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $$$1$$$ to $$$n$$$, the junction $$$1$$$ is called the root.A subtree of a junction $$$v$$$ is a set of junctions $$$u$$$ such that the path from $$$u$$$ to the root must pass through $$$v$$$. Note that $$$v$$$ itself is included in a subtree of $$$v$$$.A leaf is such a junction that its subtree contains exactly one junction.The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $$$t$$$ that all light bulbs in the subtree of $$$t$$$ have different colors.Arkady is interested in the following question: for each $$$k$$$ from $$$1$$$ to $$$n$$$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $$$k$$$?
Output $$$n$$$ integers. The $$$i$$$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $$$i$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of junctions in the tree. The second line contains $$$n - 1$$$ integers $$$p_2$$$, $$$p_3$$$, ..., $$$p_n$$$ ($$$1 \le p_i &lt; i$$$), where $$$p_i$$$ means there is a branch between junctions $$$i$$$ and $$$p_i$$$. It is guaranteed that this set of branches forms a tree.
standard output
standard input
Python 3
Python
1,600
train_025.jsonl
a887646245738abe27e94f7cf11b39fd
256 megabytes
["3\n1 1", "5\n1 1 3 3"]
PASSED
n = int(input()) p = [0,0] + [int(w) for w in input().split()] d = [0] * (n+1) for i in range(n, 1, -1): if d[i] == 0: d[i] = 1 d[p[i]] += d[i] if n == 1: d[1] = 1 d = d[1:] d.sort() print(*d)
1543163700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["2\n1 2\n2 3", "3\n1 2\n2 3\n3 4\n3 5"]
ad49b1b537ca539ea0898ee31a0aecf8
NoteIn the first example the only network is shown on the left picture.In the second example one of optimal networks is shown on the right picture.Exit-nodes are highlighted.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids. If there are multiple answers, print any of them.
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
standard output
standard input
Python 2
Python
1,800
train_005.jsonl
aff35ff907371f0ded1169be148b0b3f
512 megabytes
["3 2", "5 3"]
PASSED
n,k=map(int,raw_input().split()) print (n-1)/k*2+min((n-1)%k,2) for i in range(n-1): print max(1,i+2-k),i+2
1499791500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["2\n4\n5\n999999999\n5"]
681ee82880ddd0de907aac2ccad8fc04
NoteIn the first sample: $$$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1$$$, $$$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2$$$, $$$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1$$$, $$$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable.
Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$$$, where $$$\left\lfloor\frac{x}{a}\right\rfloor$$$ is $$$\frac{x}{a}$$$, rounded down, $$$x \bmod a$$$ — the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \le x \le r$$$).
For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $$$a$$$.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$$$) — the left and right boundaries of the segment and the fixed value of $$$a$$$.
standard output
standard input
Python 3
Python
900
train_104.jsonl
ab2b4efc6652567f2ee7130d242e6188
256 megabytes
["5\n\n1 4 3\n\n5 8 4\n\n6 10 6\n\n1 1000000000 1000000000\n\n10 12 8"]
PASSED
t = int(input()) if t>0: for i in range(t): l,r,a = map(int, input().split()) if a>r: print(r//a + r%a) else: if r//a == l//a: print(r//a + r%a) elif r//a - l//a == 1: r1 = r//a + r%a l1 = l//a + (a-1)%a if r1>l1: print(r1) else: print(l1) else: r1 = r//a + r%a l1 = r//a - 1 + (a-1)%a if r1>l1: print(r1) else: print(l1)
1646750100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["54", "1000000000000000000"]
96dee17800e147350bd37e60f66f49dd
NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$.
There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.
Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.
The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le m \le 2 \cdot 10^9$$$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.
standard output
standard input
Python 3
Python
1,000
train_003.jsonl
b47668a9dbe68acfd1ab79305816edcd
256 megabytes
["6 9 2\n1 3 3 7 4 2", "3 1000000000 1\n1000000000 987654321 1000000000"]
PASSED
n,m,k = list(map(int,input().split())) arr = list(map(int,input().split())) a = max(arr) if arr.count(a) > 1: b = a else: arr = sorted(arr) b = arr[n - 2] u = 0 l = m // (k + 1) u += l * (k * a + b) w = m % (k + 1) u += w * a print(u)
1550504400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["-1", "0", "1\n1", "1\n2"]
c046e64e008e997620efc21aec199bdb
NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di =  - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.
Print  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.
The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.
standard output
standard input
Python 2
Python
2,100
train_031.jsonl
ab3d69f6d5910e91765b7b127a4ae42c
256 megabytes
["1 0\n1", "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4", "2 1\n1 1\n1 2", "3 3\n0 -1 1\n1 2\n2 3\n1 3"]
PASSED
from collections import deque def subtree_specs(graph, d, node, visited, edges_dict, res_edges): num_ones = 0 for nb in graph[node]: if not visited[nb]: visited[nb] = True res = subtree_specs(graph, d, nb, visited, edges_dict, res_edges) if res % 2 == 1: # Need to attach this node res_edges.append(edges_dict[node][nb]) num_ones += res if d[node] == 1: num_ones += 1 return num_ones def subtree_specs_stack(graph, d, edges_dict): n = len(graph) visited = n * [False] visited[0] = True children = [[] for _ in range(n)] num_ones = n * [-1] res_edges = [] q = deque([(0, 'InProcess')]) while len(q) > 0: node, state = q.pop() if state == 'InProcess': q.append((node, 'Done')) for nb in graph[node]: if not visited[nb]: visited[nb] = True q.append((nb, 'InProcess')) children[node].append(nb) elif state == 'Done': res = sum([num_ones[i] for i in children[node]]) if d[node] == 1: res += 1 num_ones[node] = res for child in children[node]: if num_ones[child] % 2 == 1: res_edges.append(edges_dict[node][child]) return res_edges def main(): n, m = map(int, raw_input().split(' ')) d = map(int, raw_input().split(' ')) graph = [[] for _ in range(n)] edges_dict = {} for i in range(m): node1, node2 = map(int, raw_input().split(' ')) node1 -= 1 node2 -= 1 graph[node1].append(node2) graph[node2].append(node1) if node1 not in edges_dict: edges_dict[node1] = {} if node2 not in edges_dict: edges_dict[node2] = {} if node2 not in edges_dict[node1]: edges_dict[node1][node2] = i + 1 if node1 not in edges_dict[node2]: edges_dict[node2][node1] = i + 1 if len([el for el in d if el == 1]) == 0: print 0 return else: if len([el for el in d if el == 1]) % 2 == 1: if len([el for el in d if el == -1]) == 0: print -1 return else: i = [i for i in range(len(d)) if d[i] == -1][0] d[i] = 1 res = subtree_specs_stack(graph, d, edges_dict) print len(res) for el in res: print el if __name__ == "__main__": main()
1503068700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES", "YES", "NO"]
64b597a47106d0f08fcfad155e0495c3
NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.
Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).
The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.
standard output
standard input
PyPy 3
Python
900
train_011.jsonl
f6b8724cd7715792859c5f3fbff36a20
256 megabytes
["5 3\n1 1 1 1 1\n1 1 1 1 1", "5 4\n1 0 0 0 1\n0 1 1 1 1", "5 2\n0 1 1 1 1\n1 1 1 1 1"]
PASSED
n,s = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) s-=1 if a[0]==0: print('NO') elif a[s]==1: print('YES') elif any([(a[i] and b[i]) for i in range(s+1,n)]) and b[s]==1: print('YES') else: print('NO')
1541860500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2", "2"]
944ab87c148df0fc59ec0263d6fd8b9f
NoteIn the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s. The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only. The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
standard output
standard input
Python 3
Python
2,100
train_053.jsonl
496f25e71bb9f302589dfad055890d09
256 megabytes
["5\nbb?a?\n1", "9\nab??ab???\n3"]
PASSED
match = 0; nonmatch = 0; count = 0 def calc_match(s, t, p): global match global nonmatch global count if p == len(s)-len(t): return if p+len(t) < len(s): if s[p+len(t)] == '?': count -= 1 elif s[p+len(t)] == t[-1]: match -= 1 else: nonmatch -= 1 match, nonmatch = nonmatch, match if p+len(t) < len(s): if s[p] == '?': count += 1 elif s[p] == 'a': match += 1 else: nonmatch += 1 def init_match(s, t): global match global nonmatch global count p = len(s)-len(t) for i in range(len(t)): if s[p+i] == '?': count += 1 elif s[p+i] == t[i]: match += 1 else: nonmatch += 1 n = int(input()) s = input() m = int(input()) t = "" for i in range(m): if i%2==0: t = t + 'a' else: t = t + 'b' init_match(s,t) dp = [] for i in range(n+3): dp.append((0, 0)) p = n-m while p >= 0: calc_match(s, t, p) if nonmatch == 0: if dp[p+1][0] == dp[p+m][0]+1: dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count)) elif dp[p+1][0] > dp[p+m][0]+1: dp[p] = dp[p+1] else: dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count) else: dp[p] = dp[p+1] p -= 1 print(dp[0][1])
1513008300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["72900", "317451037"]
6fcd8713af5a108d590bc99da314cded
NoteIn the first example, $$$f_{4} = 90$$$, $$$f_{5} = 72900$$$.In the second example, $$$f_{17} \approx 2.28 \times 10^{29587}$$$.
Let $$$f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$$$ for $$$x \ge 4$$$.You have given integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$. Find $$$f_{n} \bmod (10^{9}+7)$$$.
Print $$$f_{n} \bmod (10^{9} + 7)$$$.
The only line contains five integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$ ($$$4 \le n \le 10^{18}$$$, $$$1 \le f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, $$$c \le 10^{9}$$$).
standard output
standard input
Python 3
Python
2,300
train_000.jsonl
3bf934bfa45c8ccf487e4f51f1003160
256 megabytes
["5 1 2 5 3", "17 97 41 37 11"]
PASSED
def mat_mul(a, b): n, m, p = len(a), len(b), len(b[0]) res = [[0]*p for _ in range(n)] for i in range(n): for j in range(p): for k in range(m): res[i][j] += a[i][k]*b[k][j] res[i][j] %= 1000000006 return res def mat_pow(a, n): if n == 1: return a if n%2 == 1: return mat_mul(mat_pow(a, n-1), a) t = mat_pow(a, n//2) return mat_mul(t, t) n, f1, f2, f3, c = map(int, input().split()) m1 = [[3, 1000000004, 0, 1000000005, 1], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]] m2 = [[2], [0], [0], [0], [0]] t1 = pow(c, mat_mul(mat_pow(m1, n), m2)[-1][0], 1000000007) m1 = [[0, 0, 1], [1, 0, 1], [0, 1, 1]] m2 = [[1], [0], [0]] m3 = mat_mul(mat_pow(m1, n-1), m2) t2 = pow(f1, m3[0][0], 1000000007) t3 = pow(f2, m3[1][0], 1000000007) t4 = pow(f3, m3[2][0], 1000000007) print(t1*t2*t3*t4%1000000007)
1560258300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1", "-1", "2 4 1 3", "2 5 3 1 4"]
dfca19b36c1d682ee83224a317e495e9
null
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n).A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1.You have integer n. Find some lucky permutation p of size n.
Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist. Otherwise, print n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) after a space — the required permutation. If there are multiple answers, you can print any of them.
The first line contains integer n (1 ≤ n ≤ 105) — the required permutation size.
standard output
standard input
Python 3
Python
1,400
train_062.jsonl
b7f82d0e86758b4eada6e788a850e0e2
256 megabytes
["1", "2", "4", "5"]
PASSED
n = int(input()) p = [0] * n if n == 1: print(1) exit() for sh in range(n // 4): p[n - sh * 2 - 2] = n - sh * 2 p[sh * 2] = n - 1 - sh * 2 p[n - sh * 2 - 1] = 2 + sh * 2 p[sh * 2 + 1] = 1 + sh * 2 if n % 4 == 1: p[n // 2] = n // 2 + 1 if n % 4 == 2: print(-1) exit() if n % 4 == 3: print(-1) exit() print(" ".join([str(i) for i in p]))
1364025600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["70 27 \n17 \n3 4 100 4\n10 90\n1 1 2 1 1 1 1 1 1 \n999900 90 9"]
2afb210831529a99f8f04f13e5438d55
NoteIn the first test case, $$$70_{10} + 27_{10} = 97_{10}$$$, and Alice's sum is $$$$$$70_{11} + 27_{11} = 97_{11} = 9 \cdot 11 + 7 = 106_{10}.$$$$$$ (Here $$$x_b$$$ represents the number $$$x$$$ in base $$$b$$$.) It can be shown that it is impossible for Alice to get a larger sum than $$$106_{10}$$$.In the second test case, Bob can only write a single number on the board, so he must write $$$17$$$.In the third test case, $$$3_{10} + 4_{10} + 100_{10} + 4_{10} = 111_{10}$$$, and Alice's sum is $$$$$$3_{11} + 4_{11} + 100_{11} + 4_{11} = 110_{11} = 1 \cdot 11^2 + 1 \cdot 11 = 132_{10}.$$$$$$ It can be shown that it is impossible for Alice to get a larger sum than $$$132_{10}$$$.
On the board, Bob wrote $$$n$$$ positive integers in base $$$10$$$ with sum $$$s$$$ (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-$$$11$$$ integers and adds them up (in base $$$11$$$).What numbers should Bob write on the board, so Alice's sum is as large as possible?
For each test case, output $$$n$$$ positive integers — the numbers Bob should write on the board, so Alice's sum is as large as possible. If there are multiple answers, print any of them.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$s$$$ and $$$n$$$ ($$$1 \leq s \leq 10^9$$$; $$$1 \leq n \leq \min(100, s)$$$) — the sum and amount of numbers on the board, respectively. Numbers $$$s$$$ and $$$n$$$ are given in decimal notation (base $$$10$$$).
standard output
standard input
PyPy 3
Python
2,000
train_089.jsonl
a93f197c100725a3cfdee58adc6ca091
256 megabytes
["6\n97 2\n17 1\n111 4\n100 2\n10 9\n999999 3"]
PASSED
def solver(s, n): num = 10 ** (len(str(s))-1) for i in range(n-1): while s - num < n - (i + 1): num //= 10 print(num, end=' ') s -= num print(s) T = int(input()) for t in range(T): S, N = map(int, input().split()) solver(S, N) ''' 6 97 2 17 1 111 4 100 2 10 9 999999 3 1 14 7 '''
1630852500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["NO\nNO\nYES\nYES\nYES\nYES\nNO\nNO\nYES"]
9363df0735005832573ef4d17b6a8302
NoteFor the first test case, $$$a = [1]$$$, so the answer is "NO", since the only element in the array is $$$1$$$.For the second test case the array is $$$a = [3, 4, 5]$$$ and we have $$$1$$$ operation. After the first operation the array can change to: $$$[3, 20]$$$, $$$[4, 15]$$$ or $$$[5, 12]$$$ all of which having their greatest common divisor equal to $$$1$$$ so the answer is "NO".For the third test case, $$$a = [13]$$$, so the answer is "YES", since the only element in the array is $$$13$$$.For the fourth test case, $$$a = [4]$$$, so the answer is "YES", since the only element in the array is $$$4$$$.
Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times? Choose $$$2$$$ numbers from $$$a$$$. Permanently remove one occurrence of each of them from the array. Insert their product back into $$$a$$$. $$$\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.
For each test case, print "YES" if it is possible to have the GCD of the corresponding array greater than $$$1$$$ by performing at most $$$k$$$ operations, and "NO" otherwise (case insensitive).
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of test cases follows. The input for each test case consists of a single line containing $$$3$$$ non-negative integers $$$l$$$, $$$r$$$, and $$$k$$$ ($$$1 \leq l \leq r \leq 10^9, \enspace 0 \leq k \leq r - l$$$).
standard output
standard input
Python 3
Python
800
train_093.jsonl
b55bd725eed01cfdac7878fa1f797954
256 megabytes
["9\n1 1 0\n3 5 1\n13 13 0\n4 4 0\n3 7 4\n4 10 3\n2 4 0\n1 7 3\n1 5 3"]
PASSED
for i in range(int(input())): a=list(map(int,input().split(' '))) if a[0]==a[1]: if a[0]!=1: print('YES') else: print('NO') else: k=a[2] if a[0]%2!=0: d=1+(a[1]-a[0])//2 else: d=(a[1]-a[0]+1)//2 if k>=d: print('YES') else: print('NO')
1642862100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["7", "6"]
55512092f84fdf712b212ed389ae6bc8
NoteThere are $$$7$$$ subpermutations in the first test case. Their segments of indices are $$$[1, 4]$$$, $$$[3, 3]$$$, $$$[3, 6]$$$, $$$[4, 7]$$$, $$$[6, 7]$$$, $$$[7, 7]$$$ and $$$[7, 8]$$$.In the second test case $$$6$$$ subpermutations exist: $$$[1, 1]$$$, $$$[2, 2]$$$, $$$[2, 3]$$$, $$$[3, 4]$$$, $$$[4, 4]$$$ and $$$[4, 5]$$$.
You have an array $$$a_1, a_2, \dots, a_n$$$. Let's call some subarray $$$a_l, a_{l + 1}, \dots , a_r$$$ of this array a subpermutation if it contains all integers from $$$1$$$ to $$$r-l+1$$$ exactly once. For example, array $$$a = [2, 2, 1, 3, 2, 3, 1]$$$ contains $$$6$$$ subarrays which are subpermutations: $$$[a_2 \dots a_3]$$$, $$$[a_2 \dots a_4]$$$, $$$[a_3 \dots a_3]$$$, $$$[a_3 \dots a_5]$$$, $$$[a_5 \dots a_7]$$$, $$$[a_7 \dots a_7]$$$.You are asked to calculate the number of subpermutations.
Print the number of subpermutations of the array $$$a$$$.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$). This array can contain the same integers.
standard output
standard input
PyPy 3
Python
2,500
train_033.jsonl
4ff0b87eabe82c7e06ea8d4c654cc33c
256 megabytes
["8\n2 4 1 3 4 2 1 2", "5\n1 1 2 1 2"]
PASSED
import sys import math input=sys.stdin.readline #sys.setrecursionlimit(1000000) mod=int(1000000007) i=lambda :map(int,input().split()) n=int(input()) a=[int(x) for x in input().split()] t=[[0]*21 for i in range(300005)] for i in range(n): t[i][0]=a[i] def build(n): for j in range(1,20): for i in range(n): if i+(1<<j)-1>n-1: break; t[i][j]=max(t[i][j-1],t[i+(1<<(j-1))][j-1]) def query(p,q): p,q=int(p),int(q) log=int(math.log2(q-p+1)) m=t[p][log] n=t[q-(1<<log)+1][log] return max(m,n) b=[-1]*(n+2) build(n) max1=-1 ans=0 for i in range(n): max1=max(max1,b[a[i]]) b[a[i]]=i x=b[1] while x>max1: if x<=max1: break p=query(x,i) if p==i-x+1: ans+=1 x=b[p+1] else: x=i-p+1 print(ans)
1559745300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
5 seconds
["A\nD 3\n2\nB\n2"]
299c209b070e510e7ed3b525f51fec8a
NoteThe first example has two test cases. In the first test case, the graph looks like the following. In the sample output, the player decides to play as Alice and chooses "decreasing" and starting at node $$$3$$$. The judge responds by moving to node $$$6$$$. After, the player moves to node $$$2$$$. At this point, the judge has no more moves (since the weight must "increase"), so it gives up and prints $$$-1$$$.In the next case, we have two nodes connected by an edge of weight $$$1$$$. The player decides to play as Bob. No matter what the judge chooses, the player can move the token to the other node and the judge has no moves so will lose.
You are given a complete bipartite graph with $$$2n$$$ nodes, with $$$n$$$ nodes on each side of the bipartition. Nodes $$$1$$$ through $$$n$$$ are on one side of the bipartition, and nodes $$$n+1$$$ to $$$2n$$$ are on the other side. You are also given an $$$n \times n$$$ matrix $$$a$$$ describing the edge weights. $$$a_{ij}$$$ denotes the weight of the edge between nodes $$$i$$$ and $$$j+n$$$. Each edge has a distinct weight.Alice and Bob are playing a game on this graph. First Alice chooses to play as either "increasing" or "decreasing" for herself, and Bob gets the other choice. Then she places a token on any node of the graph. Bob then moves the token along any edge incident to that node. They now take turns playing the following game, with Alice going first.The current player must move the token from the current vertex to some adjacent unvisited vertex. Let $$$w$$$ be the last weight of the last edge that was traversed. The edge that is traversed must be strictly greater than $$$w$$$ if the player is playing as "increasing", otherwise, it must be strictly less. The first player unable to make a move loses.You are given $$$n$$$ and the edge weights of the graph. You can choose to play as either Alice or Bob, and you will play against the judge. You must win all the games for your answer to be judged correct.
null
null
standard output
standard input
PyPy 2
Python
3,500
train_080.jsonl
4899e07de654ffb241a773dd528ec9f0
256 megabytes
["2\n3\n3 1 9\n2 5 7\n6 4 8\n6\n-1\n1\n1\nI 1\n-1"]
PASSED
import sys def stable_marriage(p1, p2): n = len(p1) ret = [-1 for __ in xrange(2*n)] free = [True for __ in xrange(n)] nfree = n def engage(m,w): ret[w+n] = m ret[m] = w+n free[m] = False while nfree > 0: m = next(i for i in xrange(n) if free[i]) idx = 0 while free[m]: w = p1[m][idx] if ret[w+n] == -1: engage(m,w) nfree -= 1 else: m1 = ret[w+n] if p2[w].index(m) < p2[w].index(m1): free[m1] = True ret[m1] = -1 engage(m,w) idx += 1 return ret def process_one(): n = int(raw_input()) grid = [map(int, raw_input().split()) for __ in xrange(n)] print "B" sys.stdout.flush() x,d = raw_input().split() d = int(d) sign = -1 if ((x == 'I') ^ (d <= n)) else 1 partner = stable_marriage( [sorted(range(n), key=lambda x: +sign*grid[i][x]) for i in xrange(n)], [sorted(range(n), key=lambda x: -sign*grid[x][i]) for i in xrange(n)], ) while True: if d == -1: return if d == -2: sys.exit(0) print partner[d-1]+1 sys.stdout.flush() d = int(raw_input()) t = int(raw_input()) for ___ in xrange(t): process_one()
1556989500
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1 2 4\n1 2\n1\n1\n1 2 3 4 5"]
81f4bc9ac72ed39da8614131954d0d99
NoteIn the first test case: If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\{1\}$$$, $$$\{2\}$$$, $$$\{3\}$$$, $$$\{4\}$$$. Since $$$\&amp;$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$. If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\{1, 3\}$$$ and $$$\{2, 4\}$$$: $$$x = a_1 ~ \&amp; ~ a_3$$$ $$$=$$$ $$$a_2 ~ \&amp; ~ a_4$$$ $$$=$$$ $$$4 ~ \&amp; ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation — $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$. If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$. If $$$k = 4$$$, we can make one operation with set $$$\{1, 2, 3, 4\}$$$, because $$$x = a_1 ~ \&amp; ~ a_2 ~ \&amp; ~ a_3 ~ \&amp; ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations: Operation with indices $$$\{1, 3\}$$$: $$$x = a_1 ~ \&amp; ~ a_3$$$ $$$=$$$ $$$13 ~ \&amp; ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$. Operation with indices $$$\{3, 4\}$$$: $$$x = a_3 ~ \&amp; ~ a_4$$$ $$$=$$$ $$$16 ~ \&amp; ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$. Operation with indices $$$\{2, 4\}$$$: $$$x = a_2 ~ \&amp; ~ a_4$$$ $$$=$$$ $$$7 ~ \&amp; ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$. Operation with indices $$$\{1, 2\}$$$: $$$x = a_1 ~ \&amp; ~ a_2$$$ $$$=$$$ $$$4 ~ \&amp; ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\&amp;$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \&amp; ~ y$$$ is a result of operation $$$\&amp;$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} $$$$$$
You are given array $$$a_1, a_2, \ldots, a_n$$$, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter $$$k$$$ ($$$1 \leq k \leq n$$$) as follows: Choose $$$k$$$ distinct array indices $$$1 \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \le n$$$. Calculate $$$x = a_{i_1} ~ \&amp; ~ a_{i_2} ~ \&amp; ~ \ldots ~ \&amp; ~ a_{i_k}$$$, where $$$\&amp;$$$ denotes the bitwise AND operation (notes section contains formal definition). Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.
For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i &lt; 2^{30}$$$) — array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.
standard output
standard input
PyPy 3-64
Python
1,300
train_092.jsonl
7e7a62fc9de0b210b642622ef7f91298
512 megabytes
["5\n4\n4 4 4 4\n4\n13 7 25 19\n6\n3 5 3 1 7 1\n1\n1\n5\n0 0 0 0 0"]
PASSED
def getint(): return [int(i) for i in input().split()] def get(): return int(input()) def getstr(): return [i for i in input().split()] def S(): for test in range(int(input())): solve() import math import itertools as it import bisect import time import collections as ct def solve(): b=[0]*32 n=get() a=getint() for i in a: x=bin(i)[2:] x=x[::-1] for j in range(len(x)): b[j]+=int(x[j]) ans=[int(i) for i in range(1,n+1)] for i in range(1,n+1): for j in range(0,31): if b[j]%i: ans[i-1]=0 for i in range(n): if ans[i]: print(ans[i],end=" ") print() S()
1635143700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["&gt;\n=\n&lt;\n=\n&lt;"]
a4eeaf7252b9115b67b9eca5f2bf621d
NoteThe comparisons in the example are: $$$20 &gt; 19$$$, $$$1000 = 1000$$$, $$$1999 &lt; 2000$$$, $$$1 = 1$$$, $$$99 &lt; 100$$$.
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $$$x$$$ with $$$p$$$ zeros appended to its end.Now Monocarp asks you to compare these two numbers. Can you help him?
For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '&lt;'. If the first number is greater than the second one, print '&gt;'. If they are equal, print '='.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$x_1$$$ and $$$p_1$$$ ($$$1 \le x_1 \le 10^6; 0 \le p_1 \le 10^6$$$) — the description of the first number. The second line of each testcase contains two integers $$$x_2$$$ and $$$p_2$$$ ($$$1 \le x_2 \le 10^6; 0 \le p_2 \le 10^6$$$) — the description of the second number.
standard output
standard input
PyPy 3-64
Python
900
train_090.jsonl
3068e6f323024f5174400f4f5839664a
256 megabytes
["5\n2 1\n19 0\n10 2\n100 1\n1999 0\n2 3\n1 0\n1 0\n99 0\n1 2"]
PASSED
import math for _ in range(int(input())): x1, p1 = map(int, input().split()) x2, p2 = map(int, input().split()) a=math.log(x1/x2, 10) if a>(p2-p1): print(">") elif a<(p2-p1): print("<") else: print("=")
1638369300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5 6 3", "5 12 23 34 36 27 18 11 6 1"]
126eaff19fe69989cd5b588503a0fed8
null
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest step has number 1, and the highest step has number n. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down"  —  to the direction "up".Olga always moves to the next step in the direction which is shown on the pointer above the step. If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the n-th) step. In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second. For each step find the duration of the dream if Olga was at this step at the beginning of the dream.Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.
Print n numbers, the i-th of which is equal either to the duration of Olga's dream or to  - 1 if Olga never goes beyond the stairs, if in the beginning of sleep she was on the i-th step.
The first line contains single integer n (1 ≤ n ≤ 106) — the number of steps on the stairs. The second line contains a string s with the length n — it denotes the initial direction of pointers on the stairs. The i-th character of string s denotes the direction of the pointer above i-th step, and is either 'U' (it means that this pointer is directed up), or 'D' (it means this pointed is directed down). The pointers are given in order from bottom to top.
standard output
standard input
Python 3
Python
2,400
train_059.jsonl
2fdee68b4cc319ff695a85c873ee20d9
256 megabytes
["3\nUUD", "10\nUUDUDUUDDU"]
PASSED
n=int(input()) string = input() q1,q2,B,C=[],[],[],[] A=0 for i in range(n): if string[i] == "D": q1.append(i) else: q2.append(n-1-i) for i in range(len(q1)): A+=(q1[i]-i)*2+1 B.append(A) A=0 temp = [] for i in range(len(q2)): A+=(q2[len(q2)-1-i]-i)*2+1 C.append(A) C.reverse() B=list(map(str,B+C)) print(" ".join(B))
1477922700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2", "4", "6"]
2ff789ae0095bb7ff0e747b0d4df59bc
NoteFor first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $$$2$$$ (e.g. at the moment $$$2$$$).In the second example, all lights are initially on. So the answer is $$$4$$$.
It is a holiday season, and Koala is decorating his house with cool lights! He owns $$$n$$$ lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $$$a_i$$$ and $$$b_i$$$. Light with parameters $$$a_i$$$ and $$$b_i$$$ will toggle (on to off, or off to on) every $$$a_i$$$ seconds starting from the $$$b_i$$$-th second. In other words, it will toggle at the moments $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \cdot a_i$$$ and so on.You know for each light whether it's initially on or off and its corresponding parameters $$$a_i$$$ and $$$b_i$$$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. Here is a graphic for the first example.
Print a single integer — the maximum number of lights that will ever be on at the same time.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of lights. The next line contains a string $$$s$$$ of $$$n$$$ characters. The $$$i$$$-th character is "1", if the $$$i$$$-th lamp is initially on. Otherwise, $$$i$$$-th character is "0". The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 5$$$)  — the parameters of the $$$i$$$-th light.
standard output
standard input
Python 3
Python
1,300
train_012.jsonl
935fc042813d682016d9659abed59f30
256 megabytes
["3\n101\n3 3\n3 2\n3 1", "4\n1111\n3 4\n5 2\n3 1\n3 2", "6\n011100\n5 3\n5 5\n2 4\n3 5\n4 2\n1 5"]
PASSED
import math n = int(input()) ini = str(input()) ab = [] maxon = 0 for i in range(n): abi = list(map(int, input().split())) ab.append(abi) for t in range(1, 241): res = [] i = 0 for abi in ab: if t-abi[1] <= 0: res.append(int(ini[i])==0) else: res.append(math.ceil((t-abi[1])/abi[0])%2==int(ini[i])) i = i + 1 maxon = max(maxon, n-sum(res)) if maxon == n: break; print(maxon)
1568466300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["4\n2\n0"]
e1de1e92fac8a6db3222c0d3c26843d8
NoteIn the first sample, one of the optimal solutions is:$$$a = \{2, 0, 1, 1, 0, 2, 1\}$$$$$$b = \{1, 0, 1, 0, 2, 1, 0\}$$$$$$c = \{2, 0, 0, 0, 0, 2, 0\}$$$In the second sample, one of the optimal solutions is:$$$a = \{0, 2, 0, 0, 0\}$$$$$$b = \{1, 1, 0, 1, 0\}$$$$$$c = \{0, 2, 0, 0, 0\}$$$In the third sample, the only possible solution is:$$$a = \{2\}$$$$$$b = \{2\}$$$$$$c = \{0\}$$$
You are given two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \begin{cases} a_i b_i &amp; \mbox{if }a_i &gt; b_i \\ 0 &amp; \mbox{if }a_i = b_i \\ -a_i b_i &amp; \mbox{if }a_i &lt; b_i \end{cases}$$$You'd like to make $$$\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?
For each test case, print the maximum possible sum of the sequence $$$c$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 &gt; 0$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.
standard output
standard input
PyPy 2
Python
1,100
train_003.jsonl
cad704dd4ed3566b651c43dbef08f063
256 megabytes
["3\n2 3 2\n3 3 1\n4 0 1\n2 3 0\n0 0 1\n0 0 1"]
PASSED
t = int(raw_input()) for _ in range(t): x1, y1, z1 = map(int, raw_input().strip().split(" ")) x2, y2, z2 = map(int, raw_input().strip().split(" ")) answer = 0 num_twos = min(z1, y2) answer += 2*num_twos z1 -= num_twos y2 -= num_twos a = min(x1, z2) x1 -= a z2 -= a b = min(x2, y1) x2 -= b y1 -= b answer -= 2*min(y1, z2) print(answer)
1598020500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES", "NO"]
159f163dd6da4668f01a66ddf746eb93
null
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 ≤ i ≤ n) there exist two numbers xi and ki that denote a possible transformation: ki kilograms of material xi can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material xi. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.For each i (1 ≤ i ≤ n) Igor knows that the experiment requires ai kilograms of material i, and the laboratory contains bi kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Print YES if it is possible to conduct an experiment. Otherwise print NO.
The first line contains one integer number n (1 ≤ n ≤ 105) — the number of materials discovered by Berland chemists. The second line contains n integer numbers b1, b2... bn (1 ≤ bi ≤ 1012) — supplies of BerSU laboratory. The third line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 1012) — the amounts required for the experiment. Then n - 1 lines follow. j-th of them contains two numbers xj + 1 and kj + 1 that denote transformation of (j + 1)-th material (1 ≤ xj + 1 ≤ j, 1 ≤ kj + 1 ≤ 109).
standard output
standard input
Python 3
Python
2,300
train_020.jsonl
810501201fd3d73fd805eeb1d2947516
256 megabytes
["3\n1 2 3\n3 2 1\n1 1\n1 1", "3\n3 2 1\n1 2 3\n1 1\n1 2"]
PASSED
import sys # @profile def main(): f = sys.stdin # f = open('input.txt', 'r') # fo = open('log.txt', 'w') n = int(f.readline()) # b = [] # for i in range(n): # b.append() b = list(map(int, f.readline().strip().split(' '))) a = list(map(int, f.readline().strip().split(' '))) # return b = [b[i] - a[i] for i in range(n)] c = [[0, 0]] for i in range(n - 1): line = f.readline().strip().split(' ') c.append([int(line[0]), int(line[1])]) # print(c) for i in range(n - 1, 0, -1): # print(i) fa = c[i][0] - 1 if b[i] >= 0: b[fa] += b[i] else: b[fa] += b[i] * c[i][1] if b[fa] < -1e17: print('NO') return 0 # for x in b: # fo.write(str(x) + '\n') if b[0] >= 0: print('YES') else: print('NO') main()
1504623900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["2\n1\n3\n2", "1\n1\n1"]
907893a0a78a7444d26bdd793d9c7499
null
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.For every ball print the number of the basket where it will go according to Valeric's scheme.Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
Print n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of balls and baskets, correspondingly.
standard output
standard input
Python 3
Python
1,300
train_013.jsonl
bad5c6e4ada7d55066d0b84ff5b06e1e
256 megabytes
["4 3", "3 1"]
PASSED
n, m = map(int, input().split()) a = [] t = 1 if m % 2 else -1 for i in range(m): a.append(int(m/2)+int(m%2)+t*int((i+1)/2)) t *= -1 for i in range(n): print(a[int(i%m)])
1339342200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
5 seconds
["3 1 0\n2 0"]
f07a78f9317b2d897aca2d9ca62837f0
NoteIn the first test case, If we delete the nodes in order $$$1 \rightarrow 2 \rightarrow 3$$$ or $$$1 \rightarrow 3 \rightarrow 2$$$, then the obtained sequence will be $$$a = [2, 0, 0]$$$ which has $$$\operatorname{gcd}$$$ equals to $$$2$$$. If we delete the nodes in order $$$2 \rightarrow 1 \rightarrow 3$$$, then the obtained sequence will be $$$a = [1, 1, 0]$$$ which has $$$\operatorname{gcd}$$$ equals to $$$1$$$. If we delete the nodes in order $$$3 \rightarrow 1 \rightarrow 2$$$, then the obtained sequence will be $$$a = [1, 0, 1]$$$ which has $$$\operatorname{gcd}$$$ equals to $$$1$$$. If we delete the nodes in order $$$2 \rightarrow 3 \rightarrow 1$$$ or $$$3 \rightarrow 2 \rightarrow 1$$$, then the obtained sequence will be $$$a = [0, 1, 1]$$$ which has $$$\operatorname{gcd}$$$ equals to $$$1$$$. Note that here we are counting the number of different sequences, not the number of different orders of deleting nodes.
You are given a tree with $$$n$$$ nodes. As a reminder, a tree is a connected undirected graph without cycles.Let $$$a_1, a_2, \ldots, a_n$$$ be a sequence of integers. Perform the following operation exactly $$$n$$$ times: Select an unerased node $$$u$$$. Assign $$$a_u :=$$$ number of unerased nodes adjacent to $$$u$$$. Then, erase the node $$$u$$$ along with all edges that have it as an endpoint. For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the number, modulo $$$998\,244\,353$$$, of different sequences $$$a_1, a_2, \ldots, a_n$$$ that satisfy the following conditions: it is possible to obtain $$$a$$$ by performing the aforementioned operations exactly $$$n$$$ times in some order. $$$\operatorname{gcd}(a_1, a_2, \ldots, a_n) = k$$$. Here, $$$\operatorname{gcd}$$$ means the greatest common divisor of the elements in $$$a$$$.
For each test case, print $$$n$$$ integers in a single line, where for each $$$k$$$ from $$$1$$$ to $$$n$$$, the $$$k$$$-th integer denotes the answer when $$$\operatorname{gcd}$$$ equals to $$$k$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). Each of the next $$$n - 1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$) indicating 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 $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,600
train_087.jsonl
9a6a374d9337b890aac0a54f793cc58f
256 megabytes
["2\n3\n2 1\n1 3\n2\n1 2"]
PASSED
import sys input = lambda: sys.stdin.readline().rstrip("\r\n") MOD = 998244353 t = int(input()) while t > 0: t -= 1 n = int(input()) g = [[] for i in range(n)] for i in range(n - 1): x, y = map(int, input().split()) g[x - 1] += [y - 1] g[y - 1] += [x - 1] f = [0] * n parent = [0] * n f[1] = pow(2, n - 1, MOD) order = [0] for v in order: for u in g[v]: if u != parent[v]: parent[u] = v order += [u] def dfs(k): size = [0] * n for v in reversed(order): if size[v] % k == 0: if v != 0: size[parent[v]] += 1 elif v == 0 or (size[v] + 1) % k != 0: return False return True for i in range(2, n): if (n - 1) % i == 0: f[i] = int(dfs(i)) h = [0] * (n + 1) for i in range(n - 1, 0, -1): h[i] = f[i] for j in range(i * 2, n, i): h[i] -= h[j] print(*(x for x in h[1:n + 1]))
1627569300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3 2 1", "-1", "3 2 1"]
46e7cd6723553d2c6d6c6d0999a5b5fc
null
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
standard output
standard input
Python 3
Python
1,500
train_021.jsonl
a224c103dbbde749d324089fc8ebeb64
256 megabytes
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
PASSED
from collections import defaultdict n,m = list(map(int,input().split())) if m==0: for i in range(1,n+1,3): print(i,i+1,i+2) else: graph = defaultdict(list) for i in range(m): u,v = list(map(int,input().split())) graph[u].append(v) graph[v].append(u) visited = [False for i in range(n)] d = {} for i in range(n): if visited[i]==False: cur = i+1 q = [] q.append(cur) d[cur] = [cur] while q!=[]: u = q.pop(0) for k in graph[u]: if visited[k-1]==False: visited[k-1] = True q.append(k) d[cur].append(k) for i in d: d[i] = list(set(d[i])) f = 0 for i in d: if len(d[i])>3: f = 1 break if f==1: print(-1) else: cnt1,cnt2,cnt3 = [],[],[] for i in d: if len(d[i])==1: cnt1.append(d[i]) elif len(d[i])==2: cnt2.append(d[i]) elif len(d[i])==3: cnt3.append(d[i]) if (len(cnt1)-len(cnt2))%3!=0 or len(cnt1)<len(cnt2): print(-1) else: for i in cnt3: print(*i) for i in range(len(cnt2)): x = cnt1[i]+cnt2[i] print(*x) for i in range(len(cnt2),len(cnt1),3): x = cnt1[i]+cnt1[i+1]+cnt1[i+2] print(*x)
1366903800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1\n4\n4\n4\n3\n1"]
e0a1dc397838852957d0e15ec98d5efe
NoteHere are the images for the example test cases. Blue dots stand for the houses, green — possible positions for the exhibition.First test case.Second test case. Third test case. Fourth test case. Fifth test case. Sixth test case. Here both houses are located at $$$(0, 0)$$$.
You and your friends live in $$$n$$$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.
For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.
First line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 1000)$$$. Next $$$n$$$ lines describe the positions of the houses $$$(x_i, y_i)$$$ $$$(0 \leq x_i, y_i \leq 10^9)$$$. It's guaranteed that the sum of all $$$n$$$ does not exceed $$$1000$$$.
standard output
standard input
Python 3
Python
1,500
train_110.jsonl
f10555b5b32416d10d803cdd54f66b8a
256 megabytes
["6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0"]
PASSED
import os DEBUG = 'DEBUG' in os.environ def debug(*args): if DEBUG: print(">", *args) def solution(houses): if len(houses) == 1: return 1 housesX = [] housesY = [] for house in houses: housesX.append(house[0]) housesY.append(house[1]) housesX.sort() housesY.sort() leftX = -1 rightX = -1 topY = -1 bottomY = -1 # if even # 0 1 2 3 if len(houses) % 2 == 0: leftX = housesX[len(houses) // 2 - 1] rightX = housesX[len(houses) // 2] bottomY = housesY[len(houses) // 2 - 1] topY = housesY[len(houses) // 2] return (rightX - leftX + 1) * (topY - bottomY + 1) # if odd # 0 1 2 if len(houses) % 2 == 1: return 1 debug(leftX, rightX, topY, bottomY) return "NO" for t in range(int(input())): houses = [] for t2 in range(int(input())): houses.append(list(map(int, input().split()))) print(solution(houses))
1613658900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["0.9230769231\n0.6666666667"]
c8a42b3dfa8c9ee031ab4efd4c90bd58
NoteDish from the first sample looks like this:Dish from the second sample looks like this:
Have you ever tasted Martian food? Well, you should.Their signature dish is served on a completely black plate with the radius of R, flat as a pancake.First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians.Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians.Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius.Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border.To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the k-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy?
Print t lines — the radius of the k-th portion of the Green Bull Terrier for each test. The absolute or relative error of the answer should not exceed 10 - 6.
The first line contains integer t (1 ≤ t ≤ 104) — amount of testcases. Each of the following t lines contain three positive integers: the radii of the plate and a portion of the Golden Honduras R and r (1 ≤ r &lt; R ≤ 104) and the number k (1 ≤ k ≤ 104). In the pretests 1 ≤ k ≤ 2.
standard output
standard input
Python 3
Python
2,800
train_007.jsonl
4fea16271eab35b5a5bea72728e35584
256 megabytes
["2\n4 3 1\n4 2 2"]
PASSED
#!/usr/bin/env python3 def solve(R,r,k): # Thanks to Numberphile's "Epic circles" video # Use the formula for radii of circles in Pappus chain r = r / R n = k answer = ((1-r)*r)/(2*((n**2)*((1-r)**2)+r)) # Note that in a Pappus chain the diameter of the circle is 1, so we need to scale up: answer = 2*R * answer print("%.10f" % answer) t = int(input()) for i in range(t): R,r,k = map(int, input().split()) solve(R,r,k)
1303226100
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
4 seconds
["6"]
fe29785b8286b6d74318c0eaa6ae2bb5
null
You are given a tree T consisting of n vertices. A number is written on each vertex; the number written on vertex i is ai. Let's denote the function I(x, y) as the difference between maximum and minimum value of ai on a simple path connecting vertices x and y.Your task is to calculate .
Print one number equal to .
The first line contains one integer number n (1 ≤ n ≤ 106) — the number of vertices in the tree. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the numbers written on the vertices. Then n - 1 lines follow. Each line contains two integers x and y denoting an edge connecting vertex x and vertex y (1 ≤ x, y ≤ n, x ≠ y). It is guaranteed that these edges denote a tree.
standard output
standard input
PyPy 2
Python
2,400
train_077.jsonl
fb8172d92186c320ce8a43053757fb03
256 megabytes
["4\n2 2 3 1\n1 2\n1 3\n1 4"]
PASSED
import sys range = xrange input = raw_input # returns order such that A[order[i]] <= A[order[i + 1]] def sqrtsorted(A, maxval = 10**6): asqrt = int((maxval)**0.5 + 2) blocks1 = [[] for _ in range(asqrt)] blocks2 = [[] for _ in range(asqrt)] for i in range(len(A)): blocks1[A[i] % asqrt].append(i) for block in blocks1: for i in block: blocks2[A[i]//asqrt].append(i) ret = [] for block in blocks2: ret += block return ret class DisjointSetUnion: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n def find(self, a): acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] return a def join(self, a, b): a, b = self.find(a), self.find(b) if a != b: if self.size[a] < self.size[b]: a, b = b, a self.parent[b] = a self.size[a] += self.size[b] return (self.size[a] - self.size[b]) * (self.size[b]) inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 A = inp[ii:ii + n]; ii += n order = sqrtsorted(A) mapper = [0]*n for i in range(n): mapper[order[i]] = i B = [A[i] for i in order] coupl = [[] for _ in range(n)] for _ in range(n - 1): u = mapper[inp[ii] - 1]; ii += 1 v = mapper[inp[ii] - 1]; ii += 1 coupl[u].append(v) coupl[v].append(u) total = 0 dsu = DisjointSetUnion(n) for node in range(n): s = 0 for nei in coupl[node]: if nei < node: s += dsu.join(node, nei) total += s * B[node] dsu = DisjointSetUnion(n) for node in reversed(range(n)): s = 0 for nei in coupl[node]: if nei > node: s += dsu.join(node, nei) total -= s * B[node] print total
1515848700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["4", "15"]
f6cd855ceda6029fc7d14daf2c9bb7dc
NoteIn the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i &lt; j and pi &gt; pj.
Print a single integer — the number of inversions in the resulting sequence.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation.
standard output
standard input
Python 2
Python
2,100
train_018.jsonl
da026a653cedbfd25e981e854ae2253b
256 megabytes
["2\n4 2\n1 4", "3\n1 6\n3 4\n2 5"]
PASSED
from sys import stdin from itertools import repeat def main(): n = int(stdin.readline()) data = map(int, stdin.read().split(), repeat(10, 2 * n)) d = {} for i in xrange(n): a, b = data[i*2], data[i*2+1] d[a], d[b] = d.get(b, b), d.get(a, a) s = d.keys() s.sort() idx = {} for i, x in enumerate(s, 1): idx[x] = i ans = 0 b = [0] * (2 * n + 1) ans = 0 for i, x in enumerate(s): y = d[x] z = idx[y] r = 0 while z > 0: r += b[z] z = z & (z - 1) ans += i - r if y > x: ans += y - x - idx[y] + idx[x] elif y < x: ans += x - y - idx[x] + idx[y] z = idx[y] while z <= 2 * n: b[z] += 1 z += z - (z & (z - 1)) print ans main()
1430411400
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
6 seconds
["3\n4\n2\n4\n1"]
e93981ba508fec99c8ae3e8aa480dd52
NoteConsider the example test case.The answer to the first query is $$$3$$$, as there are three suitable substrings: $$$s[3\dots6]$$$, $$$s[3\dots4]$$$ and $$$s[5\dots6]$$$.The answer to the second query is $$$4$$$. The substrings are $$$s[3\dots6]$$$, $$$s[3\dots4]$$$, $$$s[5\dots6]$$$ and $$$s[2\dots7]$$$.After the third query, the string becomes ")(..())()".The answer to the fourth query is $$$2$$$. The substrings are $$$s[5\dots6]$$$ and $$$s[2\dots7]$$$. Note that $$$s[3\dots6]$$$ is not a simple RBS anymore, as it starts with ".".The answer to the fifth query is $$$4$$$. The substrings are $$$s[5\dots6]$$$, $$$s[2\dots7]$$$, $$$s[8\dots9]$$$ and $$$s[2\dots9]$$$.After the sixth query, the string becomes ")(....)()".After the seventh query, the string becomes ")......()".The answer to the eighth query is $$$1$$$. The substring is $$$s[8\dots9]$$$.
This is the hard version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version."Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice and entertain the owner in various ways.The developers from "Interplanetary Software, Inc." have recently decided to release a software update for these robots. After the update, the cats must solve the problems about bracket sequences. One of the problems is described below. First, we need to learn a bit of bracket sequence theory. Consider the strings that contain characters "(", ")" and ".". Call a string regular bracket sequence (RBS), if it can be transformed to an empty string by one or more operations of removing either single "." characters, or a continuous substring "()". For instance, the string "(()(.))" is an RBS, as it can be transformed to an empty string with the following sequence of removals: "(()(.))" $$$\rightarrow$$$ "(()())" $$$\rightarrow$$$ "(())" $$$\rightarrow$$$ "()" $$$\rightarrow$$$ "". We got an empty string, so the initial string was an RBS. At the same time, the string ")(" is not an RBS, as it is not possible to apply such removal operations to it.An RBS is simple if this RBS is not empty, doesn't start with ".", and doesn't end with ".".Denote the substring of the string $$$s$$$ as its sequential subsegment. In particular, $$$s[l\dots r] = s_ls_{l+1}\dots s_r$$$, where $$$s_i$$$ is the $$$i$$$-th character of the string $$$s$$$.Now, move on to the problem statement itself. You are given a string $$$s$$$, initially consisting of characters "(" and ")". You need to answer the following queries: Given two indices, $$$l$$$ and $$$r$$$ ($$$1 \le l &lt; r \le n$$$). It's guaranteed that the $$$l$$$-th character is equal to "(", the $$$r$$$-th character is equal to ")", and the characters between them are equal to ".". Then the $$$l$$$-th and the $$$r$$$-th characters must be set to ".". Given two indices, $$$l$$$ and $$$r$$$ ($$$1 \le l &lt; r \le n$$$), and it's guaranteed that the substring $$$s[l\dots r]$$$ is a simple RBS. You need to find the number of substrings in $$$s[l\dots r]$$$ such that they are simple RBS. In other words, find the number of index pairs $$$i$$$, $$$j$$$ such that $$$l \le i &lt; j \le r$$$ and $$$s[i\dots j]$$$ is a simple RBS. You are an employee in "Interplanetary Software, Inc." and you were given the task to teach the cats to solve the problem above, after the update.
For each query, print a single integer in a separate line, the number of substrings that are simple RBS. The answers must be printed in the same order as the queries are specified in the input.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 3\cdot10^5$$$, $$$1 \le q \le 3\cdot10^5$$$), the length of the string, and the number of queries. The second line contains the string $$$s$$$, consisting of $$$n$$$ characters "(" and ")". Each of the following $$$q$$$ lines contains three integers $$$t$$$, $$$l$$$ and $$$r$$$ ($$$t \in \{1, 2\}$$$, $$$1 \le l &lt; r \le n$$$), the queries you need to answer. It is guaranteed that all the queries are valid and correspond to the problem statements.
standard output
standard input
PyPy 3
Python
2,800
train_085.jsonl
a9b2b77cf19d54b922a79a6b22d43040
256 megabytes
["9 8\n)(()())()\n2 3 6\n2 2 7\n1 3 4\n2 2 7\n2 2 9\n1 5 6\n1 2 7\n2 8 9"]
PASSED
''' E2. Cats on the Upgrade (hard version) https://codeforces.com/contest/1625/problem/E2 ''' import io, os, sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str output = sys.stdout.write DEBUG = os.environ.get('debug') not in [None, '0'] if DEBUG: from inspect import currentframe, getframeinfo from re import search def debug(*args): if not DEBUG: return frame = currentframe().f_back s = getframeinfo(frame).code_context[0] r = search(r"\((.*)\)", s).group(1) vnames = r.split(', ') var_and_vals = [f'{var}={val}' for var, val in zip(vnames, args)] prefix = f'{currentframe().f_back.f_lineno:02d}: ' print(f'{prefix}{", ".join(var_and_vals)}') INF = float('inf') # ----------------------------------------- from typing import List class SegmentTreeInfo: def __init__(self, parent=INF, sum=0, cnt=0): self.parent = parent # over all ( inside this substring, what's the leftmost parent idx self.cnt = cnt # over all ( inside this substring, how many are direct child of self.parent self.sum = sum # over all ( inside this substring that are direct child of self.parent, what's the sum of their subtree RBS count (recursive, subtree lies inside substring but not necessarily all covered by segtree segment) def __add__(self, other): res = SegmentTreeInfo() # if have same par, obvious # if l is par of r, this step adds r's direct children (l's grandchildren) # l's direct children includes r and already counted in l.sum res.sum = self.sum + other.sum if self.parent < other.parent: res.parent, res.cnt = self.parent, self.cnt elif self.parent > other.parent: res.parent, res.cnt = other.parent, other.cnt else: res.parent, res.cnt = self.parent, self.cnt + other.cnt return res def __repr__(self): return f'SegmentTreeInfo(parent={self.parent},sum={self.sum},cnt={self.cnt})' class SegmentTree: def __init__(self, lo: int, hi: int, init_arr: List[SegmentTreeInfo] = None) -> None: '''init segtree intervals, optionally with data''' self.lo, self.hi = lo, hi self.mi = mi = (lo + hi) // 2 self.info = SegmentTreeInfo() if lo == hi and init_arr: self.info = init_arr[lo] elif lo < hi: self.left = SegmentTree(lo, mi) self.right = SegmentTree(mi+1, hi) def query(self, qlo: int, qhi: int) -> SegmentTreeInfo: '''range query qlo..qhi intersect self.lo..self.hi''' if qlo < self.lo or qhi > self.hi: return SegmentTreeInfo() if qlo == self.lo and qhi == self.hi: return self.info res = SegmentTreeInfo() if qlo <= self.mi: res += self.left.query(qlo, min(qhi, self.mi)) if qhi > self.mi: res += self.right.query(max(qlo, self.mi+1), qhi) return res def update(self, qi: int, v: SegmentTreeInfo): '''update this segment and children when data[qi]=v''' if qi < self.lo or qi > self.hi: return if qi == self.lo == self.hi: self.info = v else: if qi <= self.mi: self.left.update(qi, v) else: self.right.update(qi, v) self.info = SegmentTreeInfo() # update from child if self.left: self.info += self.left.info if self.right: self.info += self.right.info def solve(): N, Q = map(int, input().split()) S = input().decode().strip() # build bracket tree: go down 1 level for (, up for ) # each vertex is a RBS # par[i] = index of parent ( for S[i] = (; might be set when bracket invalid # match[i] = index of matching bracket of S[i]; only set when bracket valid par = [-1] * N match = [-1] * N stack = [] for i, c in enumerate(S): if c == '(': stack.append(i) elif stack: # skip unmatched brackets j = stack.pop() match[i], match[j] = j, i if j > 0: if S[j-1] == '(': par[j] = j-1 # parent and child elif match[j-1] != -1: par[j] = par[match[j-1]] # siblings # count num children under each RBS deg = [0] * N for i in range(N): if par[i] != -1: # opening bracket deg[par[i]] += 1 # update at each RBS opening segtree = SegmentTree(0, N-1) for i in range(N): if i < match[i]: # opening bracket segtree.update(i, SegmentTreeInfo(par[i], deg[i] * (deg[i] + 1) // 2, 1)) # segtree.query(l, r) = num RBS within S[l..r] res = [] for _ in range(Q): op, l, r = map(int, input().split()) l -= 1 r -= 1 if op == 1: assert deg[l] == 0 # (.) segtree.update(l, SegmentTreeInfo()) pl = par[l] if pl != -1: deg[pl] -= 1 segtree.update(pl, SegmentTreeInfo(par[pl], deg[pl] * (deg[pl] + 1) // 2, 1)) else: v = segtree.query(l, r) res.append(v.sum + v.cnt * (v.cnt + 1) // 2) print('\n'.join(map(str, res))) if __name__ == '__main__': solve()
1641989100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["0", "5554443330", "-1"]
b263917e47e1c84340bcb1c77999fd7e
NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.
On a single line print the answer to the problem. If such number does not exist, then you should print -1.
A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.
standard output
standard input
Python 3
Python
1,600
train_013.jsonl
bcef56c06439c10a9f397b5b0d7dd437
256 megabytes
["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"]
PASSED
def ans(): global answered global final if(answered): return sum = 0 for i in final: sum+=i if(sum==0): print(0) answered = True return for i in final: print(i,end="") print() answered = True answered = False N = int(input()) A = list(int(i) for i in input().split()) A.sort() A.reverse() final = A if(A[N-1]!=0): print (-1) answered = True else: sum = 0 for i in A: sum+=i if(sum%3==0): ans() elif(sum%3==2): for i in reversed(range(len(A))): if(A[i]%3==2): final.pop(i) ans() break count = 0 for i in reversed(range(len(A))): if(A[i]%3==1): final.pop(i) count+=1 if(count==2): ans() break elif(sum%3==1): for i in reversed(range(len(A))): if(A[i]%3==1): A.pop(i) ans() break count = 0 for i in reversed(range(len(A))): if(A[i]%3==2): A.pop(i) count+=1 if(count==2): ans() break if(not answered): print (-1)
1343662200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["11\n0\n13\n60\n58"]
9fcc55a137b5ff021fdc8e1e867ce856
NoteIn the first test case, one possible strategy is as follows: Buy a good key for $$$5$$$ coins, and open chest $$$1$$$, receiving $$$10$$$ coins. Your current balance is $$$0 + 10 - 5 = 5$$$ coins. Buy a good key for $$$5$$$ coins, and open chest $$$2$$$, receiving $$$10$$$ coins. Your current balance is $$$5 + 10 - 5 = 10$$$ coins. Use a bad key and open chest $$$3$$$. As a result of using a bad key, the number of coins in chest $$$3$$$ becomes $$$\left\lfloor \frac{3}{2} \right\rfloor = 1$$$, and the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{1}{2} \right\rfloor = 0$$$. Your current balance is $$$10 + 1 = 11$$$. Use a bad key and open chest $$$4$$$. As a result of using a bad key, the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{0}{2} \right\rfloor = 0$$$. Your current balance is $$$11 + 0 = 11$$$. At the end of the process, you have $$$11$$$ coins, which can be proven to be maximal.
There are $$$n$$$ chests. The $$$i$$$-th chest contains $$$a_i$$$ coins. You need to open all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.There are two types of keys you can use to open a chest: a good key, which costs $$$k$$$ coins to use; a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, including the chest it is about to open. The halving operation will round down to the nearest integer for each chest halved. In other words using a bad key to open chest $$$i$$$ will do $$$a_i = \lfloor{\frac{a_i}{2}\rfloor}$$$, $$$a_{i+1} = \lfloor\frac{a_{i+1}}{2}\rfloor, \dots, a_n = \lfloor \frac{a_n}{2}\rfloor$$$; any key (both good and bad) breaks after a usage, that is, it is a one-time use. You need to use in total $$$n$$$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.During the process, you are allowed to go into debt; for example, if you have $$$1$$$ coin, you are allowed to buy a good key worth $$$k=3$$$ coins, and your balance will become $$$-2$$$ coins.Find the maximum number of coins you can have after opening all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.
For each test case output a single integer  — the maximum number of coins you can obtain after opening the chests in order from chest $$$1$$$ to chest $$$n$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$; $$$0 \leq k \leq 10^9$$$) — the number of chests and the cost of a good key respectively. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 10^9$$$)  — the amount of coins in each chest. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_086.jsonl
7a3f8606cd2126032a9416cac5e3ef54
256 megabytes
["5\n\n4 5\n\n10 10 3 1\n\n1 2\n\n1\n\n3 12\n\n10 10 29\n\n12 51\n\n5 74 89 45 18 69 67 67 11 96 23 59\n\n2 57\n\n85 60"]
PASSED
import sys from array import array input = lambda: sys.stdin.buffer.readline().decode().strip() inp = lambda dtype: [dtype(x) for x in input().split()] for _ in range(int(input())): n, k = inp(int) a = array('i', inp(int)) dp = [array('q', [-10 ** 18] * 30) for _ in range(2)] dp[1][0] = 0 for i in range(n): dp[i & 1][0] = dp[(i - 1) & 1][0] + a[i] - k for j in range(1, min(29, i + 1) + 1): cur = a[i] // (1 << j) dp[i & 1][j] = max(dp[(i - 1) & 1][j] + cur - k, dp[(i - 1) & 1][j - 1] + cur) if i + 1 >= 29: dp[i & 1][-1] = max(dp[i & 1][-1], dp[(i - 1) & 1][-1]) print(max(dp[(n - 1) & 1]))
1657636500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["? 1 3 2\n\n? 1 2 3\n\n! 2"]
e66101a49797b1e244dd9709dc21e657
NoteThe tree in the example is as follows:The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).The hack corresponding to the example would look like:3 22 3 1
The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect $$$k$$$-ary tree if each vertex is either a leaf (has no children) or has exactly $$$k$$$ children. Also, in perfect $$$k$$$-ary tree all leafs must have same depth.For example, the picture below illustrates perfect binary tree with $$$15$$$ vertices:There is a perfect $$$k$$$-ary tree with $$$n$$$ nodes. The nodes are labeled with distinct integers from $$$1$$$ to $$$n$$$, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.You are allowed to make at most $$$60 \cdot n$$$ queries of the following type: "? $$$a$$$ $$$b$$$ $$$c$$$", the query returns "Yes" if node with label $$$b$$$ lies on the path from $$$a$$$ to $$$c$$$ and "No" otherwise. Both $$$a$$$ and $$$c$$$ are considered to be lying on the path from $$$a$$$ to $$$c$$$.When you are ready to report the root of the tree, print "! $$$s$$$", where $$$s$$$ is the label of the root of the tree. It is possible to report the root only once and this query is not counted towards limit of $$$60 \cdot n$$$ queries.
null
null
standard output
standard input
Python 3
Python
2,400
train_023.jsonl
8c0e7d24018a1ac63e2aa2cc3feaad96
256 megabytes
["3 2\n\nNo\n\nYes"]
PASSED
from math import log from random import randint import sys n, k = map(int, input().split()) lg = int(log(n, k)) * 2 + 1 have = set() def find_diam(): a = randint(1, n) b = randint(a, n) #print('New') if (a == b) or (a, b) in have: return [] have.add((a, b)) cnt = 2 was = [a, b] for i in range(1, n + 1): if i == a or i == b: continue if cnt + n - i + 1 < lg: break print('?', a, i, b, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if ans == 1: was.append(i) if cnt == lg: break if cnt == lg: return was return [] res = [] while res == []: res = find_diam() a, b = res[0], res[1] betw = res[2:] bad = set() for v in betw: cnt = 1 if v in bad: continue g1 = [] g2 = [] for i in betw: if i == v: continue print('?', a, i, v, flush=True) sys.stdout.flush() ans = 1 if input()[0] == 'Y' else 0 cnt += ans if ans == 1: g1.append(i) else: g2.append(i) if cnt == lg // 2: print('!', v) sys.stdout.flush() exit(0) if cnt < lg // 2: for el in g1: bad.add(el) else: for el in g2: bad.add(el) exit(12)
1542901500
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["3\n2\n1\n1\n1\n5\n1\n1\n3\n3"]
ca817fe0a97e2d8a6bcfcb00103b6b6d
Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting: swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$; swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.
You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.
For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.
The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test. The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,400
train_102.jsonl
ad6619e0a1d9b2b8e2ba1cdd91cb4561
256 megabytes
["10\n\n8 2\n\nbxyaxzay\n\n6 3\n\naaaaaa\n\n6 1\n\nabcdef\n\n6 6\n\nabcdef\n\n3 2\n\ndxd\n\n11 2\n\nabcabcabcac\n\n6 6\n\nsipkic\n\n7 2\n\neatoohd\n\n3 1\n\nllw\n\n6 2\n\nbfvfbv"]
PASSED
for t in range(int(input())): n, k = map(int, input().split()) s = input() d = dict() for i in s: if i in d: d[i] += 1 else: d[i] = 1 counter_2 = 0 for i in d: counter_2 += d[i]//2 ans = (counter_2//k)*2 extra = n - (ans*k) ans += 1 if extra >= k else 0 print(ans)
1641825300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["2 1\n4 3\n2 2"]
601853dd471f5dc7f72fa42bfcf0c858
null
There is a rectangular grid of size $$$n \times m$$$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $$$(i, j)$$$ is $$$c_{i, j}$$$. You are also given a map of directions: for each cell, there is a direction $$$s_{i, j}$$$ which is one of the four characters 'U', 'R', 'D' and 'L'. If $$$s_{i, j}$$$ is 'U' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i - 1, j)$$$; if $$$s_{i, j}$$$ is 'R' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i, j + 1)$$$; if $$$s_{i, j}$$$ is 'D' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i + 1, j)$$$; if $$$s_{i, j}$$$ is 'L' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i, j - 1)$$$. It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied. Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction. Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $$$(1, 1)$$$ and $$$(1, 2)$$$, but if the grid is "RLL" then you cannot place robots in cells $$$(1, 1)$$$ and $$$(1, 3)$$$ because during the first second both robots will occupy the cell $$$(1, 2)$$$. The robots make an infinite number of moves.Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.You have to answer $$$t$$$ independent test cases.
For each test case, print two integers — the maximum number of robots you can place to satisfy all the conditions described in the problem statement and the maximum number of black cells occupied by robots before all movements if the number of robots placed is maximized. Note that you can place robots only before all movements.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 &lt; nm \le 10^6$$$) — the number of rows and the number of columns correspondingly. The next $$$n$$$ lines contain $$$m$$$ characters each, where the $$$j$$$-th character of the $$$i$$$-th line is $$$c_{i, j}$$$ ($$$c_{i, j}$$$ is either '0' if the cell $$$(i, j)$$$ is black or '1' if the cell $$$(i, j)$$$ is white). The next $$$n$$$ lines also contain $$$m$$$ characters each, where the $$$j$$$-th character of the $$$i$$$-th line is $$$s_{i, j}$$$ ($$$s_{i, j}$$$ is 'U', 'R', 'D' or 'L' and describes the direction of the cell $$$(i, j)$$$). It is guaranteed that the sum of the sizes of fields does not exceed $$$10^6$$$ ($$$\sum nm \le 10^6$$$).
standard output
standard input
PyPy 3
Python
2,200
train_006.jsonl
5433dcd5ae14bf9cf19f831ff5d477dd
256 megabytes
["3\n1 2\n01\nRL\n3 3\n001\n101\n110\nRLL\nDLD\nULL\n3 3\n000\n000\n000\nRRD\nRLD\nULL"]
PASSED
from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): def solve(): n,m = map(int, input().split()) colour = [] for _ in range(n): colour.append(input()) dir = [] for _ in range(n): dir.append(input()) eqgrid = [[None]*m for _ in range(n)] next_path = 0 pathsizes = [] eclass_has_black = [] totls = 0 for ni in range (n): for nj in range(m): if eqgrid[ni][nj]: continue i = ni j = nj path = [] count = 1 while not eqgrid[i][j]: path.append((i,j)) eqgrid[i][j] = (count, next_path) count += 1 if dir[i][j] == 'L': j -=1 elif dir[i][j] == 'R': j +=1 elif dir[i][j] == 'U': i -=1 else: i+=1 ppos, found_path = eqgrid[i][j] if found_path == next_path: ls = count - ppos eclass_has_black.append([False]*ls) for ix, (k, l) in enumerate(path[::-1]): eq = ix%ls eqgrid[k][l] = (eq, next_path) if colour[k][l] == '0': eclass_has_black[next_path][eq] = True pathsizes.append(ls) totls += ls next_path += 1 else: ls = pathsizes[found_path] for ix, (k, l) in enumerate(path[::-1], 1): eq = (ix + ppos) % ls eqgrid[k][l] = (eq, found_path) if colour[k][l] == '0': eclass_has_black[found_path][eq] = True blacks = len([b for p in eclass_has_black for b in p if b]) print(totls, blacks) q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main()
1586788500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1 2 3\n2 1\n2 1 3\n-1\n1\n3 2 1 4"]
667c5af27db369257039d0832258600d
NoteIn the first test case for permutation $$$p = [1, 2, 3]$$$ Vasya should write $$$next = [2, 3, 4]$$$, because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation.In the third test case, any permutation can be the answer because all numbers $$$next_i$$$ are lost.In the fourth test case, there is no satisfying permutation, so the answer is $$$-1$$$.
Vasya has written some permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, so for all $$$1 \leq i \leq n$$$ it is true that $$$1 \leq p_i \leq n$$$ and all $$$p_1, p_2, \ldots, p_n$$$ are different. After that he wrote $$$n$$$ numbers $$$next_1, next_2, \ldots, next_n$$$. The number $$$next_i$$$ is equal to the minimal index $$$i &lt; j \leq n$$$, such that $$$p_j &gt; p_i$$$. If there is no such $$$j$$$ let's let's define as $$$next_i = n + 1$$$.In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $$$next_i$$$ are completely lost! If for some $$$i$$$ the value $$$next_i$$$ is lost, let's say that $$$next_i = -1$$$.You are given numbers $$$next_1, next_2, \ldots, next_n$$$ (maybe some of them are equal to $$$-1$$$). Help Vasya to find such permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, that he can write it to the notebook and all numbers $$$next_i$$$, which are not equal to $$$-1$$$, will be correct.
Print $$$T$$$ lines, in $$$i$$$-th of them answer to the $$$i$$$-th test case. If there is no such permutations $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, that Vasya could write, print the only number $$$-1$$$. In the other case print $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$, separated by spaces ($$$1 \leq p_i \leq n$$$). All defined values of $$$next_i$$$ which are not equal to $$$-1$$$ should be computed correctly $$$p_1, p_2, \ldots, p_n$$$ using defenition given in the statement of the problem. If there exists more than one solution you can find any of them.
The first line contains one integer $$$t$$$ — the number of test cases ($$$1 \leq t \leq 100\,000$$$). Next $$$2 \cdot t$$$ lines contains the description of test cases,two lines for each. The first line contains one integer $$$n$$$ — the length of the permutation, written by Vasya ($$$1 \leq n \leq 500\,000$$$). The second line contains $$$n$$$ integers $$$next_1, next_2, \ldots, next_n$$$, separated by spaces ($$$next_i = -1$$$ or $$$i &lt; next_i \leq n + 1$$$). It is guaranteed, that the sum of $$$n$$$ in all test cases doesn't exceed $$$500\,000$$$. In hacks you can only use one test case, so $$$T = 1$$$.
standard output
standard input
PyPy 2
Python
2,100
train_019.jsonl
c613dad11d5b1e8baf36061434b5232b
256 megabytes
["6\n3\n2 3 4\n2\n3 3\n3\n-1 -1 -1\n3\n3 4 -1\n1\n2\n4\n4 -1 4 5"]
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') t=int(input()) for u in xrange(t): n=int(input()) a=list(map(int,input().split())) long=[] lens=0 fucked=False for i in xrange(n): if a[i]==-1: if lens==0: a[i]=i+2 else: a[i]=long[-1] else: if lens==0 or a[i]<long[-1]: long.append(a[i]) lens+=1 elif lens>0 and a[i]>long[-1]: fucked=True if lens>0: if i>=long[-1]-2: long.pop() lens-=1 if fucked: print(-1) else: back={} for i in xrange(n+1): back[i+1]=[] for i in xrange(n): back[a[i]].append(i+1) perm=[0]*n q=[n+1] big=n while q!=[]: newq=[] for guy in q: for boi in back[guy]: perm[boi-1]=big big-=1 newq+=back[guy] q=newq perm=[str(guy) for guy in perm] print(" ".join(perm))
1557671700
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["3\n1 5 4", "-1"]
9f13d3d0266b46e4201ea6a2378d1b71
NoteConsider the examples above.In the first example, the group of spiders is illustrated on the picture below: We choose the two-legged, the ten-legged and the $$$16$$$-legged spiders. It's not hard to see that each pair may weave a web with enough durability, as $$$2 \oplus 10 = 8 \ge 8$$$, $$$2 \oplus 16 = 18 \ge 8$$$ and $$$10 \oplus 16 = 26 \ge 8$$$.This is not the only way, as you can also choose, for example, the spiders with indices $$$3$$$, $$$4$$$, and $$$6$$$.In the second example, no pair of spiders can weave the web with durability $$$1024$$$ or more, so the answer is $$$-1$$$.
Binary Spiders are species of spiders that live on Mars. These spiders weave their webs to defend themselves from enemies.To weave a web, spiders join in pairs. If the first spider in pair has $$$x$$$ legs, and the second spider has $$$y$$$ legs, then they weave a web with durability $$$x \oplus y$$$. Here, $$$\oplus$$$ means bitwise XOR.Binary Spiders live in large groups. You observe a group of $$$n$$$ spiders, and the $$$i$$$-th spider has $$$a_i$$$ legs.When the group is threatened, some of the spiders become defenders. Defenders are chosen in the following way. First, there must be at least two defenders. Second, any pair of defenders must be able to weave a web with durability at least $$$k$$$. Third, there must be as much defenders as possible.Scientists have researched the behaviour of Binary Spiders for a long time, and now they have a hypothesis that they can always choose the defenders in an optimal way, satisfying the conditions above. You need to verify this hypothesis on your group of spiders. So, you need to understand how many spiders must become defenders. You are not a Binary Spider, so you decided to use a computer to solve this problem.
In the first line, print a single integer $$$\ell$$$ ($$$2 \le \ell \le n$$$), the maximum possible amount of defenders. In the second line, print $$$\ell$$$ integers $$$b_i$$$, separated by a single space ($$$1 \le b_i \le n$$$) — indices of spiders that will become defenders. If there exists more than one way to choose the defenders, print any of them. Unfortunately, it may appear that it's impossible to choose the defenders. In this case, print a single integer $$$-1$$$.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3\cdot10^5$$$, $$$0 \le k \le 2^{30} - 1$$$), the amount of spiders in the group and the minimal allowed durability of a web. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \le a_i \le 2^{30}-1$$$) — the number of legs the $$$i$$$-th spider has.
standard output
standard input
PyPy 3-64
Python
2,300
train_085.jsonl
a81fe9e0c138b0bd7a50f1db754766ac
256 megabytes
["6 8\n2 8 4 16 10 14", "6 1024\n1 2 3 1 4 0"]
PASSED
import sys import os from io import BytesIO, IOBase from _collections import defaultdict from random import randrange # 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") if sys.version_info[0] < 3: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) f = sys.stdin if os.environ.get('USER') == "loic": f = open("data.in") line = lambda: f.readline().split() ui = lambda: int(line()[0]) ti = lambda: map(int,line()) li = lambda: list(ti()) ####################################################################### def max_xor_of_pair(arr): m = 0 mask = 0 s = set() d = {} pair = (-1,-1) for i in range(30, -1, -1): mask |= (1 << i) tmp = m | (1 << i) for a in arr: pref = a & mask s.add(pref) # d[pref] = a for pref in s: if tmp ^ pref in s: m = tmp # pair = (d[pref], d[tmp ^ pref]) break s.clear() return m,pair def solve(): if K == 0: return str(N) + "\n" + " ".join(map(str,range(1,N+1))) pref = defaultdict(list) msb = len(bin(K)) - 2 for a in A: val = a >> msb pref[val].append(a) res = [] for l in pref.values(): if len(l) == 1: res.extend(l) else: m,pair = max_xor_of_pair(l) if m >= K: # res.append(pair[0]) # res.append(pair[1]) s = set(l) for val in s: if val ^ m in s: res += [val,val^m] break else: res.append(l[0]) if len(res) < 2: return str(-1) mp = {v:i for i,v in enumerate(A)} return str(len(res)) + "\n" + " ".join(str(mp[v]+1) for v in res) for test in range(1,1+1): N,K = ti() A = li() print(solve()) f.close()
1641989100
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
6 seconds
["4"]
507e3e805e91a91e5130f53588e62dab
NoteAfter the trap is set, the new energy requirement for the first Corridor may be either smaller, larger, or equal to the old energy requiremenet.In the example, if the energy of the first Corridor is set to $$$4$$$ or less, then the Daleks may use the set of Corridors $$$\{ \{ 1,2 \}, \{ 2,3 \} \}$$$ (in particular, if it were set to less than $$$4$$$, then this would be the only set of Corridors that they would use). However, if it is larger than $$$4$$$, then they will instead use the set $$$\{ \{2,3\}, \{3,1\} \}$$$.
Heidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a carefully chosen Time Corridor. She knows that tinkering with the Time Vortex is dangerous, so she consulted the Doctor on how to proceed. She has learned the following: Different Time Corridors require different amounts of energy to keep stable. Daleks are unlikely to use all corridors in their invasion. They will pick a set of Corridors that requires the smallest total energy to maintain, yet still makes (time) travel possible between any two destinations (for those in the know: they will use a minimum spanning tree). Setting the trap may modify the energy required to keep the Corridor stable. Heidi decided to carry out a field test and deploy one trap, placing it along the first Corridor. But she needs to know whether the Daleks are going to use this corridor after the deployment of the trap. She gives you a map of Time Corridors (an undirected graph) with energy requirements for each Corridor.For a Corridor $$$c$$$, $$$E_{max}(c)$$$ is the largest $$$e \le 10^9$$$ such that if we changed the required amount of energy of $$$c$$$ to $$$e$$$, then the Daleks may still be using $$$c$$$ in their invasion (that is, it belongs to some minimum spanning tree). Your task is to calculate $$$E_{max}(c_1)$$$ for the Corridor $$$c_1$$$ that Heidi plans to arm with a trap, which is the first edge in the graph.
Output a single integer: $$$E_{max}(c_1)$$$ for the first Corridor $$$c_1$$$ from the input.
The first line contains integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$n - 1 \leq m \leq 10^6$$$), number of destinations to be invaded and the number of Time Corridors. Each of the next $$$m$$$ lines describes a Corridor: destinations $$$a$$$, $$$b$$$ and energy $$$e$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$, $$$0 \leq e \leq 10^9$$$). It's guaranteed, that no pair $$$\{a, b\}$$$ will repeat and that the graph is connected — that is, it is possible to travel between any two destinations using zero or more Time Corridors.
standard output
standard input
Python 2
Python
1,900
train_026.jsonl
3dcbeb2f45226a36dd152e22fb99488c
128 megabytes
["3 3\n1 2 8\n2 3 3\n3 1 4"]
PASSED
from __future__ import division, print_function def main(): class DSU: def __init__ (self,n): self.parent=list(range(n)) self.size=[1]*n self.count_sets=n def find(self,u): to_update=[] while u!=self.parent[u]: to_update.append(u) u=self.parent[u] for v in to_update: self.parent[v]=u return u def union(self,u,v): u=self.find(u) v=self.find(v) if u==v: return if self.size[u] < self.size[v]: u,v=v,u self.count_sets-=1 self.parent[v]=u self.size[u]+=self.size[v] def set_size(self,a): return self.size[self.find(a)] n,m=map(int,input().split()) a,b,e=map(int,input().split()) a-=1 b-=1 l1=[] flag1=0 flag2=0 for i in range(m-1): x,y,z=map(int,input().split()) l1.append((z,x-1,y-1)) l1.sort() import sys my_dsu=DSU(n) for item in l1: if my_dsu.find(item[1])!=my_dsu.find(item[2]): my_dsu.union(item[1],item[2]) if my_dsu.find(a)==my_dsu.find(b): print(item[0]) sys.exit() print(10**9) py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main()
1562483100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["4", "2"]
2ed58a84bd705e416cd25f139f904d68
NoteIn the first sample, you can obtain a nested sequence of $$$4$$$ rubber bands($$$1$$$, $$$2$$$, $$$5$$$, and $$$6$$$) by the conversion shown below. Of course, there are other conversions exist to make a nested sequence of $$$4$$$ rubber bands. However, you cannot make sequence of $$$5$$$ or more nested rubber bands with given tree. You can see one of the possible conversions for the second sample below.
You have a tree of $$$n$$$ vertices. You are going to convert this tree into $$$n$$$ rubber bands on infinitely large plane. Conversion rule follows: For every pair of vertices $$$a$$$ and $$$b$$$, rubber bands $$$a$$$ and $$$b$$$ should intersect if and only if there is an edge exists between $$$a$$$ and $$$b$$$ in the tree. Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect. Now let's define following things: Rubber band $$$a$$$ includes rubber band $$$b$$$, if and only if rubber band $$$b$$$ is in rubber band $$$a$$$'s area, and they don't intersect each other. Sequence of rubber bands $$$a_{1}, a_{2}, \ldots, a_{k}$$$ ($$$k \ge 2$$$) are nested, if and only if for all $$$i$$$ ($$$2 \le i \le k$$$), $$$a_{i-1}$$$ includes $$$a_{i}$$$. This is an example of conversion. Note that rubber bands $$$5$$$ and $$$6$$$ are nested. It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.
Print the answer.
The first line contains integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the number of vertices in tree. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$) — it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. It is guaranteed that given graph forms tree of $$$n$$$ vertices.
standard output
standard input
PyPy 2
Python
2,700
train_019.jsonl
bc4e721e99e76e8d11f3c5c29816f7ae
256 megabytes
["6\n1 3\n2 3\n3 4\n4 5\n4 6", "4\n1 2\n2 3\n3 4"]
PASSED
FAST_IO = 1 if FAST_IO: import io, sys, atexit rr = iter(sys.stdin.read().splitlines()).next sys.stdout = _OUTPUT_BUFFER = io.BytesIO() @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) else: rr = raw_input rri = lambda: int(rr()) rrm = lambda: map(int, rr().split()) ### def solve(N, graph): VISIT, DO = 0, 1 stack = [[DO, 0, -1], [VISIT, 0, -1]] res = [None] * N ans = 0 while stack: cmd, node, par = stack.pop() if cmd == VISIT: for nei in graph[node]: if nei != par: stack.append([DO, nei, node]) stack.append([VISIT, nei, node]) else: white = black = 0 best = [] bestb = [] for nei in graph[node]: if nei != par: w, b = res[nei] white = max(white, b) black = max(black, w, b) best.append(max(w, b)) best.sort(reverse=True) if len(best) >= 3: best.pop() bestb.append(b) bestb.sort(reverse=True) if len(bestb) >= 3: bestb.pop() white += 1 black += len(graph[node]) - 2 ans = max(ans, sum(bestb) + 1, sum(best) + len(graph[node]) - 2) res[node] = [white, black] return ans N = rri() graph = [[] for _ in xrange(N)] for _ in xrange(N-1): u, v=rrm() u -= 1 v -= 1 graph[u].append(v) graph[v].append(u) print solve(N, graph)
1586700300
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
1 second
["YES\n11640\n1024", "YES\n2842545891539\n28171911281811000", "NO"]
695418026140545863313f5f3cc1bf00
null
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.
In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them. If there is no answer, print in a single line "NO" (without the quotes).
The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).
standard output
standard input
Python 2
Python
1,700
train_002.jsonl
e7307ec36730a59a230d6c52b843010c
256 megabytes
["116401024\n97 1024", "284254589153928171911281811000\n1009 1000", "120\n12 1"]
PASSED
from sys import stdin, stdout def main_mine(): key = stdin.readline().strip() a, b = map(int, stdin.readline().split()) l = len(key) n = map(int, key) div_b = [] div = 0 mod10 = 1 for d in reversed(n): div = (div + d * mod10) % b mod10 = 10 * mod10 % b div_b.append(div) div = 0 cut_ind = 0 for i, d in enumerate(n[:-1]): div = (div * 10 + d) % a if n[i+1] and not div and not div_b[l - i - 2]: cut_ind = i+1 break if cut_ind: stdout.write('YES\n') stdout.write(key[:cut_ind] + '\n') stdout.write(key[cut_ind:] + '\n') else: stdout.write('NO\n') from itertools import repeat def main(): a = stdin.readline().strip() b, c = map(int, stdin.readline().split()) l = len(a) n = map(int, a, repeat(10, l)) y = [] k = 0 d = 1 for i in xrange(l-1, -1, -1): k = (k + n[i] * d) % c d = d * 10 % c y.append(k) y.reverse() k = 0 for i, x in enumerate(n[:-1]): k = (k * 10 + x) % b if n[i+1] and not k and not y[i+1]: stdout.write("YES\n") stdout.write(str(a[:i+1]) + "\n") stdout.write(str(a[i+1:]) + "\n") return stdout.write("NO") main()
1416733800
[ "number theory", "math", "strings" ]
[ 0, 0, 0, 1, 1, 0, 1, 0 ]
1 second
["6", "2", "120"]
dbc9b7ff6f495fe72a747d79006488c3
NoteIn the first example, $$$[1, 2, 3]$$$ is a valid permutation as we can consider the index with value $$$3$$$ as the source and index with value $$$1$$$ as the sink. Thus, after conversion we get a beautiful array $$$[2, 2, 2]$$$, and the total cost would be $$$2$$$. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.In the second example, $$$[0, 0, 4, 4]$$$ and $$$[4, 4, 0, 0]$$$ are balanced permutations.In the third example, all permutations are balanced.
An array is called beautiful if all the elements in the array are equal.You can transform an array using the following steps any number of times: Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i,j \leq n$$$), and an integer $$$x$$$ ($$$1 \leq x \leq a_i$$$). Let $$$i$$$ be the source index and $$$j$$$ be the sink index. Decrease the $$$i$$$-th element by $$$x$$$, and increase the $$$j$$$-th element by $$$x$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index are $$$a_i-x$$$ and $$$a_j+x$$$ respectively. The cost of this operation is $$$x \cdot |j-i| $$$. Now the $$$i$$$-th index can no longer be the sink and the $$$j$$$-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step $$$3$$$.For example, array $$$[0, 2, 3, 3]$$$ can be transformed into a beautiful array $$$[2, 2, 2, 2]$$$ with total cost $$$1 \cdot |1-3| + 1 \cdot |1-4| = 5$$$.An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.You are given an array $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo $$$10^9 + 7$$$.
Output a single integer — the number of balanced permutations modulo $$$10^9+7$$$.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
standard output
standard input
PyPy 3-64
Python
2,300
train_088.jsonl
af5d509b026485193816964ca9791ba9
256 megabytes
["3\n1 2 3", "4\n0 4 0 4", "5\n0 11 12 13 14"]
PASSED
from operator import mod import os,sys from random import randint, shuffle from io import BytesIO, IOBase from collections import defaultdict,deque,Counter from bisect import bisect_left,bisect_right from heapq import heappush,heappop from functools import lru_cache from itertools import accumulate, permutations import math # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split())) # for _ in range(int(input())): # n, k = list(map(int, input().split())) # if k > (n - 1) // 2: # print(-1) # else: # l, r = 1, n # a = [] # for i in range(2 * k): # if i % 2 == 0: # a.append(l) # l += 1 # else: # a.append(r) # r -= 1 # for i in range(r, l - 1, -1): # a.append(i) # print(*a) # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split())) # x = a[0] # for i in range(n): # x &= a[i] # cnt = 0 # for i in range(n): # if a[i] == x: # cnt += 1 # if cnt < 2: # print(0) # else: # ans = cnt * (cnt - 1) # mod = 10 ** 9 + 7 # for i in range(1, n - 1): # ans = ans * i % mod # print(ans) # mod = 10 ** 9 + 7 # ans = [[0] * 200020 for _ in range(10)] # ans[0][0] = 1 # for j in range(200019): # for i in range(9): # ans[i + 1][j + 1] = ans[i][j] # ans[0][j + 1] = (ans[0][j + 1] + ans[9][j]) % mod # ans[1][j + 1] = (ans[1][j + 1] + ans[9][j]) % mod # for _ in range(int(input())): # n, m = list(map(int, input().split())) # res = 0 # while n: # x = n % 10 # for i in range(10): # res += ans[i][m + x] # n //= 10 # print(res % mod) # for _ in range(int(input())): # n, p = list(map(int, input().split())) # a = list(map(int, input().split())) # id = [i for i in range(n)] # id.sort(key=lambda x : a[x]) # vis = [0] * n # ans = p * (n - 1) # for i in range(n): # x = id[i] # if a[x] >= p: break # if vis[x] == 1: continue # vis[x] = 1 # l = x - 1 # r = x + 1 # while r < n and a[r] % a[x] == 0 and vis[r] == 0: # vis[r] = 1 # r += 1 # while l >= 0 and a[l] % a[x] == 0 and vis[l] == 0: # vis[l] = 1 # l -= 1 # if r > x + 1: # vis[r - 1] = 0 # if l < x - 1: # vis[l + 1] = 0 # ans -= (r - l - 2) * (p - a[x]) # print(ans) mod = 10 ** 9 + 7 N = 200010 fac = [1] * N for i in range(2, N): fac[i] = fac[i - 1] * i % mod invfac = [1] * N invfac[N - 1] = pow(fac[N - 1], mod - 2, mod) for i in range(N - 1)[::-1]: invfac[i] = invfac[i + 1] * (i + 1) % mod def c(i, j): return fac[i] * invfac[j] * invfac[i - j] % mod def solve(): n = int(input()) a = list(map(int, input().split())) if sum(a) % n: print(0) return mean = sum(a) // n x = l = r = 0 cnt1 = Counter() cnt2 = Counter() cnt = Counter(sorted(a)) for i in range(n): if a[i] == mean: x += 1 elif a[i] < mean: cnt1[a[i]] += 1 l += 1 else: cnt2[a[i]] += 1 r += 1 if l <= 1 or r <= 1: ans = fac[n] for i in cnt: ans = ans * invfac[cnt[i]] % mod print(ans) return ans = fac[l] for i in cnt1: ans = ans * invfac[cnt1[i]] % mod ans = ans * fac[r] % mod for i in cnt2: ans = ans * invfac[cnt2[i]] % mod ans = ans * c(n, x) % mod print(ans * 2 % mod) solve()
1618151700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n2 3", "1\n1"]
5ec62d1ab7bd3b14ec3f1508ca327134
NoteIn the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them.In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step.
Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.
In the first line print the minimum number of steps required to make all pairs of guests friends. In the second line print the ids of guests, who are selected at each step. If there are multiple solutions, you can output any of them.
The first line contains two integers n and m (1 ≤ n ≤ 22; ) — the number of guests at the party (including Arseny) and the number of pairs of people which are friends. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n; u ≠ v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.
standard output
standard input
PyPy 3
Python
2,400
train_027.jsonl
c0f811ea6bb1db4648e6cf9d8c2d24d6
256 megabytes
["5 6\n1 2\n1 3\n2 3\n2 5\n3 4\n4 5", "4 4\n1 2\n1 3\n1 4\n3 4"]
PASSED
from collections import defaultdict def count(x): c=0 while x > 0: c+=1 x &= (x-1) return c n,m=map(int,input().split()) g=defaultdict(list) for _ in range(m): u, v = map(int,input().split()) u-=1;v-=1 g[u].append(v) g[v].append(u) mask1=0;mask2=0;MAX=(1<<n)-1 a=[0]*(1 << n) dp=[MAX]*(1 << n) if m == (n*(n-1))//2: print(0) exit(0) for i,j in g.items(): mask1 = (1 << i);mask2=0;mask2 |= mask1 for k in j: mask2 |= (1 << k) dp[mask2]=mask1 a[mask1]=mask2 for i in range(0,(1 << n)-1): if dp[i] != MAX: #print('HEllo') temp = dp[i] ^ i for j in range(n): if temp & (1 << j) != 0: nmask = i | a[(1 << j)] dp[nmask]=dp[i] | (1 << j) if count(dp[i] | (1 << j)) < count(dp[nmask]) else dp[nmask] ans = [] for i in range(n): if dp[-1] & (1 << i) != 0: ans.append(i+1) print(len(ans)) print(*ans)
1514037900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4\n3\n0\n8"]
2b611e202c931d50d8a260b2b45d4cd7
NoteIn the first example, the correct pairs are: ($$$1, 4$$$), ($$$4,1$$$), ($$$3, 6$$$), ($$$6, 3$$$).In the second example, the correct pairs are: ($$$1, 2$$$), ($$$2, 1$$$), ($$$3, 3$$$).
You are given three positive (greater than zero) integers $$$c$$$, $$$d$$$ and $$$x$$$. You have to find the number of pairs of positive integers $$$(a, b)$$$ such that equality $$$c \cdot lcm(a, b) - d \cdot gcd(a, b) = x$$$ holds. Where $$$lcm(a, b)$$$ is the least common multiple of $$$a$$$ and $$$b$$$ and $$$gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
For each test case, print one integer — the number of pairs ($$$a, b$$$) such that the above equality holds.
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 three integer $$$c$$$, $$$d$$$ and $$$x$$$ ($$$1 \le c, d, x \le 10^7$$$).
standard output
standard input
PyPy 3-64
Python
2,100
train_104.jsonl
a8f61ce25f495e816fe420d0ffc5ee21
512 megabytes
["4\n1 1 3\n4 2 6\n3 3 7\n2 7 25"]
PASSED
import sys input = lambda: sys.stdin.readline().rstrip() MAX = 2*(10**7) + 1 memo = {} def get_divisors(x: int) -> list: if x in memo: return memo[x] factori = [] while x > 1: factori.append(min_fact[x]) x //= min_fact[x] now = [1] factori.sort() for p in factori: nxt = [] for i in now: nxt.append(i*p) if i % p: nxt.append(i) now = nxt memo[x] = now return now def sieve_of_eratosthenes(n): min_fact = [1] * (n + 1) lst = [1] * (n+1) for p in range(2, n + 1): if min_fact[p] > 1: continue for i in range(p, n+1, p): min_fact[i] = p lst[i] *= 2 return min_fact, lst min_fact, lst = sieve_of_eratosthenes(MAX) t = int(input()) for _ in range(t): c, d, x = map(int, input().split()) ans = 0 divs = get_divisors(x) for g in divs: tmp = (x + d*g) if tmp % c == 0: l = tmp // c else: continue if l % g: continue n = l // g ans += lst[n] print(ans)
1616079000
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["2\n0\n1", "0\n0\n2\n0\n0\n2\n1\n0\n1\n1"]
a3e89153f98c139d7e84f2307b128b24
NoteThe following is an explanation of the first example. The graph in the first example. Here is one possible walk for the first query:$$$$$$1 \overset{5}{\rightarrow} 3 \overset{3}{\rightarrow} 2 \overset{1}{\rightarrow} 1 \overset{5}{\rightarrow} 3 \overset{1}{\rightarrow} 4 \overset{2}{\rightarrow} 5.$$$$$$The array of weights is $$$w=[5,3,1,5,1,2]$$$. Now if we take the bitwise AND of every prefix of this array, we get the set $$$\{5,1,0\}$$$. The MEX of this set is $$$2$$$. We cannot get a walk with a smaller length (as defined in the statement).
There is an undirected, connected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. A walk from vertex $$$u$$$ to vertex $$$v$$$ is defined as a sequence of vertices $$$p_1,p_2,\ldots,p_k$$$ (which are not necessarily distinct) starting with $$$u$$$ and ending with $$$v$$$, such that $$$p_i$$$ and $$$p_{i+1}$$$ are connected by an edge for $$$1 \leq i &lt; k$$$.We define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.More formally, let us have $$$[w_1,w_2,\ldots,w_{k-1}]$$$ where $$$w_i$$$ is the weight of the edge between $$$p_i$$$ and $$$p_{i+1}$$$. Then the length of the walk is given by $$$\mathrm{MEX}(\{w_1,\,w_1\&amp; w_2,\,\ldots,\,w_1\&amp; w_2\&amp; \ldots\&amp; w_{k-1}\})$$$, where $$$\&amp;$$$ denotes the bitwise AND operation.Now you must process $$$q$$$ queries of the form u v. For each query, find the minimum possible length of a walk from $$$u$$$ to $$$v$$$.The MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance: The MEX of $$$\{2,1\}$$$ is $$$0$$$, because $$$0$$$ does not belong to the set. The MEX of $$$\{3,1,0\}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the set, but $$$2$$$ does not. The MEX of $$$\{0,3,1,2\}$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the set, but $$$4$$$ does not.
For each query, print one line containing a single integer — the answer to the query.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$; $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2},10^5\right)}$$$). Each of the next $$$m$$$ lines contains three integers $$$a$$$, $$$b$$$, and $$$w$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$; $$$0 \leq w &lt; 2^{30}$$$) indicating an undirected edge between vertex $$$a$$$ and vertex $$$b$$$ with weight $$$w$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$), the description of each query.
standard output
standard input
PyPy 3-64
Python
2,200
train_110.jsonl
2dc6d518f26630ddb8c7a847b998cd3c
256 megabytes
["6 7\n1 2 1\n2 3 3\n3 1 5\n4 5 2\n5 6 4\n6 4 6\n3 4 1\n3\n1 5\n1 2\n5 3", "9 8\n1 2 5\n2 3 11\n3 4 10\n3 5 10\n5 6 2\n5 7 1\n7 8 5\n7 9 5\n10\n5 7\n2 5\n7 1\n6 4\n5 2\n7 6\n4 1\n6 2\n4 7\n2 8"]
PASSED
import sys import os from io import BytesIO, IOBase # 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") if sys.version_info[0] < 3: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) file = sys.stdin if os.environ.get('USER') == "loic": file = open("data.in") line = lambda: file.readline().split() ui = lambda: int(line()[0]) ti = lambda: map(int,line()) li = lambda: list(ti()) ####################################################################### class DSU: def __init__(self, limit): self.link = [-1]*limit self.sz = [1]*limit self.even = [False] * limit def find(self,u): root = u par = u while par != -1: root = par par = self.link[par] par = u while par != root: self.link[par] = root par = self.link[par] return root ''' return True if u and v were not in same group, false otherwise ''' def union(self,u,v): root_u = self.find(u) root_v = self.find(v) if root_u == root_v: return False rank_u = self.sz[root_u] rank_v = self.sz[root_v] if rank_u < rank_v: self.link[root_u] = root_v self.sz[root_v] += self.sz[root_u] else: self.link[root_v] = root_u self.sz[root_u] += self.sz[root_v] return True ''' return size of the component containing u ''' def size(self,u): return self.sz[self.find(u)] def solve(): dsu_zero = [DSU(N) for _ in range(30)] dsu_one = [DSU(N) for _ in range(30)] for j in range(30): zero = dsu_zero[j] one = dsu_one[j] for u,v,w in E: if w >> j & 1: zero.union(u,v) if j > 0 and w & 1: one.union(u,v) even = [False] * N for u,v,w in E: if not w & 1: even[u] = True even[v] = True link = [False] * N for j in range(1,30): dsu = dsu_one[j] for u,v,w in E: if not w & 1: root_u = dsu.find(u) dsu.even[root_u] = True root_v = dsu.find(v) dsu.even[root_v] = True for j in range(1,30): dsu = dsu_one[j] for n in range(N): if not link[n] and dsu.even[dsu.find(n)]: link[n] = True def mex(u,v): for j in range(30): dsu = dsu_zero[j] if dsu.find(u) == dsu.find(v): return 0 if link[u]: return 1 if even[u]: return 1 return 2 res = [] for u,v in Q: res.append(mex(u,v)) return "\n".join(str(v) for v in res) for test in range(1,1+1): N,M = ti() E = [] for _ in range(M): u,v,w = ti() u -= 1 v -= 1 E.append((u,v,w)) Q = [] for _ in range(ui()): u,v = ti() u -= 1 v -= 1 Q.append((u,v)) print(solve()) file.close()
1650206100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["Matching\n2\nIndSet\n1\nIndSet\n2 4\nMatching\n1 15"]
0cca30daffe672caa6a6fdbb6a935f43
NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $$$n$$$.The fourth graph does not have an independent set of size 2, but there is a matching of size 2.
You are given a graph with $$$3 \cdot n$$$ vertices and $$$m$$$ edges. You are to find a matching of $$$n$$$ edges, or an independent set of $$$n$$$ vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.
Print your answer for each of the $$$T$$$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $$$n$$$, on the first line print "Matching" (without quotes), and on the second line print $$$n$$$ integers — the indices of the edges in the matching. The edges are numbered from $$$1$$$ to $$$m$$$ in the input order. If you found an independent set of size $$$n$$$, on the first line print "IndSet" (without quotes), and on the second line print $$$n$$$ integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $$$n$$$, and an independent set of size $$$n$$$, then you should print exactly one of such matchings or exactly one of such independent sets.
The first line contains a single integer $$$T \ge 1$$$ — the number of graphs you need to process. The description of $$$T$$$ graphs follows. The first line of description of a single graph contains two integers $$$n$$$ and $$$m$$$, where $$$3 \cdot n$$$ is the number of vertices, and $$$m$$$ is the number of edges in the graph ($$$1 \leq n \leq 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$). Each of the next $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \leq v_i, u_i \leq 3 \cdot n$$$), meaning that there is an edge between vertices $$$v_i$$$ and $$$u_i$$$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $$$n$$$ over all graphs in a single test does not exceed $$$10^{5}$$$, and the sum of all $$$m$$$ over all graphs in a single test does not exceed $$$5 \cdot 10^{5}$$$.
standard output
standard input
PyPy 3
Python
2,000
train_006.jsonl
8980f99302324d7e031f5fd5b9e94516
256 megabytes
["4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6"]
PASSED
import sys input = sys.stdin.readline def main(): tes = int(input()) for testcase in [0]*tes: n,m = map(int,input().split()) new = [True]*(3*n) res = [] for i in range(1,m+1): u,v = map(int,input().split()) if new[u-1] and new[v-1]: if len(res) < n: res.append(i) new[u-1] = new[v-1] = False if len(res) >= n: print("Matching") print(*res) else: vs = [] for i in range(3*n): if new[i]: vs.append(i+1) if len(vs) >= n: break print("IndSet") print(*vs) if __name__ == '__main__': main()
1564497300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["36\n6"]
6b7a083225f0dd895cc48ca68af695f4
NoteIn the second testcase of the example there are six y-factorizations: { - 4,  - 1}; { - 2,  - 2}; { - 1,  - 4}; {1, 4}; {2, 2}; {4, 1}.
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: There are y elements in F, and all of them are integer numbers; . You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≤ i ≤ y) such that Ai ≠ Bi. Since the answer can be very large, print it modulo 109 + 7.
Print q integers. i-th integer has to be equal to the number of yi-factorizations of xi modulo 109 + 7.
The first line contains one integer q (1 ≤ q ≤ 105) — the number of testcases to solve. Then q lines follow, each containing two integers xi and yi (1 ≤ xi, yi ≤ 106). Each of these lines represents a testcase.
standard output
standard input
Python 3
Python
2,000
train_075.jsonl
fc4e4b92a16a26e9eca55156a8ec3150
256 megabytes
["2\n6 3\n4 2"]
PASSED
from array import array md = 10 ** 9 + 7 def fact_all(N): lp = array('Q', [2]*(N+1)) pr = array('Q', [2]) pra = pr.append for i in range(3, N+1, 2): if lp[i] == 2: lp[i] = i pra(i) for p in pr: ip = i * p if p > lp[i] or ip > N: break lp[ip] = p return lp def cnk(n, k): if k > n//2: k = n - k ans = 1 for i in range(n-k+1, n+1): ans *= i for i in range(2, k+1): ans //= i ans = ans % md return ans def factor(n, lpa=fact_all(10**6)): pws = [] num_ones = 0 dv = lpa[n] while n > 1 and dv * dv <= n: lp = 0 c, o = divmod(n, dv) while o == 0: lp += 1 n = c c, o = divmod(n, dv) if lp == 1: num_ones += 1 else: pws.append(lp) dv = lpa[n] if n > 1: num_ones += 1 # pws.append(1) return pws, num_ones def main(): q = int(input()) for __ in range(q): x, y = input().split() x, y = int(x), int(y) ans = pow(2, y - 1, md) pws, num_ones = factor(x) for f in pws: cm = cnk(f + y - 1, f) ans = (ans * cm) % md if num_ones: ans = (ans * pow(y, num_ones, md)) % md print(ans) if __name__ == '__main__': main()
1511449500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["0.0000000000", "0.0740740741"]
9d55b98c75e703a554051d3088a68e59
NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability .
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?
Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
The first line of input contains a single integer n (2 ≤ n ≤ 2000) — the number of balls in the jar. The second line contains n integers ai (1 ≤ ai ≤ 5000) — the number written on the ith ball. It is guaranteed that no two balls have the same number.
standard output
standard input
PyPy 2
Python
1,800
train_044.jsonl
eb36cec500c3d2faf9c1abf8877b4b2b
256 megabytes
["2\n1 2", "3\n1 2 10"]
PASSED
n , m = input() , map(int,raw_input().split()) a = {} for i in xrange(n-1): for j in xrange(i+1,n): x = abs(m[i]-m[j]) if x in a: a[x]+=1 else: a[x]=1 d = [i for i in a] b = [0]*10005 for i in xrange(len(d)): for j in xrange(i,len(d)): if d[i]==d[j]: b[d[i]+d[j]] += a[d[i]]*a[d[j]] else: b[d[i]+d[j]] += a[d[i]]*a[d[j]]*2 for i in xrange(1,len(b)): b[i]=b[i]+b[i-1] ans=0 for i in xrange(n-1): for j in xrange(i+1,n): ans+=b[abs(m[i]-m[j])-1] den = (n*(n-1)/2)**3 print ans/float(den)
1455384900
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
1 second
["Yes", "No", "Yes"]
cf7bf89a6038586b69d3b8021cee0b27
NoteIn the first example the second point can be removed.In the second example there is no suitable for the condition point.In the third example any point can be removed.
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.
Print "Yes" if there is such a point, "No" — otherwise. You can print every letter in any case (upper or lower).
The first line contains a single positive integer n (2 ≤ n ≤ 105). The following n lines contain coordinates of the points. The i-th of these lines contains two single integers xi and yi (|xi|, |yi| ≤ 109, xi ≠ 0). No two points coincide.
standard output
standard input
PyPy 3
Python
800
train_001.jsonl
61fc6ea722848cad301ddb85324a964c
256 megabytes
["3\n1 1\n-1 -1\n2 -1", "4\n1 1\n2 2\n-1 1\n-2 2", "3\n1 2\n2 1\n4 60"]
PASSED
n=int(input()) countl=0 countr=0 for _ in range(n): a,b=map(int,input().split()) if a<0: countl+=1 else: countr+=1 if min(countl,countr)<=1: print("Yes") else: print("No")
1513008300
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
3 seconds
["1\n3 \n-1\n0\n\n2\n1 2"]
128fb67bf707590cb1b60bceeb7ce598
null
Polycarp has $$$n$$$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of $$$n$$$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of $$$n$$$ words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of $$$n$$$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.
Print answer for all of $$$t$$$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $$$k$$$ ($$$0 \le k \le n$$$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $$$k$$$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $$$1$$$ to $$$n$$$ in the order they appear. If $$$k=0$$$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of words in the Polycarp's set. Next $$$n$$$ lines contain these words. All of $$$n$$$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $$$4\cdot10^6$$$. All words are different. Guaranteed, that the sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $$$4\cdot10^6$$$.
standard output
standard input
PyPy 3
Python
1,900
train_012.jsonl
2154823c2da2f45b62b1e588ff11f789
256 megabytes
["4\n4\n0001\n1000\n0011\n0111\n3\n010\n101\n0\n2\n00000\n00001\n4\n01\n001\n0001\n00001"]
PASSED
k = int(input()) for i in range(k): is_t = set() a = dict() a['00'] = [] a['11'] = [] a['01'] = [] a['10'] = [] n = int(input()) s = [] for i in range(n): b = input() a[b[0] + b[-1]].append(i) s.append(b) is_t.add(b) c = len(a['10']) d = len(a['01']) if c + d == 0: if len(a['00']) == 0 or len(a['11']) == 0: print(0) else: print(-1) elif c > d: ans = [] i = 0 m = (d + c) // 2 while d != m and i < len(a['10']): s1 = s[a['10'][i]] if s1[::-1] not in is_t: d += 1 ans.append(a['10'][i] + 1) i += 1 if d != m: print(-1) else: print(len(ans)) print(*ans) else: ans = [] i = 0 m = (d + c) // 2 while c != m and i < len(a['01']): s1 = s[a['01'][i]] if s1[::-1] not in is_t: c += 1 ans.append(a['01'][i] + 1) i += 1 if c != m: print(-1) else: print(len(ans)) print(*ans)
1576321500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["NO\nYES\nYES\nNO\nYES\nYES"]
73a077e8e715c72e37cf10fca281d3e2
NoteThe state of conveyor with $$$t = 0$$$. Red arrow represents the direction of each belt, and blue figure represents slime.The state of conveyor with $$$t = 1$$$.The state of conveyor with $$$t = 2$$$.
There is a conveyor with $$$120$$$ rows and $$$120$$$ columns. Each row and column is numbered from $$$0$$$ to $$$119$$$, and the cell in $$$i$$$-th row and $$$j$$$-th column is denoted as $$$(i, j)$$$. The top leftmost cell is $$$(0, 0)$$$. Each cell has a belt, and all belts are initially facing to the right.Initially, a slime ball is on the belt of $$$(0, 0)$$$, and other belts are empty. Every second, the state of the conveyor changes as follows: All slime balls on the conveyor move one cell in the direction of the belt at the same time. If there is no cell in the moved position, the slime gets out of the conveyor, and if two slime balls move to the same cell, they merge into one. All belts with slime ball in the previous second change direction at the same time: belts facing to the right become facing to the down, and vice versa. A new slime ball is placed on cell $$$(0, 0)$$$. There are $$$q$$$ queries, each being three integers $$$t$$$, $$$x$$$, and $$$y$$$. You have to find out if there is a slime at the cell $$$(x, y)$$$ after $$$t$$$ seconds from the start. Can you do it?
Print the answer for each test case, one per line. If there is a slime ball in the cell $$$(x, y)$$$ after $$$t$$$ seconds from the initial state, print "YES". Otherwise, print "NO".
The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. The only line of each query contains three integers $$$t$$$, $$$x$$$, and $$$y$$$ ($$$0 \le t \le 10^{18}$$$, $$$0 \le x, y &lt; 120$$$).
standard output
standard input
PyPy 3-64
Python
2,700
train_104.jsonl
495a0ecff1011b3894b7934093b1e3ea
256 megabytes
["6\n\n1 1 0\n\n5 1 3\n\n0 0 0\n\n2 4 5\n\n2 0 2\n\n1547748756 100 111"]
PASSED
#from math import ceil, floor #, gcd, log, factorial, comb, perm, #log10, log2, log, sin, asin, tan, atan, radians #from heapq import heappop,heappush,heapify #heappop(hq), heapify(list) #from collections import defaultdict as dd #mydd=dd(list) for .append #from collections import deque as dq #deque e.g. myqueue=dq(list) #append/appendleft/appendright/pop/popleft #from bisect import bisect as bis #a=[1,3,4,6,7,8] #bis(a,5) --> 3 #import statistics as stat # stat.median(a), mode, mean #from math import ceil, floor import sys input = sys.stdin.readline #print = sys.stdout.write #sys.setrecursionlimit(100000) #default is 1000 ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) #.split(','), default is space #list([0,*map(int,input().split(" "))]) # pad a zero to avoid zero indexing def insr(): s = input() return(list(s[:len(s) - 1])) #################################################### #t=1 q = int(input()) for qc in range(q): t,x,y=map(int, input().split()) # n=inp() # a=inlt() # x=list(input().strip("\n").split()) # s=input().strip("\n") # s=input()[:-1] # s=insr() # occ=dict(); # for i in range(n):occ[i]=[] # for i in range(n): # occ[i].append(inlt()) # a=[] # for i in range(n): # a.append(inlt()) if x+y>t:print('NO');continue if x==y==0:print('YES');continue a=[[0]*122 for i in range(122)] a[0][0]=t-x-y for i in range(x+1): for j in range(y+1): a[i+1][j]+=a[i][j]//2 a[i][j+1]+=(a[i][j]+1)//2 i=0;j=0 while i+j<x+y and i<121 and j<121: if a[i][j]%2: i+=1 else: j+=1 if i==x: print('YES') else: print('NO') #print(*ans,sep=' ')##print("{:.3f}".format(ans)+"%") #:b binary :% eg print("{:6.2%}".format(ans)) #print(" ".join(str(i) for i in ans)) #print(" ".join(map(str,ans))) #seems faster #print(a[0] if a else 0) #prefixsum a=[a1...an] #psa=[0]*(n+1) #for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x+1] e.g. sum 1st 5 items in psa[5] #ASCII<->number ord('f')=102 chr(102)='f' #def binary_search(li, val, lb, ub): # while ((ub-lb)>1): # mid = (lb + ub) // 2 # if li[mid] >= val: # ub = mid # else: # lb = mid # return lb+1 #return index of elements <val in li #def binary_search(li, val, lb, ub): # ans = -1 # while (lb <= ub): # mid = (lb + ub) // 2 # if li[mid] > val: # ub = mid - 1 # elif val > li[mid]: # lb = mid + 1 # else: # ans = mid # return index # break # return ans ########## #def pref(li): # pref_sum = [0] # for i in li: # pref_sum.append(pref_sum[-1] + i) # return pref_sum ########## #def suff(li): # suff_sum = [0] # for i in range(len(li)-1,-1,-1): # suff_sum.insert(0,suff_sum[0] + li[i]) # return suff_sum ############# #def maxSubArraySumI(arr): #Kadane's algorithm with index # max_till_now=arr[0];max_ending=0;size=len(arr) # start=0;end=0;s=0 # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending: # max_till_now=max_ending # start=s;end=i # if max_ending<0: # max_ending=0 # s=i+1 # return max_till_now,start,end ############# avoid max for 2 elements - slower than direct if #def maxSubArraySum(arr): #Kadane's algorithm # max_till_now=arr[0];max_ending=0;size=len(arr) # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending:max_till_now=max_ending # if max_ending<0:max_ending=0 # return max_till_now ############# #def findbits(x): # tmp=[] # while x>0:tmp.append(x%2);x//=2 # tmp.reverse() # return tmp ##############Dijkstra algorithm example #dg=[999999]*(n+1);dg[n]=0;todo=[(0,n)];chkd=[0]*(n+1) #while todo:#### find x with min dg in todo # _,x=hq.heappop(todo) # if chkd[x]:continue # for i in coming[x]:going[i]-=1 # for i in coming[x]: # tmp=1+dg[x]+going[i] # if tmp<dg[i]:dg[i]=tmp;hq.heappush(todo,(dg[i],i)) # chkd[x]=1 ################ # adj swaps to match 2 binary strings: sum_{i=1}^n(abs(diff in i-th prefix sums)) ############### ##s=[2, 3, 1, 4, 5, 3] ##sorted(range(len(s)), key=lambda k: s[k]) ##gives sorted indices [2, 0, 1, 5, 3, 4] ##m= [[3, 4, 6], [2, 4, 8], [2, 3, 4], [1, 2, 3], [7, 6, 7], [1, 8, 2]] ##m.sort(reverse=True,key=lambda k:k[2]) #sorts m according to 3rd elements
1663598100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["YES\nYES\nYES\nYES\nYES\nYES\nNO\nYES", "YES\nYES\nYES\nYES\nYES\nNO\nYES\nNO"]
0cc9671ff72e44bd5921cc0e46ada36c
NoteIn the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe:
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $$$1$$$, $$$2$$$, $$$3$$$, so that each character is painted in at most one color, and the description of the $$$i$$$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $$$i$$$.The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.
Write $$$q$$$ lines. The $$$i$$$-th of them should be YES if the religions could coexist in peace after the $$$i$$$-th evolution, or NO otherwise. You can print each character in any case (either upper or lower).
The first line of the input contains two integers $$$n, q$$$ ($$$1 \leq n \leq 100\,000$$$, $$$1 \leq q \leq 1000$$$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $$$n$$$ consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats: + $$$i$$$ $$$c$$$ ($$$i \in \{1, 2, 3\}$$$, $$$c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$$$: append the character $$$c$$$ to the end of $$$i$$$-th religion description. - $$$i$$$ ($$$i \in \{1, 2, 3\}$$$) – remove the last character from the $$$i$$$-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than $$$250$$$ characters.
standard output
standard input
PyPy 3
Python
2,200
train_026.jsonl
342c6c4cfe6f53639c9998131d3aaa6a
256 megabytes
["6 8\nabdabc\n+ 1 a\n+ 1 d\n+ 2 b\n+ 2 c\n+ 3 a\n+ 3 b\n+ 1 c\n- 2", "6 8\nabbaab\n+ 1 a\n+ 2 a\n+ 3 a\n+ 1 b\n+ 2 b\n+ 3 b\n- 1\n+ 2 z"]
PASSED
import sys input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ n, q = map(int, input().split()) s = '!' + input() nxt = [[n + 1] * (n + 2) for _ in range(26)] for i in range(n - 1, -1, -1): c = ord(s[i + 1]) - 97 for j in range(26): nxt[j][i] = nxt[j][i + 1] nxt[c][i] = i + 1 w = [[-1], [-1], [-1]] idx = lambda i, j, k: i * 65536 + j * 256 + k dp = [0] * (256 * 256 * 256) def calc(fix=None): r = list(map(range, (len(w[0]), len(w[1]), len(w[2])))) if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix])) for i in r[0]: for j in r[1]: for k in r[2]: dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1, nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1, nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1) if i == j == k == 0: dp[idx(i, j, k)] = 0 out = [] for _ in range(q): t, *r = input().split() if t == '+': i, c = int(r[0]) - 1, ord(r[1]) - 97 w[i].append(c) calc(i) else: i = int(r[0]) - 1 w[i].pop() req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)] out.append('YES' if req <= n else 'NO') print(*out, sep='\n')
1556548500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n6"]
787a45f427c2db98b2ddb78925e0e0f1
NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$.
Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.
For each test case, output one integer — the minimum possible difference of weights between the two piles.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 30$$$; $$$n$$$ is even) — the number of coins that Phoenix has.
standard output
standard input
Python 3
Python
800
train_002.jsonl
7d3dee2a0554a46c4963daeaf61c361e
256 megabytes
["2\n2\n4"]
PASSED
no=int(input()) j=[] for r in range(no): weights=[] n=int(input()) for each in range(1,n+ 1): weights.append(pow(2,each)) ans=sum(weights[:n//2]) j.append(ans) for r in j: print(r)
1588343700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["26730", "1115598", "11", "265359409"]
6e093dbcbcaa7c87c9b62546745984db
null
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally, if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$; if $$$p &lt; q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.
Print the answer modulo $$$998\,244\,353$$$.
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. All numbers $$$a_1, a_2, \dots, a_n$$$ are of equal length (that is, they consist of the same number of digits).
standard output
standard input
Python 3
Python
1,500
train_005.jsonl
720d3b34a94690518bc5def3f7d1925f
256 megabytes
["3\n12 33 45", "2\n123 456", "1\n1", "5\n1000000000 1000000000 1000000000 1000000000 1000000000"]
PASSED
def main(): n = int(input()) a = [int(i) for i in input().split()] size = len(str(a[0])) ans = 0; MOD = 998244353 ten = [1] for i in range(1, 21): ten.append(ten[-1] * 10) for i in range(n): for j in range(size): ans += int(str(a[i])[j]) * ten[2 * size - 2 * j - 1] * n ans += int(str(a[i])[j]) * ten[2 * size - 2 * j - 2] * n ans %= MOD print(ans) main()
1563374100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["32"]
08b8dbb6e167db69dc965e8ad4835808
NoteIn the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8.
The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).What is the minimum cost of preparation and printing?
Output the minimum cost of preparation and printing k problems — that is, the minimum possible sum ai1 + ai2 + ... + aik + bj1 + bj2 + ... + bjk, where 1 ≤ i1 &lt; i2 &lt; ... &lt; ik ≤ n, 1 ≤ j1 &lt; j2 &lt; ... &lt; jk ≤ n and i1 ≤ j1, i2 ≤ j2, ..., ik ≤ jk.
The first line of input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an () — the preparation costs. The third line contains n space-separated integers b1, ..., bn () — the printing costs.
standard output
standard input
PyPy 3
Python
2,400
train_001.jsonl
310dc096081dd15a9e2b17c39a3d1557
256 megabytes
["8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1"]
PASSED
from collections import deque from heapq import heappop, heappush class Edge(object): __slots__ = ('x', 'y', 'cap', 'cost', 'inv') def __repr__(self): return '{e.x}-->{e.y} ({e.cap} , {e.cost})'.format(e=self) class MCFP(list): def add(G, x, y, cap, cost): n = max(x, y) + 1 while len(G)<n: G.append([]) e = Edge() ; G[x].append(e) w = Edge() ; G[y].append(w) e.x=x ; e.y=y; e.cap=cap; e.cost=cost ; w.inv=e w.x=y ; w.y=x; w.cap=0; w.cost=-cost ; e.inv=w def solve(G, src, tgt, flowStop=float('inf'), inf=float('inf')): flowVal = flowCost = 0 n = len(G) G.inQ = [0]*n G.phi = h = [0]*n G.prev = p = [None]*n G.dist = d = [inf]*n G.SPFA(src) while p[tgt]!=None and flowVal<flowStop: b = [] ; x = tgt while x!=src: b.append(p[x]) ; x=p[x].x z = min(e.cap for e in b) for e in b: e.cap-=z ; e.inv.cap+=z flowVal += z flowCost += z * (d[tgt] - h[src] + h[tgt]) for i in range(n): if p[i]!=None: h[i]+=d[i] ; d[i]=inf p[tgt] = None G.SPFA(src) return flowVal, flowCost def SPFA(G, src): inQ = G.inQ ; prev = G.prev d = G.dist ; h = G.phi d[src] = 0 Q = deque([src]) while Q: x = Q.popleft() inQ[x] = 0 for e in G[x]: if e.cap <= 0: continue y = e.y ; dy = d[x] + h[x] + e.cost - h[y] if dy < d[y]: d[y] = dy ; prev[y] = e if inQ[y]==0: inQ[y] = 1 if not Q or dy > d[Q[0]]: Q.append(y) else: Q.appendleft(y) return import sys, random ints = (int(x) for x in sys.stdin.read().split()) sys.setrecursionlimit(3000) def main(): n, k = (next(ints) for i in range(2)) a = [next(ints) for i in range(n)] b = [next(ints) for i in range(n)] G = MCFP() src, tgt = 2*n+1, 2*n+2 for i in range(n): G.add(src, i, 1, 0) G.add(i, i+n, 1, a[i]) G.add(i+n, tgt, 1, b[i]) if i+1<n: G.add(i, i+1, n, 0) G.add(i+n, i+n+1, n, 0) flowVal, ans = G.solve(src, tgt, k) assert flowVal == k print(ans) #print(G) return def test(n,k): R = random.Random(0) yield n ; yield k for i in range(n): yield R.randint(1, 10**9) for i in range(n): yield R.randint(1, 10**9) #ints=test(1000, 800) main()
1495958700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nNO\nNO\nYES", "NO\nNO\nYES"]
ac8519dfce1b3b1fafc02820563a2dbd
NoteExplanation of the test from the condition: Initially $$$A=[2,2,1]$$$, $$$B=[0,0,0]$$$. After operation "A 1 3": $$$A=[0,0,0]$$$, $$$B=[0,0,0]$$$ (addition is modulo 3). After operation "A 1 3": $$$A=[1,1,2]$$$, $$$B=[0,0,0]$$$. After operation "B 1 1": $$$A=[1,1,2]$$$, $$$B=[1,0,0]$$$. After operation "B 2 2": $$$A=[1,1,2]$$$, $$$B=[1,1,0]$$$. After operation "A 3 3": $$$A=[1,1,0]$$$, $$$B=[1,1,0]$$$.
One of my most productive days was throwing away 1,000 lines of code.— Ken ThompsonFibonacci addition is an operation on an array $$$X$$$ of integers, parametrized by indices $$$l$$$ and $$$r$$$. Fibonacci addition increases $$$X_l$$$ by $$$F_1$$$, increases $$$X_{l + 1}$$$ by $$$F_2$$$, and so on up to $$$X_r$$$ which is increased by $$$F_{r - l + 1}$$$.$$$F_i$$$ denotes the $$$i$$$-th Fibonacci number ($$$F_1 = 1$$$, $$$F_2 = 1$$$, $$$F_{i} = F_{i - 1} + F_{i - 2}$$$ for $$$i &gt; 2$$$), and all operations are performed modulo $$$MOD$$$.You are given two arrays $$$A$$$ and $$$B$$$ of the same length. We will ask you to perform several Fibonacci additions on these arrays with different parameters, and after each operation you have to report whether arrays $$$A$$$ and $$$B$$$ are equal modulo $$$MOD$$$.
After each operation, print "YES" (without quotes) if the arrays are equal and "NO" otherwise. Letter case does not matter.
The first line contains 3 numbers $$$n$$$, $$$q$$$ and $$$MOD$$$ ($$$1 \le n, q \le 3\cdot 10^5, 1 \le MOD \le 10^9+7$$$) — the length of the arrays, the number of operations, and the number modulo which all operations are performed. The second line contains $$$n$$$ numbers — array $$$A$$$ ($$$0 \le A_i &lt; MOD$$$). The third line also contains $$$n$$$ numbers — array $$$B$$$ ($$$0 \le B_i &lt; MOD$$$). The next $$$q$$$ lines contain character $$$c$$$ and two numbers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — operation parameters. If $$$c$$$ is "A", Fibonacci addition is to be performed on array $$$A$$$, and if it is is "B", the operation is to be performed on $$$B$$$.
standard output
standard input
PyPy 3-64
Python
2,700
train_107.jsonl
0dc4ee3a39acbca3dbdcc3bf2b7fbd08
256 megabytes
["3 5 3\n2 2 1\n0 0 0\nA 1 3\nA 1 3\nB 1 1\nB 2 2\nA 3 3", "5 3 10\n2 5 0 3 5\n3 5 8 2 5\nB 2 3\nB 3 4\nA 1 2"]
PASSED
# import sys # I = lambda: [*map(int, sys.stdin.readline().split())] import io,os read = io.BytesIO(os.read(0, os.fstat(0).st_size)) I = lambda: read.readline().split() n, q, M = map(int, I()) F = [1, 1] period = None for i in range(n - 1): F.append((F[-1] + F[-2]) % M) A = [*map(int, I())] B = [*map(int, I())] d = [(A[i] - B[i]) % M for i in range(n)] fd = [d[0]] if n > 1: fd.append((d[1] - d[0]) % M) for i in range(2, n): fd.append((d[i] - d[i - 1] - d[i - 2]) % M) s = sum(fd) out = [] for i in range(q): ss, l, r = I() if ss.decode('utf-8') == 'A': mul = 1 else: mul = -1 l = int(l) - 1 r = int(r) s -= fd[l] fd[l] = (fd[l] + mul) % M s += fd[l] if r + 1 < n: s -= fd[r + 1] fd[r + 1] = (fd[r + 1] - mul * F[r - l - 1]) % M s += fd[r + 1] if r < n: s -= fd[r] fd[r] = (fd[r] - mul * F[r - l]) % M s += fd[r] if s == 0: out.append('YES') else: out.append('NO') print('\n'.join(out))
1644158100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["138.23007676", "289.02652413"]
56a13208f0a9b2fad23756f39acd64af
NoteThe first sample corresponds to the illustrations in the legend.
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area Ci described by a center (xi, yi) and a radius ri. No two ranges' borders have more than one common point, that is for every pair (i, j) (1 ≤ i &lt; j ≤ n) either ranges Ci and Cj are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.
Output one decimal number — the largest achievable sum of spaciousness over two halves of the night. The output is considered correct if it has a relative or absolute error of at most 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
The first line of input contains a positive integer n (1 ≤ n ≤ 1 000) — the number of dancers. The following n lines each describes a dancer: the i-th line among them contains three space-separated integers xi, yi and ri ( - 106 ≤ xi, yi ≤ 106, 1 ≤ ri ≤ 106), describing a circular movement range centered at (xi, yi) with radius ri.
standard output
standard input
Python 3
Python
2,000
train_045.jsonl
7d44e8f59c58fe1cfbef6f9ddda3c967
256 megabytes
["5\n2 1 6\n0 4 1\n2 -1 3\n1 -2 1\n4 -1 1", "8\n0 0 1\n0 0 2\n0 0 3\n0 0 4\n0 0 5\n0 0 6\n0 0 7\n0 0 8"]
PASSED
import math class circ: def __init__(self, x, y, r): self.x = x*1.0 self.y = y*1.0 self.r = r*1.0 n = 0 n = int(input()) vec = [] for i in range(n): st = input().split(' ') a = int(st[0]) b = int(st[1]) c = int(st[2]) vec.append(circ(a,b,c)) gr = [[] for i in range(n)] pad = [-1 for i in range(n)] vis = [False for i in range(n)] for i in range(n): for k in range(n): if i == k: continue dist = math.hypot(vec[i].x - vec[k].x, vec[i].y - vec[k].y) if (dist < vec[k].r and vec[k].r > vec[i].r and (pad[i] < 0 or vec[k].r < vec[pad[i]].r)): pad[i] = k for i in range(n): if pad[i] < 0: continue gr[pad[i]].append(i) st = [] ans = 0.0 for i in range(n): if pad[i] >= 0 or vis[i]: continue st.append((i, 0)) while len(st) > 0: node, level = st.pop() vis[node] = True mult = -1.0 if level == 0 or level%2 == 1: mult = 1.0 ans += (mult * (vec[node].r * vec[node].r * math.pi)) for next in gr[node]: st.append((next, level+1)) print(ans)
1496837700
[ "geometry", "trees" ]
[ 0, 1, 0, 0, 0, 0, 0, 1 ]
0.5 seconds
["6", "10"]
43a65d1cfe59931991b6aefae1ecd10e
NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are: $$$s[1 \dots 2]$$$ $$$s[2 \dots 2]$$$ $$$s[1 \dots 4]$$$ $$$s[2 \dots 4]$$$ $$$s[3 \dots 4]$$$ $$$s[4 \dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \dots 1]$$$ and $$$s[2 \dots 2]$$$ both define the substring "2", they are still counted as different substrings.
You are given a string $$$s=s_1s_2\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \ldots s_r$$$. A substring $$$s[l \dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.
Print the number of even substrings of $$$s$$$.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 65000$$$) — the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.
standard output
standard input
Python 3
Python
800
train_021.jsonl
7f7652ce48cf7994a80ee217c39c238f
256 megabytes
["4\n1234", "4\n2244"]
PASSED
def f(): a=input() b=str(input()) n=0 for i in range(len(b)): if int(b[i])%2==0: n+=i+1 print(n) return n f()
1553182500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2 9 15", "11 14 20 27 31"]
c047040426e736e9085395ed9666135f
null
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai &lt; aj holds for any two indices i, j (i &lt; j). For any two indices i and j (i &lt; j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.
Output a line that contains n space-separated integers a1 a2, ..., an (1 ≤ ai ≤ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1. If there are multiple solutions you can output any one.
The input contains a single integer: n (1 ≤ n ≤ 105).
standard output
standard input
PyPy 2
Python
1,200
train_002.jsonl
ee9812557f344ad714c7db3a612d66f2
256 megabytes
["3", "5"]
PASSED
def sos(n): lst=[] prime = [True for i in range(n+1)] p=2 while(p * p <= n): if (prime[p] == True): for i in range(p * 2, n+1, p): prime[i] = False p+=1 lis =[] for p in range(2, n): if prime[p]: lst.append(str(p)) return lst lstp=sos(1500002) n=input() print " ".join(lstp[0:n])
1372941000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3", "13"]
587ac3b470aaacaa024a0c6dde134b7c
NoteIn the first example, all three non-empty possible subsequences are good: $$$\{1\}$$$, $$$\{1, 2\}$$$, $$$\{2\}$$$In the second example, the possible good subsequences are: $$$\{2\}$$$, $$$\{2, 2\}$$$, $$$\{2, 22\}$$$, $$$\{2, 14\}$$$, $$$\{2\}$$$, $$$\{2, 22\}$$$, $$$\{2, 14\}$$$, $$$\{1\}$$$, $$$\{1, 22\}$$$, $$$\{1, 14\}$$$, $$$\{22\}$$$, $$$\{22, 14\}$$$, $$$\{14\}$$$.Note, that some subsequences are listed more than once, since they occur in the original array multiple times.
You are given an integer array $$$a_1, a_2, \ldots, a_n$$$.The array $$$b$$$ is called to be a subsequence of $$$a$$$ if it is possible to remove some elements from $$$a$$$ to get $$$b$$$.Array $$$b_1, b_2, \ldots, b_k$$$ is called to be good if it is not empty and for every $$$i$$$ ($$$1 \le i \le k$$$) $$$b_i$$$ is divisible by $$$i$$$.Find the number of good subsequences in $$$a$$$ modulo $$$10^9 + 7$$$. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, the array $$$a$$$ has exactly $$$2^n - 1$$$ different subsequences (excluding an empty subsequence).
Print exactly one integer — the number of good subsequences taken modulo $$$10^9 + 7$$$.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of the array $$$a$$$. The next line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).
standard output
standard input
PyPy 2
Python
1,700
train_000.jsonl
3e451b277d6d35becc4a2827d1ca5177
256 megabytes
["2\n1 2", "5\n2 2 1 22 14"]
PASSED
#!/usr/bin/env python """ This file is part of https://github.com/Cheran-Senthil/PyRival. Copyright 2018 Cheran Senthilkumar all rights reserved, Cheran Senthilkumar <[email protected]> Permission to use, modify, and distribute this software is given under the terms of the MIT License. """ from sys import stdin def memodict(f): """ Memoization decorator for a function taking a single argument. """ class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ @memodict def all_factors(n): return sorted(set(reduce(list.__add__, ([i, n/i] for i in xrange(1, int(n**0.5) + 1, 2 if n % 2 else 1) if n % i == 0))), reverse=True) div_cnt = [0] * (int(stdin.readline()) + 1) res, numb, sign, div_cnt[0] = 0, 0, 1, 1 s = stdin.read() for i in xrange(len(s)): if s[i] >= '0': numb = 10 * numb + ord(s[i]) - 48 else: if s[i] == '-': sign = -1 else: for j in all_factors(sign * numb): try: res, div_cnt[j] = res + div_cnt[j - 1], div_cnt[j] + div_cnt[j - 1] if res > 1000000007: res -= 1000000007 if div_cnt[j] > 1000000007: div_cnt[j] -= 1000000007 except: pass numb, sign = 0, 1 print res
1542901500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n3\n7", "1\n4\n10\n22\n43", "1\n3\n10\n24\n51\n109\n213\n421\n833"]
6744d8bcba9ef2853788ca7168b76373
NoteLet us consider the first sample after all characters have been appended to $$$S$$$, so S is "111".As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code, therefore, are as follows. "T" (translates into "1") "M" (translates into "11") "O" (translates into "111") "TT" (translates into "11") "TM" (translates into "111") "MT" (translates into "111") "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here.
In Morse code, an letter of English alphabet is represented as a string of some length from $$$1$$$ to $$$4$$$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are $$$2^1+2^2+2^3+2^4 = 30$$$ strings with length $$$1$$$ to $$$4$$$ containing only "0" and/or "1", not all of them correspond to one of the $$$26$$$ English letters. In particular, each string of "0" and/or "1" of length at most $$$4$$$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string $$$S$$$, which is initially empty. For $$$m$$$ times, either a dot or a dash will be appended to $$$S$$$, one at a time. Your task is to find and report, after each of these modifications to string $$$S$$$, the number of non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code.Since the answers can be incredibly tremendous, print them modulo $$$10^9 + 7$$$.
Print $$$m$$$ lines, the $$$i$$$-th of which being the answer after the $$$i$$$-th modification to $$$S$$$.
The first line contains an integer $$$m$$$ ($$$1 \leq m \leq 3\,000$$$) — the number of modifications to $$$S$$$. Each of the next $$$m$$$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $$$S$$$.
standard output
standard input
PyPy 3
Python
2,400
train_063.jsonl
ca5fc176f61d2aad3762d6937170b0a2
256 megabytes
["3\n1\n1\n1", "5\n1\n0\n1\n0\n1", "9\n1\n1\n0\n0\n0\n1\n1\n0\n1"]
PASSED
import os, sys nums = list(map(int, os.read(0, os.fstat(0).st_size).split())) MOD = 10 ** 9 + 7 BAD = ([0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]) def zfunc(s): z = [0] * len(s) l = r = 0 for i in range(1, len(s)): if i <= r: z[i] = min(r - i + 1, z[i - l]) while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] - 1 > r: l, r = i, i + z[i] - 1 return z n = nums[0] s = [] sm = 0 ans = [] for i in range(1, n + 1): s.append(nums[i]) cur = 0 f = [0] * (i + 1) sum4 = f[i] = 1 for j in range(i - 1, -1, -1): if j + 4 < i: sum4 -= f[j + 5] if j + 4 <= i and s[j : j + 4] in BAD: f[j] -= f[j + 4] f[j] = (f[j] + sum4) % MOD sum4 += f[j] z = zfunc(s[::-1]) new = i - max(z) sm = (sm + sum(f[:new])) % MOD ans.append(sm) print(*ans, sep='\n')
1551022500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1111111", "1101"]
1925187d2c4b9caa1e74c29d9f33f3a6
NoteIn sample test case $$$l=19$$$, $$$r=122$$$. $$$f(x,y)$$$ is maximal and is equal to $$$127$$$, with $$$x=27$$$, $$$y=100$$$, for example.
You are given two integers $$$l$$$ and $$$r$$$ in binary representation. Let $$$g(x, y)$$$ be equal to the bitwise XOR of all integers from $$$x$$$ to $$$y$$$ inclusive (that is $$$x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y$$$). Let's define $$$f(l, r)$$$ as the maximum of all values of $$$g(x, y)$$$ satisfying $$$l \le x \le y \le r$$$.Output $$$f(l, r)$$$.
In a single line output the value of $$$f(l, r)$$$ for the given pair of $$$l$$$ and $$$r$$$ in binary representation without extra leading zeros.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the binary representation of $$$r$$$. The second line contains the binary representation of $$$l$$$ — a string of length $$$n$$$ consisting of digits $$$0$$$ and $$$1$$$ ($$$0 \le l &lt; 2^n$$$). The third line contains the binary representation of $$$r$$$ — a string of length $$$n$$$ consisting of digits $$$0$$$ and $$$1$$$ ($$$0 \le r &lt; 2^n$$$). It is guaranteed that $$$l \le r$$$. The binary representation of $$$r$$$ does not contain any extra leading zeros (if $$$r=0$$$, the binary representation of it consists of a single zero). The binary representation of $$$l$$$ is preceded with leading zeros so that its length is equal to $$$n$$$.
standard output
standard input
PyPy 3-64
Python
2,600
train_105.jsonl
c4196ff2a3bc8c4b0f74f61159997f98
256 megabytes
["7\n0010011\n1111010", "4\n1010\n1101"]
PASSED
n = int(input()) le = int(input(), 2) rg = int(input(), 2) ans = rg if (2 ** (n - 1)) & le: if rg % 2 == 0 and le <= rg - 2: ans += 1 else: ans = 2 ** n - 1 if rg else 0 print('{0:b}'.format(ans))
1615039500
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["7\n11\n8"]
3d898a45ab89b93e006270a77db49017
NoteIn the first test case, the longest simple cycle is shown below: We can't increase it with the first chain, since in such case it won't be simple — the vertex $$$2$$$ on the second chain will break simplicity.
You have $$$n$$$ chains, the $$$i$$$-th chain consists of $$$c_i$$$ vertices. Vertices in each chain are numbered independently from $$$1$$$ to $$$c_i$$$ along the chain. In other words, the $$$i$$$-th chain is the undirected graph with $$$c_i$$$ vertices and $$$(c_i - 1)$$$ edges connecting the $$$j$$$-th and the $$$(j + 1)$$$-th vertices for each $$$1 \le j &lt; c_i$$$.Now you decided to unite chains in one graph in the following way: the first chain is skipped; the $$$1$$$-st vertex of the $$$i$$$-th chain is connected by an edge with the $$$a_i$$$-th vertex of the $$$(i - 1)$$$-th chain; the last ($$$c_i$$$-th) vertex of the $$$i$$$-th chain is connected by an edge with the $$$b_i$$$-th vertex of the $$$(i - 1)$$$-th chain. Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph.A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.
For each test case, print the length of the longest simple cycle.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of chains you have. The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$2 \le c_i \le 10^9$$$) — the number of vertices in the corresponding chains. The third line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_1 = -1$$$; $$$1 \le a_i \le c_{i - 1}$$$). The fourth line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$b_1 = -1$$$; $$$1 \le b_i \le c_{i - 1}$$$). Both $$$a_1$$$ and $$$b_1$$$ are equal to $$$-1$$$, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_102.jsonl
cd48fa58a957ba80c73f9ebf030ca4c8
256 megabytes
["3\n4\n3 4 3 3\n-1 1 2 2\n-1 2 2 3\n2\n5 6\n-1 5\n-1 1\n3\n3 5 2\n-1 1 1\n-1 3 5"]
PASSED
import sys, threading import math from os import path from collections import defaultdict, Counter, deque from bisect import * from string import ascii_lowercase from functools import cmp_to_key import heapq def readInts(): x = list(map(int, (sys.stdin.readline().rstrip().split()))) return x[0] if len(x) == 1 else x def readList(type=int): x = sys.stdin.readline() x = list(map(type, x.rstrip('\n\r').split())) return x def readStr(): x = sys.stdin.readline().rstrip('\r\n') write = sys.stdout.write read = sys.stdin.readline MAXN = 1123456 MOD = 10**9 + 7 class mydict: def __init__(self, func): self.random = randint(0, 1 << 32) self.default = func self.dict = {} def __getitem__(self, key): mykey = self.random ^ key if mykey not in self.dict: self.dict[mykey] = self.default() return self.dict[mykey] def get(self, key, default): mykey = self.random ^ key if mykey not in self.dict: return default return self.dict[mykey] def __setitem__(self, key, item): mykey = self.random ^ key self.dict[mykey] = item def getkeys(self): return [self.random ^ i for i in self.dict] def __str__(self): return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}' def lcm(a, b): return (a*b)//(math.gcd(a,b)) def mod(n): return n%MOD def solve(t): # print(f'Case #{t}: ', end = '') n = readInts() c = readList() a = readInts() b = readInts() pref = 0 ans = 0 for i in range(1, n): c1 = c[i] + abs(a[i] - b[i]) + 1 c2 = float('-inf') if a[i] != b[i]: c2 = c[i] - abs(a[i] - b[i]) + 1 ans = max(ans, c1, c2+pref) pref = max(c1, c2+pref) print(ans) def main(): t = 1 if path.exists("F:/Comp Programming/input.txt"): sys.stdin = open("F:/Comp Programming/input.txt", 'r') sys.stdout = open("F:/Comp Programming/output1.txt", 'w') # sys.setrecursionlimit(10**5) t = readInts() for i in range(t): solve(i+1) if __name__ == '__main__': main()
1611930900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0", "5", "3"]
bd49960701cc29bcef693808db82366f
null
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
The firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
standard output
standard input
PyPy 2
Python
1,600
train_012.jsonl
cc47626a2dbcef38b989c206cc5af5bf
256 megabytes
["5 4 1 5\n1 2\n2 3\n3 4\n4 5", "5 4 3 5\n1 2\n2 3\n3 4\n4 5", "5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5"]
PASSED
n,m,s,t = map(int, raw_input().split()) a=[0]*(n+1) b=list(a) g= [[] for i in range(n+1)] for i in range(m): u,v = map(int, raw_input().split()) g[u]+=[v] g[v]+=[u] def bfs(x, a): q=[x] while q: c=q.pop() for y in g[c]: if not a[y]: a[y] = a[c]+1 q.insert(0,y) a[x]=0 bfs(s,a) bfs(t,b) # print a,b r=0 for i in range(1,n+1): for j in range(i + 1, n + 1): if min(a[i]+b[j]+1, a[j]+b[i]+1) >= a[t]: r+=1 print r-m
1521698700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["NO\nYES\n1 4\nNO"]
fa16d33fb9447eea06fcded0026c6e31
NoteIn the second test case of the example, one of the interesting subarrays is $$$a = [2, 0, 1, 9]$$$: $$$\max(a) - \min(a) = 9 - 0 = 9 \ge 4$$$.
For an array $$$a$$$ of integers let's denote its maximal element as $$$\max(a)$$$, and minimal as $$$\min(a)$$$. We will call an array $$$a$$$ of $$$k$$$ integers interesting if $$$\max(a) - \min(a) \ge k$$$. For example, array $$$[1, 3, 4, 3]$$$ isn't interesting as $$$\max(a) - \min(a) = 4 - 1 = 3 &lt; 4$$$ while array $$$[7, 3, 0, 4, 3]$$$ is as $$$\max(a) - \min(a) = 7 - 0 = 7 \ge 5$$$.You are given an array $$$a$$$ of $$$n$$$ integers. Find some interesting nonempty subarray of $$$a$$$, or tell that it doesn't exist.An array $$$b$$$ is a subarray of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.
For each test case, output "NO" in a separate line if there is no interesting nonempty subarray in $$$a$$$. Otherwise, output "YES" in a separate line. In the next line, output two integers $$$l$$$ and $$$r$$$ ($$$1\le l \le r \le n$$$) — bounds of the chosen subarray. If there are multiple answers, print any. You can print each letter in any case (upper or lower).
The first line contains integer number $$$t$$$ ($$$1 \le t \le 10\,000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n \le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,200
train_016.jsonl
db9381f90684c020fab1bf6b2405d7aa
256 megabytes
["3\n5\n1 2 3 4 5\n4\n2 0 1 9\n2\n2019 2020"]
PASSED
t=int(input()) for o in range(t): n=int(input()) l=list(map(int,input().split())) flag=0 for i in range(n-1): if abs(l[i]-l[i+1])>=2: print("YES") print(str(i+1)+" "+str(i+2)) flag=1 break if(flag==0): print("NO")
1577628300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1 2 1 3", "1\n1 2"]
e7517e32caa1b044ebf1d39276560b47
NoteSequence x1, x2, ..., xs is lexicographically smaller than sequence y1, y2, ..., ys, if there is such integer r (1 ≤ r ≤ s), that x1 = y1, x2 = y2, ..., xr - 1 = yr - 1 and xr &lt; yr.
A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q) = m, using the minimum number of swaps. Help him do that.
In the first line, print integer k — the minimum number of swaps. In the second line, print 2k integers x1, x2, ..., x2k — the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1, x2), (x3, x4), ..., (x2k - 1, x2k). If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.
The first line contains integer n (1 ≤ n ≤ 3000) — the length of permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — Valera's initial permutation. The last line contains integer m (0 ≤ m &lt; n).
standard output
standard input
Python 2
Python
2,100
train_052.jsonl
da4e9223c725963ecfcd1581dfb40a64
256 megabytes
["5\n1 2 3 4 5\n2", "5\n2 1 4 5 3\n2"]
PASSED
n = int(raw_input()) a = [0] + map(int, raw_input().split()) g = [0] * (n+1) l = [] st = [0] * (n+1) nd = [0] * (n+1) k = 0 for x in xrange(1, n+1): if g[x]: continue y = a[x] st[x] = len(l) while not g[y]: g[y] = x l.append(y) y = a[y] nd[x] = len(l) k += nd[x] - st[x] - 1 N = 4096 b = [10000] * N * 2 pb = [0] * N * 2 def update(p, x): p += N b[p] = x pb[p] = p - N while p > 1: p, q = p / 2, p / 2 * 2 if b[q] >= b[q+1]: q += 1 b[p], pb[p] = b[q], pb[q] def query(left, right, p = 1, L = 0, R = N): if right <= L or R <= left: return (10000, -1) if left <= L and R <= right: return (b[p], pb[p]) mid = (L + R) / 2 return min(query(left, right, p+p, L, mid), query(left, right, p+p+1, mid, R)) for i, x in enumerate(l): update(i, x) m = int(raw_input()) if m == k: print 0 else: ans = [] if m > k: for i in xrange(1, n+1): if m <= k: break if g[i] != 1: for x in l[st[i]:nd[i]]: g[x] = 1 ans.extend([1, i]) k += 1 else: for i in xrange(1, n+1): while m < k and nd[i] - st[i] > 1: j, pj = query(st[i], nd[i] - 1) ans.extend([i, j]) st[i], st[j], nd[j] = pj + 1, st[i], pj + 1 k -= 1 print len(ans) / 2 for x in ans: print x, print
1402241400
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
3 seconds
["0\n2\n2\n10"]
11452ff3750578d8b2ac5b76ba2749fd
NoteIn the first test case, the only possible action is to delete vertex $$$2$$$, after which we save $$$0$$$ vertices in total.In the second test case, if we delete vertex $$$2$$$, we can save vertices $$$3$$$ and $$$4$$$.
Byteland is a beautiful land known because of its beautiful trees.Misha has found a binary tree with $$$n$$$ vertices, numbered from $$$1$$$ to $$$n$$$. A binary tree is an acyclic connected bidirectional graph containing $$$n$$$ vertices and $$$n - 1$$$ edges. Each vertex has a degree at most $$$3$$$, whereas the root is the vertex with the number $$$1$$$ and it has a degree at most $$$2$$$.Unfortunately, the root got infected.The following process happens $$$n$$$ times: Misha either chooses a non-infected (and not deleted) vertex and deletes it with all edges which have an end in this vertex or just does nothing. Then, the infection spreads to each vertex that is connected by an edge to an already infected vertex (all already infected vertices remain infected). As Misha does not have much time to think, please tell him what is the maximum number of vertices he can save from the infection (note that deleted vertices are not counted as saved).
For each test case, output the maximum number of vertices Misha can save.
There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 5000$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2\leq n\leq 3\cdot 10^5$$$) — the number of vertices of the tree. The $$$i$$$-th of the following $$$n-1$$$ lines in the test case contains two positive integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), meaning that there exists an edge between them in the graph. It is guaranteed that the graph is a binary tree rooted at $$$1$$$. It is also guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$3\cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_095.jsonl
25e87820dd31860090cc15f04339fe73
256 megabytes
["4\n\n2\n\n1 2\n\n4\n\n1 2\n\n2 3\n\n2 4\n\n7\n\n1 2\n\n1 5\n\n2 3\n\n2 4\n\n5 6\n\n5 7\n\n15\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n4 6\n\n3 7\n\n2 8\n\n1 9\n\n9 10\n\n9 11\n\n10 12\n\n10 13\n\n11 14\n\n11 15"]
PASSED
import sys input = lambda: sys.stdin.readline().rstrip() out = sys.stdout.writelines class RootedTree: def __init__(self, G: list, root: int): self._n = len(G) self._G = G self._root = root self._height = -1 self._toposo = [] self._dist = [] self._descendant_num = [] self._child = [] self._child_num = [] self._parents = [] self._diameter = -1 self._bipartite_graph = [] self._calc_dist_toposo() # self._calc_child_parents() def __len__(self) -> int: "Return the number of vertex of self. / O(1)" return self._n def __str__(self) -> str: "Print Rooted Tree. / O(N) or O(1)" self._calc_child_parents() ret = ["<RootedTree> ["] ret.extend( [f' dist:{d} - v:{str(i).zfill(2)} - p:{str(self._parents[i]).zfill(2)} - child:{self._child[i]}' for i,d in sorted(enumerate(self._dist), key=lambda x: x[1])] ) ret.append(']') return '\n'.join(ret) def _calc_dist_toposo(self) -> None: "Calc dist and toposo. / O(N)" todo = [self._root] self._dist = [-1] * self._n self._dist[self._root] = 0 self._toposo = [self._root] for v in todo: d = self._dist[v] for x,c in self._G[v]: if self._dist[x] != -1: continue self._dist[x] = d + c todo.append(x) self._toposo.append(x) return def _calc_child_parents(self) -> None: "Calc child and parents. / O(N)" if self._child and self._child_num and self._parents: return self._child_num = [0] * self._n self._child = [[] for _ in range(self._n)] self._parents = [-1] * self._n for v in self._toposo[::-1]: for x,c in self._G[v]: if self._dist[x] < self._dist[v]: self._parents[v] = x continue self._child[v].append(x) self._child_num[v] += 1 return def get_dist(self) -> list: "Return dist. / O(N)" return self._dist def get_toposo(self) -> list: "Return toposo. / O(N)" return self._toposo def get_height(self) -> int: "Return height. / O(N)" if self._height > -1: return self._height self._height = max(self._dist) return self._height def get_descendant_num(self) -> list: "Return descendant_num. / O(N)" if self._descendant_num: return self._descendant_num self._descendant_num = [1] * self._n for v in self._toposo[::-1]: for x,c in self._G[v]: if self._dist[x] < self._dist[v]: continue self._descendant_num[v] += self._descendant_num[x] for i in range(self._n): self._descendant_num[i] -= 1 return self._descendant_num def get_child(self) -> list: "Return child / O(N)" if self._child: return self._child self._calc_child_parents() return self._child def get_child_num(self) -> list: "Return child_num. / O(N)" if self._child_num: return self._child_num self._calc_child_parents() return self._child_num def get_parents(self) -> list: "Return parents. / O(N)" if self._parents: return self._parents self._calc_child_parents() return self._parents def get_diameter(self) -> int: "Return diameter of tree. / O(N)" if self._diameter > -1: return self._diameter s = self._dist.index(self.get_height()) todo = [s] ndist = [-1] * self._n ndist[s] = 0 while todo: v = todo.pop() d = ndist[v] for x, c in self._G[v]: if ndist[x] != -1: continue ndist[x] = d + c todo.append(x) self._diameter = max(ndist) return self._diameter def get_bipartite_graph(self) -> list: "Return [1 if root else 0]. / O(N)" if self._bipartite_graph: return self._bipartite_graph self._bipartite_graph = [-1] * self._n self._bipartite_graph[self._root] = 1 todo = [self._root] while todo: v = todo.popleft() nc = 0 if self._bipartite_graph[v] else 1 for x,_ in self._G[v]: if self._bipartite_graph[x] != -1: continue self._bipartite_graph[x] = nc todo.append(x) return self._bipartite_graph def main(): n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): u, v = map(int, input().split()) u -= 1 v -= 1 G[u].append((v, 1)) G[v].append((u, 1)) tree = RootedTree(G, 0) dist = tree.get_dist() order = tree.get_toposo() child = tree.get_child() dsnum = tree.get_descendant_num() dp = [0 for _ in range(n)] for v in order[::-1]: if len(child[v]) == 0: continue elif len(child[v]) == 1: dp[v] = dsnum[child[v][0]] elif len(child[v]) == 2: x1, x2 = child[v] dp[v] = max(dp[x1]+dsnum[x2], dp[x2]+dsnum[x1]) return dp[0] out('\n'.join(map(str, [main() for _ in range(int(input()))])))
1654878900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["10\n12\n12"]
9fd9bc0a037b2948d60ac2bd5d57740f
NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$.
Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times.
Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac.
The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$.
standard output
standard input
PyPy 3
Python
900
train_001.jsonl
213273f4f75bc1e760fee2653b2167cb
256 megabytes
["3\n5 1\n8 2\n3 4"]
PASSED
def f(n): for i in range(3,n+1,2): if n%i == 0: return i return n for t in range(int(input())): n, k = map(int, input().split()) if n%2 == 0: n += 2*k else: n += f(n) n += 2*(k-1) print(n)
1589286900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "0", "4"]
b07668a66a5e50659233ba055a893bd4
null
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
Output the maximum possible profit.
The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).
standard output
standard input
Python 3
Python
1,900
train_078.jsonl
d9daa3748f1dd8de5947b98d7a6c6086
64 megabytes
["4\n1 2\n2 3\n3 4", "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7", "6\n1 2\n2 3\n2 4\n5 4\n6 4"]
PASSED
__author__ = 'Darren' def solve(): def get_diameter(u): depth, v = dfs(u, set()) return dfs(v, set())[0] def dfs(u, visited): visited.add(u) max_depth, deepest_node = -1, u for v in adj_list[u]: if v not in visited: depth, w = dfs(v, visited) if depth > max_depth: max_depth, deepest_node = depth, w return max_depth + 1, deepest_node n = int(input()) roads = [] adj_list = [set() for _i in range(n+1)] for _i in range(n-1): u, v = map(int, input().split()) roads.append((u, v)) adj_list[u].add(v) adj_list[v].add(u) ans = 0 for u, v in roads: adj_list[u].remove(v) adj_list[v].remove(u) ans = max(ans, get_diameter(u) * get_diameter(v)) adj_list[u].add(v) adj_list[v].add(u) print(ans) if __name__ == '__main__': solve()
1274283000
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["YES\nNO"]
33a31edb75c9b0cf3a49ba97ad677632
NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product.
Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.
If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO".
The first line contains an 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 an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$.
standard output
standard input
PyPy 3-64
Python
800
train_110.jsonl
bb160c235436fb56c1869ab9dee74987
256 megabytes
["2\n3\n1 5 4\n2\n100 10000"]
PASSED
import math for _t in range(int(input())): n=int(input()) l=list(map(int,input().split())) ans=0 for i in l: if(int(math.sqrt(i))**2!=math.sqrt(i)**2): ans=1 if(ans==1): print("YES") else: print("NO")
1618839300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1.5 seconds
["NO\nYES\nNO\nYES\nNO\nYES"]
c47d999006d4738868f58168c7e2df2b
NoteTest case $$$1$$$: $$$n&gt;m$$$, so they can not sit down.Test case $$$2$$$: the first person can sit $$$2$$$-nd and the second person can sit in the $$$0$$$-th chair. Both of them want at least $$$1$$$ empty chair on both sides, chairs $$$1$$$ and $$$3$$$ are free, so this is a good solution.Test case $$$3$$$: if the second person sits down somewhere, he needs $$$2$$$ empty chairs, both on his right and on his left side, so it is impossible to find a place for the first person, because there are only $$$5$$$ chairs.Test case $$$4$$$: they can sit in the $$$1$$$-st, $$$4$$$-th, $$$7$$$-th chairs respectively.
$$$m$$$ chairs are arranged in a circle sequentially. The chairs are numbered from $$$0$$$ to $$$m-1$$$. $$$n$$$ people want to sit in these chairs. The $$$i$$$-th of them wants at least $$$a[i]$$$ empty chairs both on his right and left side. More formally, if the $$$i$$$-th person sits in the $$$j$$$-th chair, then no one else should sit in the following chairs: $$$(j-a[i]) \bmod m$$$, $$$(j-a[i]+1) \bmod m$$$, ... $$$(j+a[i]-1) \bmod m$$$, $$$(j+a[i]) \bmod m$$$.Decide if it is possible to sit down for all of them, under the given limitations.
For each test case print "YES" (without quotes) if it is possible for everyone to sit down and fulfil the restrictions, and "NO" (without quotes) 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 answers).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq 10^9$$$) — the number of people and the number of chairs. The next line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ... $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the minimum number of empty chairs, on both sides of the $$$i$$$-th person. It is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
900
train_084.jsonl
1c0536f7f35ee72300c107d00744a7b7
256 megabytes
["6\n3 2\n1 1 1\n2 4\n1 1\n2 5\n2 1\n3 8\n1 2 1\n4 12\n1 2 1 3\n4 19\n1 2 1 3"]
PASSED
from sys import stdin from math import gcd from collections import deque, defaultdict from heapq import heappush, heappop t = int(stdin.readline()) for _ in range(t): n, m = map(int, stdin.readline().split()) a = list(map(int, stdin.readline().split())) s = 0 min_val = 10e9 max_val = 0 for i in range(n): s += a[i] min_val = min(a[i], min_val) max_val = max(a[i], max_val) print('Yes' if n+s+(max_val - min_val) <= m else 'NO')
1650378900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3", "2", "3"]
960e4c234666d2444b80d5966f1d285d
NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.
Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
standard output
standard input
PyPy 3
Python
1,300
train_002.jsonl
81fa2c8632e013eca4a457fff4397b9f
256 megabytes
["heavymetalisheavymetal", "heavymetalismetal", "trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou"]
PASSED
#_________________ Mukul Mohan Varshney _______________# #Template import sys import os import math import copy from math import gcd from bisect import bisect from io import BytesIO, IOBase from math import sqrt,floor,factorial,gcd,log,ceil from collections import deque,Counter,defaultdict from itertools import permutations, combinations #define function def Int(): return int(sys.stdin.readline()) def Mint(): return map(int,sys.stdin.readline().split()) def Lstr(): return list(sys.stdin.readline().strip()) def Str(): return sys.stdin.readline().strip() def Mstr(): return map(str,sys.stdin.readline().strip().split()) def List(): return list(map(int,sys.stdin.readline().split())) def Hash(): return dict() def Mod(): return 1000000007 def Ncr(n,r,p): return ((fact[n])*((ifact[r]*ifact[n-r])%p))%p def Most_frequent(list): return max(set(list), key = list.count) def Mat2x2(n): return [List() for _ in range(n)] def btod(n): return int(n,2) def dtob(n): return bin(n).replace("0b","") # Driver Code def solution(): #for _ in range(Int()): n=Str() s=0 e=0 for i in range(len(n)): if(n[i:i+5]=='heavy'): s+=1 if(n[i:i+5]=='metal'): e+=s print(e) #Call the solve function if __name__ == "__main__": solution()
1371223800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["3"]
35d68cc84b4c0025f03f857779f540d7
null
People in the Tomskaya region like magic formulas very much. You can see some of them below.Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:Here, "mod" means the operation of taking the residue after dividing.The expression means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.
The only line of output should contain a single integer — the value of Q.
The first line of the input contains the only integer n (1 ≤ n ≤ 106). The next line contains n integers: p1, p2, ..., pn (0 ≤ pi ≤ 2·109).
standard output
standard input
Python 3
Python
1,600
train_016.jsonl
770748ad86c824958dcc54a2ad59e0b3
256 megabytes
["3\n1 2 3"]
PASSED
n,a=int(input()),list(map(int,input().split())) x,s=[0]*(n+1),0 for i in range(1,n+1): x[i]=i^x[i-1] if (n//i)%2:s^=x[i-1] s^=x[n%i] s^=a[i-1] print(s)
1398409200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "0\n2"]
89bf97a548fe12921102e77dda63283a
Notein the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.
A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.
In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.
The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.
standard output
standard input
Python 2
Python
2,100
train_072.jsonl
dbad5a17a56b08efebd1a31c3a3a1e78
256 megabytes
["4\n1 2\n1 3\n2 4\n1\n2 3", "4\n1 2\n2 3\n2 4\n2\n1 2\n1 3"]
PASSED
from sys import stdin, stdout def main(): n = int(stdin.readline()) to = [0] xt = [0] last = [0] * (n + 1) toa = to.append xta = xt.append c = 1 for _ in xrange(n - 1): a, b = map(int, stdin.readline().split()) xta(last[a]) last[a] = c toa(b) c += 1 xta(last[b]) last[b] = c toa(a) c += 1 st = [1] done = [0] * (n + 1) par = [0] * (n + 1) cn = [1] * (n + 1) dep = [0] * (n + 1) pp = st.pop pu = st.append while st: x = pp() if done[x] == 1: done[x] = 2 y = last[x] while y: if done[to[y]] == 2: cn[x] += cn[to[y]] y = xt[y] elif not done[x]: done[x] = 1 y = last[x] pu(x) while y: if not done[to[y]]: pu(to[y]) par[to[y]] = x dep[to[y]] = dep[x] + 1 y = xt[y] par[1] = 1 pa = [par] ppa = par pu = pa.append N = n.bit_length() for j in xrange(N): npa = [ppa[ppa[i]] for i in xrange(n + 1)] pu(npa) ppa = npa m = int(stdin.readline()) ans = [] pu = ans.append for _ in xrange(m): a, b = map(int, stdin.readline().split()) if a == b: pu(n) continue if dep[a] > dep[b]: a, b = b, a x, y = a, b z = dep[y] - dep[x] for j in xrange(N): if z >> j & 1: y = pa[j][y] if x != y: for j in xrange(N - 1, -1, -1): if pa[j][x] != pa[j][y]: x, y = pa[j][x], pa[j][y] t = pa[0][x] else: t = x z = dep[a] - 2 * dep[t] + dep[b] if z % 2: pu(0) continue z /= 2 z -= 1 y = b for j in xrange(N): if z >> j & 1: y = pa[j][y] x = cn[par[y]] - cn[y] if dep[a] == dep[b]: y = a for j in xrange(N): if z >> j & 1: y = pa[j][y] x -= cn[y] x += n - cn[par[y]] pu(x) stdout.write('\n'.join(map(str, ans))) main()
1425128400
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["balance", "left", "right", "balance"]
19f2c21b18e84f50e251b1dfd557d32f
NoteAs you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.The pictures to the examples:
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.The decoding of the lever description is given below. If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar. If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar. If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
standard output
standard input
Python 3
Python
900
train_000.jsonl
d36fa9385ce03251c358eb8d5febc507
256 megabytes
["=^==", "9===^==1", "2==^7==", "41^52=="]
PASSED
lever = input().split("^") leftWeight = 0 for d in range(len(lever[0])): if lever[0][d] != "=": leftWeight += int(lever[0][d])*(len(lever[0])-d) rightWeight = 0 for d in range(len(lever[1])): if lever[1][d] != "=": rightWeight += int(lever[1][d])*(d+1) if leftWeight > rightWeight: print("left") if rightWeight > leftWeight: print("right") if rightWeight == leftWeight: print("balance")
1387893600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["ORZ", "0"]
391c2abbe862139733fcb997ba1629b8
null
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted. If there is no valid common subsequence, output 0.
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
standard output
standard input
Python 3
Python
2,000
train_065.jsonl
400644b8550135348931110e71de3267
512 megabytes
["AJKEQSLOBSROFGZ\nOVGURWZLWVLUXTH\nOZ", "AA\nA\nA"]
PASSED
a, b, v = input(), input(), input() t = [[-1] * len(b) for x in range(len(a))] def g(i, j): if i < 0 or j < 0: return '' if t[i][j] == -1: s = g(i - 1, j - 1) if a[i] == b[j]: s += a[i] t[i][j] = max(s, g(i - 1, j), g(i, j - 1), key=lambda q: len(q) - q.count(v)) return t[i][j] s = g(len(a) - 1, len(b) - 1) while v in s: s = min(s.replace(v, v[:-1]), s.replace(v, v[1:]), key=lambda q: q.count(v)) print(s if s else 0)
1379691000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["4\n-1\n8\n-1", "1\n2"]
89c97b6c302bbb51e9d5328c680a7ea7
null
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.
For each query, print its answer in a single line.
The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.
standard output
standard input
Python 3
Python
1,900
train_004.jsonl
99a55935d070f23c133bc07879301231
256 megabytes
["2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8", "1 5 2\n1 5 10\n2 7 4"]
PASSED
import math A, B, n = map(int, input().split()) ans = [] for _ in range(n): l, t, m = map(int, input().split()) if A + B * (l - 1) > t: ans.append(-1) continue r1 = (t - A) / B + 1 D = (B-2*A)*(B-2*A)-4*B*(-2*l*A+2*A-B*(l-2)*(l-1)-2*m*t) r2 = int(((B-2*A) + math.sqrt(D)) / 2 / B) if r1 > r2: r1 = r2 ans.append(int(r1)) print("\n".join(map(str, ans)))
1429029300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["5 3 -1", "14 4 14 4 7 7", "12 5"]
476c05915a1536cd989c4681c61c9deb
NoteConsider the first monster of the first example.Monocarp can't recruit one unit of the first type, because it will take both him and the monster $$$0.75$$$ seconds to kill each other. He can recruit two units for the cost of $$$6$$$ coins and kill the monster in $$$0.375$$$ second.Monocarp can recruit one unit of the second type, because he kills the monster in $$$0.6$$$ seconds, and the monster kills him in $$$0.625$$$ seconds. The unit is faster. Thus, $$$5$$$ coins is enough.Monocarp will need at least three units of the third type to kill the first monster, that will cost $$$30$$$ coins.Monocarp will spend the least coins if he chooses the second type of units and recruits one unit of that type.
Monocarp is playing a strategy game. In the game, he recruits a squad to fight monsters. Before each battle, Monocarp has $$$C$$$ coins to spend on his squad.Before each battle starts, his squad is empty. Monocarp chooses one type of units and recruits no more units of that type than he can recruit with $$$C$$$ coins.There are $$$n$$$ types of units. Every unit type has three parameters: $$$c_i$$$ — the cost of recruiting one unit of the $$$i$$$-th type; $$$d_i$$$ — the damage that one unit of the $$$i$$$-th type deals in a second; $$$h_i$$$ — the amount of health of one unit of the $$$i$$$-th type. Monocarp has to face $$$m$$$ monsters. Every monster has two parameters: $$$D_j$$$ — the damage that the $$$j$$$-th monster deals in a second; $$$H_j$$$ — the amount of health the $$$j$$$-th monster has. Monocarp has to fight only the $$$j$$$-th monster during the $$$j$$$-th battle. He wants all his recruited units to stay alive. Both Monocarp's squad and the monster attack continuously (not once per second) and at the same time. Thus, Monocarp wins the battle if and only if his squad kills the monster strictly faster than the monster kills one of his units. The time is compared with no rounding.For each monster, Monocarp wants to know the minimum amount of coins he has to spend to kill that monster. If this amount is greater than $$$C$$$, then report that it's impossible to kill that monster.
Print $$$m$$$ integers. For each monster, print the minimum amount of coins Monocarp has to spend to kill that monster. If this amount is greater than $$$C$$$, then print $$$-1$$$.
The first line contains two integers $$$n$$$ and $$$C$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$1 \le C \le 10^6$$$) — the number of types of units and the amount of coins Monocarp has before each battle. The $$$i$$$-th of the next $$$n$$$ lines contains three integers $$$c_i, d_i$$$ and $$$h_i$$$ ($$$1 \le c_i \le C$$$; $$$1 \le d_i, h_i \le 10^6$$$). The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — the number of monsters that Monocarp has to face. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$D_j$$$ and $$$H_j$$$ ($$$1 \le D_j \le 10^6$$$; $$$1 \le H_j \le 10^{12}$$$).
standard output
standard input
PyPy 3-64
Python
2,000
train_110.jsonl
9e47cf1d6760e3ecabd46f304caf31aa
256 megabytes
["3 10\n3 4 6\n5 5 5\n10 3 4\n3\n8 3\n5 4\n10 15", "5 15\n14 10 3\n9 2 2\n10 4 3\n7 3 5\n4 3 1\n6\n11 2\n1 1\n4 7\n2 1\n1 14\n3 3", "5 13\n13 1 9\n6 4 5\n12 18 4\n9 13 2\n5 4 5\n2\n16 3\n6 2"]
PASSED
import sys import os from io import BytesIO sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) input = lambda: sys.stdin.readline().rstrip() N,C = map(int, input().split()) A = [0]*(C+1) for _ in range(N): c,d,h = map(int, input().split()) A[c] = max(A[c], h*d) # 与上面的循环分开,避免有多个c==1的情况 for c in range(C//2,0,-1): t = A[c] if t>0: for i in range(2,C//c+1): A[c*i] = max(A[c*i], t*i) M = int(input()) ans = [-1]*M B = [] for i in range(M): d1,h1 = map(int, input().split()) B.append((d1*h1,i)) B.sort(reverse=True) for c in range(1,C+1): e = A[c] while B and e>B[-1][0]: e1,i = B.pop() ans[i] = c print(*ans)
1647960300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\n4\n2", "NO", "YES\n2 1 5\n4"]
4a644d97824d29c42dbb48d79b9958fe
null
Petya and Vasya are competing with each other in a new interesting game as they always do.At the beginning of the game Petya has to come up with an array of $$$N$$$ positive integers. Sum of all elements in his array should be equal to $$$S$$$. Then Petya has to select an integer $$$K$$$ such that $$$0 \leq K \leq S$$$.In order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either $$$K$$$ or $$$S - K$$$. Otherwise Vasya loses.You are given integers $$$N$$$ and $$$S$$$. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.
If Petya can win, print "YES" (without quotes) in the first line. Then print Petya's array in the second line. The array should contain $$$N$$$ positive integers with sum equal to $$$S$$$. In the third line print $$$K$$$. If there are many correct answers, you can print any of them. If Petya can't win, print "NO" (without quotes). You can print each letter in any register (lowercase or uppercase).
The first line contains two integers $$$N$$$ and $$$S$$$ ($$$1 \leq N \leq S \leq 10^{6}$$$) — the required length of the array and the required sum of its elements.
standard output
standard input
PyPy 3
Python
1,400
train_004.jsonl
9810cf7107e6a1b3e59cb739e6642855
256 megabytes
["1 4", "3 4", "3 8"]
PASSED
n,s = list(map(int,input().split())) val = s//n rem = s%n v1 = val v2 = val+rem if v1>1: print('YES') for i in range(0,n-1): print(v1,end=" ") print(v2) print(1) else: print('NO')
1589628900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["netman: Hello, Vladik!\nVladik: Hi", "Impossible", "Impossible\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\ntigerrrrr: yes, netman\nbanany2001: yes of course."]
3ac91d8fc508ee7d1afcf22ea4b930e4
null
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Print the information about the t chats in the following format: If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format: &lt;username&gt;:&lt;text&gt; If there are multiple answers, print any of them.
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format. The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat. The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters. The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line: &lt;username&gt;:&lt;text&gt; — the format of a message with known sender. The username should appear in the list of usernames of the chat. &lt;?&gt;:&lt;text&gt; — the format of a message with unknown sender. The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters. We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha". It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
standard output
standard input
Python 2
Python
2,200
train_031.jsonl
b2b217c1460f8ccec742cb00cf3122d3
256 megabytes
["1\n2\nVladik netman\n2\n?: Hello, Vladik!\n?: Hi", "1\n2\nnetman vladik\n3\nnetman:how are you?\n?:wrong message\nvladik:im fine", "2\n3\nnetman vladik Fedosik\n2\n?: users are netman, vladik, Fedosik\nvladik: something wrong with this chat\n4\nnetman tigerrrrr banany2001 klinchuh\n4\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\n?: yes, netman\nbanany2001: yes of course."]
PASSED
import sys t =sys.stdin.readline() t = int(t) for tttt in range(t) : org=[] dic={} n =sys.stdin.readline() n = int(n) users=sys.stdin.readline().split() users=['?']+users for k in range(n+1): dic[users[k]]=k m = sys.stdin.readline() m=int(m) messusers=[] messages=[] for mmmm in range(m): curr=[] ms=sys.stdin.readline().strip() org.append(ms) pos=ms.find(':') name=ms[:pos] ms=' '+ms[pos+1:]+' ' ms=ms.replace('.',' ') ms=ms.replace('?',' ') ms=ms.replace(',',' ') ms=ms.replace('!',' ') messusers.append(dic[name]) for nm in users: nmm=' '+nm+' ' if nmm in ms: curr.append(dic[nm]) messages.append(curr) m=len(messages) found=True for i in range(m): if messusers[i]!=0: continue now=[] if i > 0 : now.append(messusers[i-1]) if i < m-1 and messusers[i+1]!=0: now.append(messusers[i+1]) now+=messages[i] cand=[] for us in range(1,len(users)): if us not in now: cand.append(us) if len(cand)==0 : found=False break else: messusers[i]=cand[0] #filter filter=[] if i<m-1: filter+=messages[i+1] if i<m-2 and messusers[i+2]!=0: filter.append(messusers[i+2]) for k in cand: if k in filter: messusers[i]=k break org[i]=users[messusers[i]]+org[i][1:] if found: for ms in org: print ms else: print 'Impossible'
1483713300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1 2\n2 3", "16 32 48\n32 48 64", "327 583\n408 664"]
5f0b8e6175113142be15ac960e4e9c4c
NoteIn the first example, the matrix $$$a$$$ can be used as the matrix $$$b$$$, because the absolute value of the difference between numbers in any adjacent pair of cells is $$$1 = 1^4$$$.In the third example: $$$327$$$ is a multiple of $$$3$$$, $$$583$$$ is a multiple of $$$11$$$, $$$408$$$ is a multiple of $$$12$$$, $$$664$$$ is a multiple of $$$8$$$; $$$|408 - 327| = 3^4$$$, $$$|583 - 327| = 4^4$$$, $$$|664 - 408| = 4^4$$$, $$$|664 - 583| = 3^4$$$.
You are given a matrix $$$a$$$ consisting of positive integers. It has $$$n$$$ rows and $$$m$$$ columns.Construct a matrix $$$b$$$ consisting of positive integers. It should have the same size as $$$a$$$, and the following conditions should be met: $$$1 \le b_{i,j} \le 10^6$$$; $$$b_{i,j}$$$ is a multiple of $$$a_{i,j}$$$; the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in $$$b$$$ is equal to $$$k^4$$$ for some integer $$$k \ge 1$$$ ($$$k$$$ is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.
The output should contain $$$n$$$ lines each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be $$$b_{i,j}$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 500$$$). Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$a_{i,j}$$$ ($$$1 \le a_{i,j} \le 16$$$).
standard output
standard input
PyPy 3-64
Python
2,200
train_092.jsonl
1e3d9f925d7235ff95b86a9b7f6e0e14
256 megabytes
["2 2\n1 2\n2 3", "2 3\n16 16 16\n16 16 16", "2 2\n3 11\n12 8"]
PASSED
a = [] n, m = map(int, input().split()) t = 720720 for _ in range(n): a.append([]) for j in map(int, input().split()): a[-1].append(j) for i in range(n): for j in range(m): if ((i + 1) + (j + 1)) % 2 == 1: a[i][j] = t else: a[i][j] **= 4 a[i][j] += t for i in range(n): print(*a[i])
1613141400
[ "number theory", "math", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 0 ]
1 second
["YES", "nO", "YES"]
424f37abd0e19208e6b0cb8b670e7187
NoteThe following image shows the first sample: both $$$P$$$ and $$$T$$$ are squares. The second sample was shown in the statements.
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon $$$P$$$ which is defined by coordinates of its vertices. Define $$$P(x,y)$$$ as a polygon obtained by translating $$$P$$$ by vector $$$\overrightarrow {(x,y)}$$$. The picture below depicts an example of the translation:Define $$$T$$$ as a set of points which is the union of all $$$P(x,y)$$$ such that the origin $$$(0,0)$$$ lies in $$$P(x,y)$$$ (both strictly inside and on the boundary). There is also an equivalent definition: a point $$$(x,y)$$$ lies in $$$T$$$ only if there are two points $$$A,B$$$ in $$$P$$$ such that $$$\overrightarrow {AB} = \overrightarrow {(x,y)}$$$. One can prove $$$T$$$ is a polygon too. For example, if $$$P$$$ is a regular triangle then $$$T$$$ is a regular hexagon. At the picture below $$$P$$$ is drawn in black and some $$$P(x,y)$$$ which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if $$$P$$$ and $$$T$$$ are similar. Your task is to check whether the polygons $$$P$$$ and $$$T$$$ are similar.
Output "YES" in a separate line, if $$$P$$$ and $$$T$$$ are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).
The first line of input will contain a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$) — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i, y_i$$$ ($$$|x_i|, |y_i| \le 10^9$$$), denoting the coordinates of the $$$i$$$-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.
standard output
standard input
Python 3
Python
1,800
train_010.jsonl
2f41e6e84e49f712fe66b29f73de52fb
256 megabytes
["4\n1 0\n4 1\n3 4\n0 3", "3\n100 86\n50 0\n150 0", "8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3"]
PASSED
n = int(input()) polygon = [None] * n for i in range(n): polygon[i] = tuple(map(int, input().split())) if n % 2: print("NO") else: def same(id1, id2): ax = polygon[id1 + 1][0] - polygon[id1][0] ay = polygon[id1 + 1][1] - polygon[id1][1] bx = polygon[id2 + 1][0] - polygon[id2][0] by = polygon[id2 + 1][1] - polygon[id2][1] return abs(ax) == abs(bx) and (ax * by == bx * ay) polygon.append(polygon[0]) for i in range(n // 2): if not same(i, i + n // 2): print("NO") exit() print("YES")
1581257100
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["3", "3223", "3133"]
0aa46c224476bfba2b1e1227b58e1630
NoteIn the second sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a1, a2, a4} = {1, 3, 5} and {a1, a3, a4} = {1, 2, 5}.In the third sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a1, a3, a4} = {1, 2, 3}.
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.Nam created a sequence a consisting of n (1 ≤ n ≤ 105) elements a1, a2, ..., an (1 ≤ ai ≤ 105). A subsequence ai1, ai2, ..., aik where 1 ≤ i1 &lt; i2 &lt; ... &lt; ik ≤ n is called increasing if ai1 &lt; ai2 &lt; ai3 &lt; ... &lt; aik. An increasing subsequence is called longest if it has maximum length among all increasing subsequences. Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 ≤ i ≤ n), into three groups: group of all i such that ai belongs to no longest increasing subsequences. group of all i such that ai belongs to at least one but not every longest increasing subsequence. group of all i such that ai belongs to every longest increasing subsequence. Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.
Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.
The first line contains the single integer n (1 ≤ n ≤ 105) denoting the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105).
standard output
standard input
Python 3
Python
2,200
train_046.jsonl
6da85e1824eddba6e014ce3f1c036a01
256 megabytes
["1\n4", "4\n1 3 2 5", "4\n1 5 2 3"]
PASSED
# a simple parser for python. use get_number() and get_word() to read def main(): def parser(): while 1: data = list(input().split(' ')) for number in data: if len(number) > 0: yield(number) input_parser = parser() gets = lambda: next(input_parser) def getNum(): data = gets() try: return int(data) except ValueError: return float(data) # ---------program--------- from bisect import bisect_left as binsleft # bisect_left = bisect_left MAXA = int(9e9) n = getNum() RANGN = range(n) a = [ getNum() for _ in RANGN ] revlis = [] g = [MAXA]*n for i in reversed(RANGN): x = -a[i] pt = binsleft( g, x ) revlis.append(pt+1) if( x < g[pt] ): g[pt] = x hlis = max( revlis ) lis, inlis = [], [] d = [0]*n for i in RANGN: g[i] = MAXA for i in RANGN: pt = binsleft( g, a[i] ) lis.append( pt+1 ) inlis.append( lis[i] + revlis[n-i-1] > hlis ) d[pt] += inlis[-1] if( a[i] < g[pt] ): g[pt] = a[i] print( ''.join( [ '32'[d[lis[i]-1] > 1] if inlis[i] else '1' for i in RANGN ] ) ) if __name__ == "__main__": main()
1415718000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n2\n0"]
ee295fd90ee9283709447481f172c73c
NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\to$$$ AABBBABB $$$\to$$$ AABBBB $$$\to$$$ ABBB $$$\to$$$ AB $$$\to$$$ (empty string). So, the answer is $$$0$$$.
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?
For each test case, print a single integer: the length of the shortest string that Zookeeper can make.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 20000)$$$  — the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,100
train_010.jsonl
2b7de7879c2dcc346bc389a268301dfe
256 megabytes
["3\nAAA\nBABA\nAABBBABBBB"]
PASSED
from collections import Counter import math import sys from bisect import bisect,bisect_left,bisect_right from itertools import permutations def input(): return sys.stdin.readline().strip() def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def mod(): return 10**9+7 for i in range(INT()): #n = INT() s = input() #n1,n2 = MAP() #a = LIST() n = len(s) ans = 0 ca = 0 cb = 0 for i in range(n-1,-1,-1): if s[i] == 'A': ca += 1 if s[i] == 'B': cb += 1 if ca>cb: ans += 1 ca = 0 cb = 0 else: if ca == cb: ca = 0 cb = 0 else: cb -= ca ca = 0 ans += cb%2 print(ans)
1602939900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n999993 1000000", "1\n1000000"]
4143caa25fcc2f4d400d169f9697be01
null
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: "Are you kidding me?", asks Chris.For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7. However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!
In the first line of output print a single integer m (1 ≤ m ≤ 106 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1 ≤ yi ≤ 106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi ≠ yj for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.
The first line of input contains a single integer n (1 ≤ n ≤ 5·105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 106), the numbers of the blocks in X. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
standard output
standard input
Python 2
Python
1,700
train_028.jsonl
365fd80633977137b93b4607bd6daf99
256 megabytes
["3\n1 4 5", "1\n1"]
PASSED
s = 10 ** 6 cnt = int(raw_input()) data = set(map(int, raw_input().split())) ans = [] p = 0 for i in data: now = s + 1 - i if now in data: p += 1 else: ans.append(now) p /= 2 if p > 0: for i in xrange(1, s / 2 + 1): now = s + 1 - i if (now not in data) and (i not in data): ans.append(i) ans.append(now) p -= 1 if p == 0: break print len(ans) print ' '.join(map(str, ans))
1395502200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n6\n-1"]
5eac47595f0212b2b652518f0fefd238
NoteOne of the possible answers to the first test case: $$$(0, 0) \to (1, 0) \to (1, 1) \to (2, 2)$$$.One of the possible answers to the second test case: $$$(0, 0) \to (0, 1) \to (1, 2) \to (0, 3) \to (1, 4) \to (2, 3) \to (3, 2) \to (4, 3)$$$.In the third test case Mikhail cannot reach the point $$$(10, 1)$$$ in 9 moves.
Mikhail walks on a Cartesian plane. He starts at the point $$$(0, 0)$$$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $$$(0, 0)$$$, he can go to any of the following points in one move: $$$(1, 0)$$$; $$$(1, 1)$$$; $$$(0, 1)$$$; $$$(-1, 1)$$$; $$$(-1, 0)$$$; $$$(-1, -1)$$$; $$$(0, -1)$$$; $$$(1, -1)$$$. If Mikhail goes from the point $$$(x1, y1)$$$ to the point $$$(x2, y2)$$$ in one move, and $$$x1 \ne x2$$$ and $$$y1 \ne y2$$$, then such a move is called a diagonal move.Mikhail has $$$q$$$ queries. For the $$$i$$$-th query Mikhail's target is to go to the point $$$(n_i, m_i)$$$ from the point $$$(0, 0)$$$ in exactly $$$k_i$$$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $$$(0, 0)$$$ to the point $$$(n_i, m_i)$$$ in $$$k_i$$$ moves.Note that Mikhail can visit any point any number of times (even the destination point!).
Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to -1 if Mikhail cannot go from the point $$$(0, 0)$$$ to the point $$$(n_i, m_i)$$$ in exactly $$$k_i$$$ moves described above. Otherwise the $$$i$$$-th integer should be equal to the the maximum number of diagonal moves among all possible movements.
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th of these $$$q$$$ lines contains three integers $$$n_i$$$, $$$m_i$$$ and $$$k_i$$$ ($$$1 \le n_i, m_i, k_i \le 10^{18}$$$) — $$$x$$$-coordinate of the destination point of the query, $$$y$$$-coordinate of the destination point of the query and the number of moves in the query, correspondingly.
standard output
standard input
PyPy 3
Python
1,600
train_030.jsonl
842d73b7e765029e0bd8a6926e88a7c9
256 megabytes
["3\n2 2 3\n4 3 7\n10 1 9"]
PASSED
for _ in range(int(input())): n,m,k = map(int,input().split()) if max(n,m)>k: print(-1) else: if (n+m)%2==0: if (n+k)%2==0: print(k) else: print(k-2) else: print(k-1)
1536330900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
7fb8b73fa2948b360644d40b7035ce4a
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
null
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
standard output
standard input
PyPy 3-64
Python
1,800
train_107.jsonl
75e5d3dda0079d906b06255f041ce7de
256 megabytes
["7 6\n\n2\n\n7"]
PASSED
import os import sys from io import BytesIO, IOBase # 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") ############# Importing modules and stuffs we require ###################################################### try: import sys from functools import lru_cache, cmp_to_key, reduce from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as Cntr from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect, insort from time import perf_counter from fractions import Fraction import copy from copy import deepcopy import time from decimal import * starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def A2(n,m): return [[0]*m for i in range(n)] def A(n):return [0]*n # from sys import stdin # input = stdin.buffer.readline # I = lambda : list(map(int,input().split())) # import sys # input=sys.stdin.readline # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import random sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") # from sys import * # setrecursionlimit(2*(10**6)) except: pass R = range ############# Importing modules and stuffs we require ###################################################### n,k = L() A = [] B = [] for i in range(n-1): print("and",1,i+2,flush=True) x = L()[0] if x==-1: exit() print("or",1,i+2,flush=True) y = L()[0] if y==-1: exit() A.append(x) B.append(y) z = 0 for ele in A: for i in range(32): if (ele>>i)&1: z|=(1<<i) print("and",2,3,flush=True) x = L()[0] print("or",2,3,flush=True) y = L()[0] for i in range(32): if ((z>>i)&1==0) and (((B[0]>>i)&1 and (x>>i)&1==0) or ((B[1]>>i)&1 and (x>>i)&1==0)) and (y>>i)&1==0: z|=(1<<i) X = [z] for i in range(n-1): z = 0 for j in range(32): if (B[i]>>j)&1 and (X[0]>>j)&1==0: z|=(1<<j) elif (A[i]>>j)&1: z|=(1<<j) X.append(z) print("finish",sorted(X)[k-1],flush=True)
1630247700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 \n1 2 3 \n1 2 4 3 \n1 2 3 4 5"]
a57823a7ca0f67a07f94175ab59d33de
NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.
You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).
For each test case print the lexicographically smallest permutation you can obtain.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.
standard output
standard input
PyPy 3-64
Python
800
train_106.jsonl
f9e5b7fd2e9dfc5b2ea3a05870dc5985
256 megabytes
["4\n\n1\n\n1\n\n3\n\n2 1 3\n\n4\n\n1 4 2 3\n\n5\n\n1 2 3 4 5"]
PASSED
#lista=list(map(int,input().split())) #x=lista[0] #n=lista[0] import math #import sys #from collections import deque #from sys import stdin, stdout from decimal import * #lista=list(map(int,input().split())) #x=lista[0] #n=lista[0] rasp_final="" #my_set=set() #for x in range(1, 100000): #my_set.add(2*x*x) #my_set.add(4*x*x) #vector_prime=[-1]*21000 #vector_rasp=[0]*21000 #vector_prime[1]=1 #vector_rasp[1]=1 #contor=2 #primes sieve #for i in range(2,21000): #if vector_prime[i]==-1: #vector_prime[i]=1 #vector_rasp[contor]=i #contor=contor+1 #for j in range(i+i,21000,i): # vector_prime[j]=0 #print(i,j) #res = list(map(int, str(num))) def cmmmdc(x,y): maximul=max(x,y) minimul=min(x,y) while maximul!=minimul and minimul!=0: dif=maximul-minimul raport=dif//minimul maximul-=minimul*(raport+1) a=max(minimul,maximul) b=min(minimul, maximul) maximul=a minimul=b return (maximul) dict = {} #suma=0 #vector=list(map(int,input().split())) #for i in vector: #suma=suma+i #luni = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':0} #luni_reverse = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 0:'December'} alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26} #alfabet_2={'1':"a", '2':"b", '3':"c", '4':"d", '5':"e", '6':"f", '7':"g", '8':"h", '9':"i", '10':"j", '11':"k", '12':"l", '13':"m", '14':"n", '15':"o", '16':"p", '17':"q", '18':"r", '19':"s", '20':"t", '21':"u", '22':"v", '23':"w", '24':"x", '25':"y", '26':"z"} #k=int(input()) k=1 contor=0 while k>0: #contor+=1 # waiting=deque() #pare=0 for _ in range(int(input())): a=int(input()) l=list(map(int,input().split())) for i in range(a): if l[i]!=i+1: j=l.index(i+1)+1 l[i:j]=l[i:j][::-1] break for i in l: print(i,end=" ") print() k=k-1 #print(rasp_final)
1644849300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2\n1 3", "0", "1\n4\n1 2 5 6"]
f78d04f699fc94103e5b08023949854d
NoteIn the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices $$$2$$$ and $$$3$$$, which results in the same final string.In the second sample, it is already impossible to perform any operations.
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by $$$n$$$ characters '(' or ')' is simple if its length $$$n$$$ is even and positive, its first $$$\frac{n}{2}$$$ characters are '(', and its last $$$\frac{n}{2}$$$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
In the first line, print an integer $$$k$$$  — the minimum number of operations you have to apply. Then, print $$$2k$$$ lines describing the operations in the following format: For each operation, print a line containing an integer $$$m$$$  — the number of characters in the subsequence you will remove. Then, print a line containing $$$m$$$ integers $$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_m$$$  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string. If there are multiple valid sequences of operations with the smallest $$$k$$$, you may print any of them.
The only line of input contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$) formed by characters '(' and ')', where $$$|s|$$$ is the length of $$$s$$$.
standard output
standard input
Python 3
Python
1,200
train_005.jsonl
a1c2ac3f5608d4165a7ebd50c2047367
256 megabytes
["(()((", ")(", "(()())"]
PASSED
s = input() a = [] i = 0 j = len(s) - 1 while i < j: while i < j and s[i] != '(': i += 1 while i < j and s[j] != ')': j -= 1 if i < j and s[i] == '(' and s[j] == ')': a.append(i + 1) a.append(j + 1) i += 1 j -= 1 if a: print(1) print(len(a)) print(*sorted(a)) else: print(0)
1583246100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["18\n1000000000000000000"]
7e6bc93543ad7bf80a019559b7bf99e0
NoteThe picture below shows the solution for the first sample. The cost $$$18$$$ is reached by taking $$$c_3$$$ 3 times and $$$c_2$$$ once, amounting to $$$5+5+5+3=18$$$.
Lindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.Consider a hexagonal tiling of the plane as on the picture below. Nicks wishes to go from the cell marked $$$(0, 0)$$$ to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from $$$(0, 0)$$$ to $$$(1, 1)$$$ will take the exact same cost as going from $$$(-2, -1)$$$ to $$$(-1, 0)$$$. The costs are given in the input in the order $$$c_1$$$, $$$c_2$$$, $$$c_3$$$, $$$c_4$$$, $$$c_5$$$, $$$c_6$$$ as in the picture below. Print the smallest cost of a path from the origin which has coordinates $$$(0, 0)$$$ to the given cell.
For each testcase output the smallest cost of a path from the origin to the given cell.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^{4}$$$). Description of the test cases follows. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$-10^{9} \le x, y \le 10^{9}$$$) representing the coordinates of the target hexagon. The second line of each test case contains six integers $$$c_1$$$, $$$c_2$$$, $$$c_3$$$, $$$c_4$$$, $$$c_5$$$, $$$c_6$$$ ($$$1 \le c_1, c_2, c_3, c_4, c_5, c_6 \le 10^{9}$$$) representing the six costs of the making one step in a particular direction (refer to the picture above to see which edge is for each value).
standard output
standard input
PyPy 3
Python
1,900
train_057.jsonl
c568755c85884c2ed08ab579f968dc55
256 megabytes
["2\n-3 1\n1 3 5 7 9 11\n1000000000 1000000000\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000"]
PASSED
import sys input = sys.stdin.readline def main(): x, y = map(int, input().split()) clst = list(map(int, input().split())) clst[0] = min(clst[0], clst[5] + clst[1]) clst[1] = min(clst[1], clst[0] + clst[2]) clst[2] = min(clst[2], clst[1] + clst[3]) clst[3] = min(clst[3], clst[2] + clst[4]) clst[4] = min(clst[4], clst[3] + clst[5]) clst[5] = min(clst[5], clst[4] + clst[0]) directions = [(1, 1), (0, 1), (-1, 0), (-1, -1), (0, -1), (1, 0)] ans = 10 ** 20 for i in range(6): dx1, dy1 = directions[i] dx2, dy2 = directions[(i + 1) % 6] a = (x * dy2 - y * dx2) // (dx1 * dy2 - dy1 * dx2) b = (x * dy1 - y * dx1) // (dx2 * dy1 - dy2 * dx1) if a < 0 or b < 0: continue ans = min(ans, clst[i] * a + clst[(i + 1) % 6] * b) print(ans) for _ in range(int(input())): main()
1603011900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Yes\nYes\nNo"]
a375dd323b7adbfa9f1cad9aa48f7247
null
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
Print $$$t$$$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains two integers $$$a_1$$$ and $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers $$$a_2$$$ and $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
standard output
standard input
PyPy 2
Python
900
train_003.jsonl
4dddf9c7fa10167424d2b2e288128e76
256 megabytes
["3\n2 3\n3 1\n3 2\n1 3\n3 3\n1 3"]
PASSED
for _ in range(input()): a1,b1=map(int,raw_input().split()) a2,b2=map(int,raw_input().split()) if a1==a2 and b1+b2==a1: print "YES" elif a1==b2 and a2+b1==a1: print "YES" elif a2==b1 and a1+b2==a2: print "YES" elif b1==b2 and a1+a2==b1: print "YES" else: print "NO"
1590154500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 1 1 1\n1 4 3 2 1\n1 3 3\n1"]
188c9dbb3e1851b7b762ed6b4b23d1bd
NoteIn the first test case one of the optimal solutions is to increase the whole array on each operation (that is, choose the suffix starting at index $$$1$$$). The final array $$$[11, 12, 13, 14]$$$ contains $$$0$$$ inversions.In the second test case, $$$a$$$ will be equal to $$$[2, 4, 3, 5, 6]$$$, $$$[2, 4, 3, 7, 8]$$$, $$$[2, 4, 6, 10, 11]$$$, $$$[2, 8, 10, 14, 15]$$$ and $$$[7, 13, 15, 19, 20]$$$ after the first, second, third, fourth, and fifth operations, respectively. So the final array $$$a$$$ has zero inversions.
You are given a permutation $$$a$$$ of size $$$n$$$ and you should perform $$$n$$$ operations on it. In the $$$i$$$-th operation, you can choose a non-empty suffix of $$$a$$$ and increase all of its elements by $$$i$$$. How can we perform the operations to minimize the number of inversions in the final array?Note that you can perform operations on the same suffix any number of times you want.A permutation of size $$$n$$$ is an array of size $$$n$$$ such that each integer from $$$1$$$ to $$$n$$$ occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array $$$a$$$ is a pair of indices $$$(i, j)$$$ such that $$$i &gt; j$$$ and $$$a_{i} &lt; a_{j}$$$.
For each test case, print $$$n$$$ integers $$$x_{1}, x_{2}, \ldots, x_{n}$$$ ($$$1 \le x_{i} \le n$$$ for each $$$1 \le i \le n$$$) indicating that the $$$i$$$-th operation must be applied to the suffix starting at index $$$x_{i}$$$. If there are multiple answers, print any of them.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ distinct integers $$$a_{1}, a_{2}, \dots, a_{n}$$$ ($$$1 \le a_i \le n$$$), the initial permutation $$$a$$$. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,300
train_103.jsonl
dd8c1cc7844f7e1b3b876232b0071137
256 megabytes
["4\n\n4\n\n1 2 3 4\n\n5\n\n1 3 2 4 5\n\n3\n\n2 3 1\n\n1\n\n1"]
PASSED
import collections import heapq import sys import math import itertools import bisect from io import BytesIO, IOBase import os ###################################################################################### #--------------------------------------funs here-------------------------------------# ###################################################################################### def values(): return tuple(map(int, sys.stdin.readline().split())) def inlsts(): return [int(i) for i in sys.stdin.readline().split()] def inp(): return int(sys.stdin.readline()) def instr(): return sys.stdin.readline().strip() def words(): return [i for i in sys.stdin.readline().strip().split()] def chars(): return [i for i in sys.stdin.readline().strip()] ###################################################################################### #--------------------------------------code here-------------------------------------# ###################################################################################### def solve(): n = inp() l=values() d={} for i in range(n): d[l[i]]=i print(*[d[n-i]+1 for i in range(n)]) if __name__ == "__main__": for i in range(inp()): solve()
1665844500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES", "YES", "NO", "NO"]
d629d09782a7af0acc359173ac4b4f0a
NoteIn the first example a wildcard character '*' can be replaced with a string "force". So the string $$$s$$$ after this replacement is "codeforces" and the answer is "YES".In the second example a wildcard character '*' can be replaced with an empty string. So the string $$$s$$$ after this replacement is "vkcup" and the answer is "YES".There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $$$t$$$ so the answer is "NO".
You are given two strings $$$s$$$ and $$$t$$$. The string $$$s$$$ consists of lowercase Latin letters and at most one wildcard character '*', the string $$$t$$$ consists only of lowercase Latin letters. The length of the string $$$s$$$ equals $$$n$$$, the length of the string $$$t$$$ equals $$$m$$$.The wildcard character '*' in the string $$$s$$$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $$$s$$$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $$$s$$$ to obtain a string $$$t$$$, then the string $$$t$$$ matches the pattern $$$s$$$.For example, if $$$s=$$$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".If the given string $$$t$$$ matches the given string $$$s$$$, print "YES", otherwise print "NO".
Print "YES" (without quotes), if you can obtain the string $$$t$$$ from the string $$$s$$$. Otherwise print "NO" (without quotes).
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the length of the string $$$t$$$, respectively. The second line contains string $$$s$$$ of length $$$n$$$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $$$t$$$ of length $$$m$$$, which consists only of lowercase Latin letters.
standard output
standard input
PyPy 3
Python
1,200
train_018.jsonl
e9f7a76fa6922a64caabc97b99848854
256 megabytes
["6 10\ncode*s\ncodeforces", "6 5\nvk*cup\nvkcup", "1 1\nv\nk", "9 6\ngfgf*gfgf\ngfgfgf"]
PASSED
n,m=map(int,input().split()) s=input() t=input() if(m<n-1): print('NO') else: if('*' in s): i=0 f=1 while(i<n and s[i]!='*'): if(s[i]!=t[i]): f=0 break else: i=i+1 if(f==1): i=n-1 j=m-1 while(s[i]!='*'): if(s[i]!=t[j]): f=0 break else: i=i-1 j=j-1 if(f==1): print("YES") else: print("NO") else: print("NO") else: if(s==t): print("YES") else: print("NO")
1534516500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["abcd", "codeforces"]
9c90974a0bb860a5e180760042fd5045
null
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
standard output
standard input
Python 3
Python
1,100
train_008.jsonl
a2e817889f8204c5dc430678c3715f49
256 megabytes
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
PASSED
n, m = list(map(int, input().strip().split())) A = [[0] * m] * n for r in range(n): A[r] = list(input().strip()) def in_row(A, r, c): x = A[r][c] left, right = A[r][:c], A[r][c + 1:] if (x in left) or (x in right): return True def in_col(A, r, c): x = A[r][c] for row in range(n): if row == r: continue if A[row][c] == x: return True out = '' for r in range(n): for c in range(m): if not in_row(A, r, c) and not in_col(A, r, c): out += A[r][c] print(out)
1308236400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["2\n2 5 6 7\n3 6 4 5\n0"]
cbd550be6982ef259de500194c33eff2
NoteNote the graph can be unconnected after a certain operation.Consider the first test case of the example: The red edges are removed, and the green ones are added.
Nastia has an unweighted tree with $$$n$$$ vertices and wants to play with it!The girl will perform the following operation with her tree, as long as she needs: Remove any existing edge. Add an edge between any pair of vertices. What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than $$$2$$$.
For each test case in the first line print a single integer $$$k$$$ — the minimum number of operations required to obtain a bamboo from the initial tree. In the next $$$k$$$ lines print $$$4$$$ integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1, y_1, x_2, y_{2} \le n$$$, $$$x_1 \neq y_1$$$, $$$x_2 \neq y_2$$$) — this way you remove the edge $$$(x_1, y_1)$$$ and add an undirected edge $$$(x_2, y_2)$$$. Note that the edge $$$(x_1, y_1)$$$ must be present in the graph at the moment of removing.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of vertices in the tree. Next $$$n - 1$$$ lines of each test cases describe the edges of the tree in form $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$). It's guaranteed the given graph is a tree and the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,500
train_099.jsonl
200a857939310d5a9e10ea9da1ec289a
256 megabytes
["2\n7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n4\n1 2\n1 3\n3 4"]
PASSED
from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def fun(adj,v,p,rem): ans=0 f=0 nf=0 for i in adj[v]: if i==p: continue (cans,cf) = yield fun(adj,i,v,rem) if cf==0: nf+=1 rem.add((v,i)) ans+=1 else: f+=1 if f>2: ans+=1 rem.add((v,i)) ans += cans if f<2: yield (ans,1) else: yield (ans,0) def get(parent,a): if parent[a]==a: return a return get(parent,parent[a]) def merge(parent,a,b): a = get(parent,a) b = get(parent,b) if a>b: a,b = b,a parent[b]=a return t = int(input()) for i in range(t): n = int(input()) adj = [[] for i in range(n)] edges = set() for j in range(n-1): [a,b] = [int(i) for i in input().split()] edges.add((a-1,b-1)) adj[a-1].append(b-1) adj[b-1].append(a-1) rem = set() print(fun(adj,0,-1,rem)[0]) for (a,b) in rem: try: edges.remove((a,b)) except: pass try: edges.remove((b,a)) except: pass parent = [i for i in range(n)] degree = [0]*n for edge in edges: degree[edge[0]]+=1 degree[edge[1]]+=1 merge(parent,edge[0],edge[1]) d = {} for i in range(n): if degree[i]>1: continue p = get(parent,i) if not p in d: d[p] = (i,i) else: d[p] = (d[p][0],i) l = list(d.values()) op = [] for i in range(len(l)-1): op.append([l[i][1],l[i+1][0]]) rem = list(rem) for i in range(len(op)): print(1+rem[i][1],1+rem[i][0],1+op[i][0],1+op[i][1])
1620398100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["Vanya\nVova\nVanya\nBoth", "Both\nBoth"]
f98ea97377a06963d1e6c1c215ca3a4a
NoteIn the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.
Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.
The first line contains three integers n,x,y (1 ≤ n ≤ 105, 1 ≤ x, y ≤ 106) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1 ≤ ai ≤ 109) — the number of hits needed do destroy the i-th monster.
standard output
standard input
Python 3
Python
1,800
train_010.jsonl
f728236602f12a1581c0b821bbf5d3af
256 megabytes
["4 3 2\n1\n2\n3\n4", "2 1 1\n1\n2"]
PASSED
n, x, y = map(int, input().split()) for _ in range(n): a = int(input()) c1, c2 = ((a + 1) * x // (x + y)) / x, ((a + 1) * y // (x + y)) / y if c1 == c2: print('Both') elif c1 > c2: print('Vanya') else: print('Vova')
1417451400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]