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
1 second
["252", "2"]
c408b1d198c7c88fc635936d960c962a
NoteIn the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively.Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.You are asked to find the brightness of the chosen pair if both of them choose optimally.
Print a single integerΒ β€” the brightness of the chosen pair.
The first line contains two space-separated integers n and m (2 ≀ n, m ≀ 50). The second line contains n space-separated integers a1, a2, ..., an. The third line contains m space-separated integers b1, b2, ..., bm. All the integers range from  - 109 to 109.
standard output
standard input
Python 3
Python
1,400
train_007.jsonl
14763b37feb2c8be8f7c21dc565cfcbb
256 megabytes
["2 2\n20 18\n2 14", "5 3\n-1 0 1 2 3\n-1 0 1"]
PASSED
n, m = [int(x) for x in input().split()] lstT = [int(x) for x in input().split()] lstB = [int(x) for x in input().split()] z=-9999999999999999999999999999 T=0 B=0 for i in range(n): for j in range(m): if z<lstT[i]*lstB[j]: T=i B=j z=lstT[i]*lstB[j] lol = -99999999999999999999 for i in range(n): for j in range(m): if T!=i: lol = max(lol, lstT[i]*lstB[j]) print(lol)
1518609900
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["1.000000000000", "-1", "1.250000000000"]
1bcf130890495bcca67b4b0418476119
NoteYou can see following graphs for sample 1 and sample 3.
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output  - 1 as the answer.
Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109).
standard output
standard input
Python 3
Python
1,700
train_026.jsonl
5daf35b34ff84e5c03e13edc0a45162e
256 megabytes
["3 1", "1 3", "4 1"]
PASSED
from math import floor def main(): a, b = map(int, input().split()) if (b > a): print(-1) return y = (a + b) / 2 k = y // b print(y / k) main()
1442416500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0 1\n1 1\n0 7"]
09625e65e62fc1c618d12969932508de
NoteIn the first test case, Alice serves the ball and spends $$$1$$$ stamina. Then Bob returns the ball and also spends $$$1$$$ stamina. Alice can't return the ball since she has no stamina left and loses the play. Both of them ran out of stamina, so the game is over with $$$0$$$ Alice's wins and $$$1$$$ Bob's wins.In the second test case, Alice serves the ball and spends $$$1$$$ stamina. Bob decides not to return the ballΒ β€” he loses the play but saves stamina. Alice, as the winner of the last play, serves the ball in the next play and spends $$$1$$$ more stamina. This time, Bob returns the ball and spends $$$1$$$ stamina. Alice doesn't have any stamina left, so she can't return the ball and loses the play. Both of them ran out of stamina, so the game is over with $$$1$$$ Alice's and $$$1$$$ Bob's win.In the third test case, Alice serves the ball and spends $$$1$$$ stamina. Bob returns the ball and spends $$$1$$$ stamina. Alice ran out of stamina, so she can't return the ball and loses the play. Bob, as a winner, serves the ball in the next $$$6$$$ plays. Each time Alice can't return the ball and loses each play. The game is over with $$$0$$$ Alice's and $$$7$$$ Bob's wins.
Alice and Bob play ping-pong with simplified rules.During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.Alice has $$$x$$$ stamina and Bob has $$$y$$$. To hit the ball (while serving or returning) each player spends $$$1$$$ stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.Calculate the resulting number of Alice's and Bob's wins.
For each test case, print two integersΒ β€” the resulting number of Alice's and Bob's wins, if both of them play optimally.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€” the number of test cases. The first and only line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^6$$$)Β β€” Alice's and Bob's initial stamina.
standard output
standard input
PyPy 2
Python
null
train_006.jsonl
057db5c181c20c60a13051da023f68b6
256 megabytes
["3\n1 1\n2 1\n1 7"]
PASSED
from collections import Counter, defaultdict, deque import bisect from sys import stdin, stdout from itertools import repeat import math def inp(force_list=False): re = map(int, raw_input().split()) if len(re) == 1 and not force_list: return re[0] return re def inst(): return raw_input().strip() def gcd(x, y): while(y): x, y = y, x % y return x mod = 1000000007 def my_main(): kase = inp() ans = [] for i in range(kase): x, y = inp() if x==y: ans.append("%s %s" % (x-1, x)) elif x>y: ans.append("%s %s" % (x-1, y)) else: ans.append("%s %s" % (x-1, y)) print '\n'.join(ans) my_main()
1606746900
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["8\n2\n4"]
a4f183775262fdc42dc5fc621c196ec9
NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.
You have a string $$$s$$$ β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid: you can place the robot in the cell $$$(3, 2)$$$; the robot performs the command 'D' and moves to $$$(3, 3)$$$; the robot performs the command 'S' and moves to $$$(4, 3)$$$; the robot performs the command 'A' and moves to $$$(4, 2)$$$; the robot performs the command 'W' and moves to $$$(3, 2)$$$; the robot performs the command 'W' and moves to $$$(2, 2)$$$; the robot performs the command 'A' and moves to $$$(2, 1)$$$; the robot performs the command 'W' and moves to $$$(1, 1)$$$. You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?
Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.
The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) β€” the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 2
Python
2,100
train_004.jsonl
74f687aef1c1cd1ad27b5c6c7f0e8b99
256 megabytes
["3\nDSAWWAW\nD\nWA"]
PASSED
import sys import math import bisect import atexit import io import heapq from collections import defaultdict, Counter MOD = int(1e9+7) # n = map(int, raw_input().split()) # input = map(int, raw_input().split()) def main(): n = map(int, raw_input().split())[0] for i in range(n): st = raw_input() dx, dy = defaultdict(list), defaultdict(list) x, y = 0, 0 mxx, mix, mxy, miy = 0, 0, 0, 0 dy[0].append(0) dx[0].append(0) for idx, c in enumerate(st): if c=='A': y-=1 dy[y].append(idx) if c=='D': y+=1 dy[y].append(idx) if c=='W': x+=1 dx[x].append(idx) if c=='S': x-=1 dx[x].append(idx) mxx = max(x, mxx) mix = min(mix, x) mxy = max(mxy, y) miy = min(miy, y) # print mxx,mix,mxy,miy xx, yy = 0, 0 if mxx!=0: if mxx - mix >1 and dx[mxx] and dx[mix] and dx[mxx][0] > dx[mix][-1]: xx = 1 if mix!=0: if mxx - mix >1 and dx[mxx] and dx[mix] and dx[mix][0] > dx[mxx][-1]: xx = 1 # print dy[mxy],mxy if mxy!=0: if mxy - miy >1 and dy[mxy] and dy[miy] and dy[mxy][0]>dy[miy][-1]: yy = 1 if miy!=0: if mxy - miy >1 and dy[mxy] and dy[miy] and dy[mxy][-1]<dy[miy][0]: yy = 1 print min((mxx-mix+1-xx)*(mxy-miy+1), (mxx-mix+1)*(mxy-miy+1-yy)) main()
1565188500
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
4 seconds
["42", "30"]
5179d7554a08d713da7597db41f0ed43
NoteThe following figure shows all $$$10$$$ possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to $$$42$$$:
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $$$100$$$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree β€” a connected undirected graph consisting of $$$n$$$ vertices connected by $$$n - 1$$$ edges. The tree is rooted at vertex $$$1$$$. A vertex $$$u$$$ is called an ancestor of $$$v$$$ if it lies on the shortest path between the root and $$$v$$$. In particular, a vertex is an ancestor of itself.Each vertex $$$v$$$ is assigned its beauty $$$x_v$$$ β€” a non-negative integer not larger than $$$10^{12}$$$. This allows us to define the beauty of a path. Let $$$u$$$ be an ancestor of $$$v$$$. Then we define the beauty $$$f(u, v)$$$ as the greatest common divisor of the beauties of all vertices on the shortest path between $$$u$$$ and $$$v$$$. Formally, if $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ are the vertices on the shortest path between $$$u$$$ and $$$v$$$, then $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Here, $$$\gcd$$$ denotes the greatest common divisor of a set of numbers. In particular, $$$f(u, u) = \gcd(x_u) = x_u$$$.Your task is to find the sum$$$$$$ \sum_{u\text{ is an ancestor of }v} f(u, v). $$$$$$As the result might be too large, please output it modulo $$$10^9 + 7$$$.Note that for each $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. In particular, $$$\gcd(0, 0) = 0$$$.
Output the sum of the beauties on all paths $$$(u, v)$$$ such that $$$u$$$ is ancestor of $$$v$$$. This sum should be printed modulo $$$10^9 + 7$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) β€” the number of vertices in the tree. The following line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). The value $$$x_v$$$ denotes the beauty of vertex $$$v$$$. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) β€” the vertices connected by a single edge.
standard output
standard input
PyPy 2
Python
2,000
train_023.jsonl
1f4f2d3e8d4997aa850c286fe1a02901
768 megabytes
["5\n4 5 6 0 8\n1 2\n1 3\n1 4\n4 5", "7\n0 2 3 0 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"]
PASSED
from __future__ import division, print_function from collections import deque def main(): def gcd(a,b): if a<b: a,b=b,a while b: a,b=b,a%b return a n=int(input()) val=list(map(int,input().split())) gcds=[ {} for _ in range(n) ] edges={} for i in range(n-1): u,v=map(int,input().split()) if u not in edges: edges[u]=[v] else : edges[u].append(v) if v not in edges: edges[v]=[u] else : edges[v].append(u) visited=[0]*n q=deque() q.append(1) visited[0]=1 mod=10**9+7 result=0 while q: u=q.popleft() x=val[u-1] if x not in gcds[u-1]: gcds[u-1][x]=1 else : gcds[u-1][x]+=1 for k in gcds[u-1]: result=(result+gcds[u-1][k]*k)%mod for v in edges[u]: if visited[v-1]==0: temp=val[v-1] for item in gcds[u-1]: a=gcd(item,temp) if a not in gcds[v-1]: gcds[v-1][a]=gcds[u-1][item] else : gcds[v-1][a]+=gcds[u-1][item] visited[v-1]=1 q.append(v) print(result) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main()
1569143100
[ "number theory", "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 1 ]
1 second
["01001"]
332902284154faeaf06d5d05455b7eb6
null
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1Β·1 + 1Β·0 + 1Β·1) + (0Β·1 + 1Β·1 + 1Β·0) + (1Β·1 + 0Β·1 + 0Β·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
The first line of input contains an integer n (1 ≀ n ≀ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≀ aij ≀ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≀ q ≀ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i β€” flip the values of the i-th row; 2 i β€” flip the values of the i-th column; 3 β€” output the unusual square of A. 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 3
Python
1,600
train_013.jsonl
26e3467d20650f5f137acf9338ed9db5
256 megabytes
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
PASSED
from sys import stdin n = int(stdin.readline()) dot = 0 j = 0 for i in range(n): line = stdin.readline() if line[j] == '1': dot ^= 1 j += 2 out = [] stdin.readline() for query in stdin: if len(query) < 3: out.append('1' if dot else '0') else: dot ^= 1 print(''.join(out))
1395502200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 -1 3 4"]
b08f925e09a9c2e7ccc6a8c5c143fc5f
NoteIf initially Pak Chanek's left hand is on vertex $$$1$$$ and his right hand is on vertex $$$5$$$, Pak Chanek can do the following moves: Move his right hand to vertex $$$4$$$ in $$$1$$$ second. Move his left hand to vertex $$$2$$$ in $$$2$$$ seconds. Move his left hand to vertex $$$4$$$ in $$$1$$$ second. In total it needs $$$1+2+1=4$$$ seconds. It can be proven that there is no other way that is faster.
Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $$$N$$$ vertices and $$$M$$$ edges. In the graph, edge $$$i$$$ connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. By using the $$$i$$$-th edge, something can move from $$$U_i$$$ to $$$V_i$$$, but not from $$$V_i$$$ to $$$U_i$$$.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $$$U_i$$$ to vertex $$$V_i$$$, Pak Chanek needs a time of $$$W_i$$$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each $$$p$$$ satisfying $$$2 \leq p \leq N$$$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$p$$$, or report if it is impossible.
Output a line containing $$$N-1$$$ integers. The $$$j$$$-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$j+1$$$, or $$$-1$$$ if it is impossible.
The first line contains two integers $$$N$$$ and $$$M$$$ ($$$2 \leq N \leq 10^5$$$, $$$0 \leq M \leq 2 \cdot 10^5$$$) β€” the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$M$$$ lines contains three integers $$$U_i$$$, $$$V_i$$$, and $$$W_i$$$ ($$$1 \le U_i, V_i \le N$$$, $$$U_i \neq V_i$$$, $$$1 \le W_i \le 10^9$$$) β€” a directed edge that connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. There is no pair of different edges $$$i$$$ and $$$j$$$ such that $$$U_i = U_j$$$ and $$$V_i = V_j$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_093.jsonl
76c7a785a67de7d4e66b3123ddeb6ade
256 megabytes
["5 7\n1 2 2\n2 4 1\n4 1 4\n2 5 3\n5 4 1\n5 2 4\n2 1 1"]
PASSED
import sys from array import array from heapq import * class graph: def __init__(self, n): self.n = n self.gdict = [array('i') for _ in range(n + 1)] self.weight = [array('i') for _ in range(n + 1)] self.dir = [array('b') for _ in range(n + 1)] def add_edge(self, node1, node2): self.gdict[node1].append(node2) self.gdict[node2].append(node1) self.dir[node1].append(1) self.dir[node2].append(0) def add_wedge(self, node1, node2, w): self.weight[node1].append(w) self.weight[node2].append(w) def dijkstra(self, root): # initial distances self.dist = [10 ** 18] * (self.n + 1) vis = array('b', [0] * (self.n + 1)) self.dist[root], que = 0, [(0, root)] # traverse all nodes while que: d, u = heappop(que) # traverse all adjacent nodes and update distances if not vis[u]: for i in range(len(self.gdict[u])): v, d2, dir = self.gdict[u][i], self.weight[u][i], self.dir[u][i] cost = d2 + self.dist[u] if not vis[v] and dir and cost < self.dist[v]: self.dist[v] = cost heappush(que, (self.dist[v], v)) vis[u] = 1 vis = array('b', [0] * (self.n + 1)) que = [(self.dist[i], i) for i in range(1, self.n + 1)] heapify(que) while que: d, u = heappop(que) # traverse all adjacent nodes and update distances if not vis[u]: for i in range(len(self.gdict[u])): v, d2, dir = self.gdict[u][i], self.weight[u][i], self.dir[u][i] cost = d2 + self.dist[u] if not vis[v] and not dir and cost < self.dist[v]: self.dist[v] = cost heappush(que, (self.dist[v], v)) vis[u] = 1 for i in range(1, self.n + 1): if self.dist[i] == 10 ** 18: self.dist[i] = -1 print(' '.join(map(str, self.dist[2:]))) input = lambda: sys.stdin.buffer.readline().decode().strip() n, m = map(int, input().split()) g = graph(n) for _ in range(m): u, v, w = map(int, input().split()) g.add_edge(u, v) g.add_wedge(u, v, w) g.dijkstra(1)
1662298500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0", "2"]
b81e7a786e4083cf7188f718bc045a85
NoteIn the second sample Joe can act like this:The diamonds' initial positions are 4 1 3.During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket.By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off.During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket.By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off.Now Joe leaves with 2 diamonds in his pocket.
It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an n - 1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than m times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only k minutes left before morning, and on each of these k minutes he can perform no more than m operations. All that remains in Joe's pocket, is considered his loot.Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.
Print a single number β€” the maximum number of diamonds Joe can steal.
The first line contains integers n, m and k (1 ≀ n ≀ 104, 1 ≀ m, k ≀ 109). The next line contains n numbers. The i-th number is equal to the amount of diamonds in the i-th cell β€” it is an integer from 0 to 105.
standard output
standard input
Python 3
Python
1,800
train_007.jsonl
8c9e73e8b6fb5e5c62105be1bded11e6
256 megabytes
["2 3 1\n2 3", "3 2 2\n4 1 3"]
PASSED
n, m, k = map(int, input().split()) a = list(map(int, input().split())) if n % 2 == 0: print('0') else: print(min(m // (n // 2 + 1) * k, min(a[::2]))) # Made By Mostafa_Khaled
1308236400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n80\n5\ncomposite", "58\n59\n78\n78\n2\nprime"]
8cf479fd47050ba96d21f3d8eb43c8f0
NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).
This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden numberΒ β€” an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x &gt; 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x &gt; 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
Up to 20 times you can ask a queryΒ β€” print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacking. To hack someone, as the input you should print the hidden numberΒ β€” one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.
After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.
standard output
standard input
Python 3
Python
1,400
train_017.jsonl
65f48ef53786850316f3d6ea62b265bb
256 megabytes
["yes\nno\nyes", "no\nyes\nno\nno\nno"]
PASSED
counter = 0; for i in [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,4,9,25,49]: print(i); counter += (input() == 'yes'); if counter > 1: print("composite"); break; else: print("prime");
1465403700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6\n1\n2"]
fb0a4c8f737c36596c2d8c1ae0d1e34e
NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.
Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types: it can contain a single sticker and no toy; it can contain a single toy and no sticker; it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.
Print $$$T$$$ integers (one number per query) β€” the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \le n \le 10^9$$$, $$$1 \le s, t \le n$$$, $$$s + t \ge n$$$) β€” the number of eggs, stickers and toys. All queries are independent.
standard output
standard input
PyPy 3
Python
900
train_006.jsonl
07e67f263ee975feb396e9f7d7837706
256 megabytes
["3\n10 5 7\n10 10 10\n2 1 1"]
PASSED
for _ in range(int(input().strip())): n, s, t = map(int, input().strip().split()) if s == t == n: print(1) else: common = s+t-n print(max(s, t)-common+1)
1561905900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n1 2\n2 3", "4\n1 2\n2 3\n3 4\n4 1"]
3f86b3cec02aafb24c5aeb2648cc3df9
null
During a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.
On the first line must be printed number m β€” the maximal number of roads in Berland. Then print m lines containing two numbers each β€” the numbers of cities that the given road joins. The cities are numbered with integers from 1 to n. If there are several variants of solving the problem, print any of them.
The first line contains an integer n (1 ≀ n ≀ 100) β€” the number of cities in Berland.
standard output
standard input
Python 3
Python
1,900
train_023.jsonl
69157ad433338658d945d09cab6f1303
256 megabytes
["3", "4"]
PASSED
###### https://codeforces.com/problemset/problem/41/E n = int(input()) a = list(range(1, n+1)) edge = [] used = [] for i, u in enumerate(a): for j in range(1, n, 2): if i + j >= n : continue ind = i+j edge.append([u, a[ind]]) print(len(edge)) for u, v in edge: print('{} {}'.format(u, v))
1289232000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["hHheidi Hei", "bbbba ba", "aaabb ab"]
fa626fb33f04323ec2dbbc235cabf7d3
NoteAn occurrence of p as a subsequence in s should be thought of as a set of positions in s such that the letters at these positions, in order, form p. The number of occurences is thus the number of such sets. For example, ab appears 6 times as a subsequence in aaabb, for the following sets of positions: {1, 4}, {1, 5}, {2, 4}, {2, 5}, {3, 4}, {3, 5} (that is, we should choose one of the a's and one of the b's).
Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she wants the phrase to appear n times in the post. She is asking you to design a post (string) s and a hidden phrase p such that p appears in s as a subsequence exactly n times.
The output should contain two nonempty strings s and p separated by a single space. Each string should be composed of letters (a-z and A-Z: both lowercase and uppercase are allowed) and have length at most 200. The number of occurrences of p in s as a subsequence should be exactly n. If there are many possible solutions, output any of them. It is guaranteed that at least one solution exists.
The first and only line of input contains a single integer n (1 ≀ n ≀ 1 000 000).
standard output
standard input
Python 3
Python
2,200
train_079.jsonl
bfdb3b5506c749b292c0228724db6f98
256 megabytes
["2", "4", "6"]
PASSED
def getstr(n): if n==1: return 'a','',1 elif n==2: return 'ab','b',2 else: if n%2==0: p,u,now=getstr((n-2)//2) c = chr(ord('a')+now) return p+c,c+u+c+c,now+1 else: p,u,now=getstr((n-1)//2) c = chr(ord('a')+now) return p+c,u+c+c,now+1 n = int(input()) ans = getstr(n) print(ans[0]+ans[1],ans[0])
1495958700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n1 4\n4 1\n1\n4 2\n0\n0\n1\n2 10\n0"]
5f0f79e39aaf4abc8c7414990d1f8be1
NoteIn the first example, two possible ways to divide $$$a$$$ into permutations are $$$\{1\} + \{4, 3, 2, 1\}$$$ and $$$\{1,4,3,2\} + \{1\}$$$.In the second example, the only way to divide $$$a$$$ into permutations is $$$\{2,4,1,3\} + \{2,1\}$$$.In the third example, there are no possible ways.
The sequence of $$$m$$$ integers is called the permutation if it contains all integers from $$$1$$$ to $$$m$$$ exactly once. The number $$$m$$$ is called the length of the permutation.Dreamoon has two permutations $$$p_1$$$ and $$$p_2$$$ of non-zero lengths $$$l_1$$$ and $$$l_2$$$.Now Dreamoon concatenates these two permutations into another sequence $$$a$$$ of length $$$l_1 + l_2$$$. First $$$l_1$$$ elements of $$$a$$$ is the permutation $$$p_1$$$ and next $$$l_2$$$ elements of $$$a$$$ is the permutation $$$p_2$$$. You are given the sequence $$$a$$$, and you need to find two permutations $$$p_1$$$ and $$$p_2$$$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)
For each test case, the first line of output should contain one integer $$$k$$$: the number of ways to divide $$$a$$$ into permutations $$$p_1$$$ and $$$p_2$$$. Each of the next $$$k$$$ lines should contain two integers $$$l_1$$$ and $$$l_2$$$ ($$$1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$$$), denoting, that it is possible to divide $$$a$$$ into two permutations of length $$$l_1$$$ and $$$l_2$$$ ($$$p_1$$$ is the first $$$l_1$$$ elements of $$$a$$$, and $$$p_2$$$ is the last $$$l_2$$$ elements of $$$a$$$). You can print solutions in any order.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$): the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n-1$$$). The total sum of $$$n$$$ is less than $$$200\,000$$$.
standard output
standard input
PyPy 3
Python
1,400
train_008.jsonl
5999fe995fe1ff8007f207f1cda16b1f
256 megabytes
["6\n5\n1 4 3 2 1\n6\n2 4 1 3 2 1\n4\n2 1 1 3\n4\n1 3 3 1\n12\n2 1 3 4 5 6 7 8 9 1 10 2\n3\n1 1 1"]
PASSED
import os, sys, atexit from io import BytesIO, StringIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline _OUTPUT_BUFFER = StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) t = int(input()) while t: t += -1 n = int(input()) l = list(map(int, input().split())) count = [0] * (n + 1) for i in l: count[i] -= -1 l1 = 0 l2 = 0 ch = 0 for i in range(1, n + 1): if count[i] == 2: l1 = i else: break l2 = n - l1 p1 = [0] * (l1 + 1) p2 = [0] * (l2 + 1) for i in range(l1): if l[i] > l1: ch = 1 break p1[l[i]] = 1 for i in range(l1, n): if l[i] > l2: ch = 1 break p2[l[i]] = 1 ch1 = 1 ch2 = 1 if 0 in p1[1: l1 + 1] or 0 in p2[1: l2 + 1] or ch: ch1 = 0 l1, l2 = l2, l1 p1 = [0] * (l1 + 1) p2 = [0] * (l2 + 1) ch = 0 for i in range(l1): if l[i] > l1: ch = 1 break p1[l[i]] = 1 for i in range(l1, n): if l[i] > l2: ch = 1 break p2[l[i]] = 1 if 0 in p1[1: l1 + 1] or 0 in p2[1: l2 + 1] or ch: ch2 = 0 if ch1: if ch2: if l1 != l2: print(2) print(l1, l2) print(l2, l1) else: print(1) print(l1, l2) else: print(1) print(l2, l1) else: if ch2: print(1) print(l1, l2) else: print(0)
1585924500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["io", "ooo"]
214cdb73c2fb5ab995eb5aec76e5f4fb
null
It is well known that Berland has n cities, which form the Silver ring β€” cities i and i + 1 (1 ≀ i &lt; n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?
If it is impossible to build the roads in such a way that no two roads intersect, output Impossible. Otherwise print m characters. i-th character should be i, if the road should be inside the ring, and o if the road should be outside the ring. If there are several solutions, output any of them.
The first line contains two integers n and m (4 ≀ n ≀ 100, 1 ≀ m ≀ 100). Each of the following m lines contains two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi). No two cities will be connected by more than one road in the list. The list will not contain the roads which exist in the Silver ring.
standard output
standard input
Python 3
Python
2,200
train_006.jsonl
f92c26db33d04e7f848e57b8f11d9088
256 megabytes
["4 2\n1 3\n2 4", "6 3\n1 3\n3 5\n5 1"]
PASSED
n, m = map(int, input().split()) road = [[] for i in range(m)] for i in range(m): road[i] = [i] + list(map(int, input().split())) + ['NONE'] for i in road: if i[2] < i[1]: i[1], i[2] = i[2], i[1] i[1], i[2] = i[1] - 1, i[2] - 1 participation = [[] for i in range(m)] for i in range(len(road)): for j in range(i + 1, len(road)): if (road[j][1] < road[i][1] < road[j][2]) ^ (road[j][1] < road[i][2] < road[j][2]): if road[j][1] != road[i][1] and road[j][2] != road[i][1] and road[j][1] != road[i][2] and road[j][2] != road[i][2]: participation[i].append(j) participation[j].append(i) result = "" mark = [0] * m stack = [] while sum(mark) != m: if len(stack) == 0: for i in range(len(mark)): if mark[i] == 0: stack.append(i) break index = stack.pop() mark[index] = 1 if road[index][3] == "NONE": road[index][3] = "i" for i in participation[index]: if road[i][3] == road[index][3]: result = "Impossible" print(result) break elif road[index][3] != "i" and road[i][3] == "NONE": road[i][3] = "i" stack.append(i) elif road[index][3] == "i" and road[i][3] == "NONE": road[i][3] = "o" stack.append(i) if result == "Impossible": break if result != "Impossible": for i in road: result += i[3] print(result)
1284130800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2\n3 4 \n4\n4 5 6 7"]
6e0ca509476a3efa3a352ca08c43023e
NoteIn the first sample case, closing any two spots is suitable.In the second sample case, closing only the spot $$$1$$$ is also suitable.
Arthur owns a ski resort on a mountain. There are $$$n$$$ landing spots on the mountain numbered from $$$1$$$ to $$$n$$$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.Arthur doesn't want to close too many spots. He will be happy to find any way to close at most $$$\frac{4}{7}n$$$ spots so that the remaining part is safe. Help him find any suitable way to do so.
For each test case, print a single integer $$$k$$$ ($$$0 \leq k \leq \frac{4}{7}n$$$)Β β€” the number of spots to be closed. In the next line, print $$$k$$$ distinct integersΒ β€” indices of all spots to be closed, in any order. If there are several answers, you may output any of them. Note that you don't have to minimize $$$k$$$. It can be shown that a suitable answer always exists.
The first line contains a single positive integer $$$T$$$Β β€” the number of test cases. $$$T$$$ test case description follows. The first line of each description contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)Β β€” the number of landing spots and tracks respectively. The following $$$m$$$ lines describe the tracks. Each of these lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x &lt; y \leq n$$$)Β β€” indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,500
train_014.jsonl
60417202e4069bfd0b129bf017b45bb2
512 megabytes
["2\n4 6\n1 2\n1 3\n2 3\n2 4\n3 4\n3 4\n7 6\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"]
PASSED
import io import os from collections import Counter, defaultdict, deque import random from heapq import heappush, heappop, heapify def solve(N, M, tracks): stops = range(1, N + 1) graph = [[] for i in range(N + 1)] graphT = [[] for i in range(N + 1)] for u, v in tracks: graph[u].append(v) graphT[v].append(u) # Since out degree is limited to 2, dangerous pairs of paths doesn't explode danger = [] for u in stops: for fr in graphT[u]: for to in graph[u]: danger.append([fr, u, to]) if not danger: return "0\n" del graph del graphT maxRemove = 4 * N // 7 dangerIds = list(range(len(danger))) removed = set() for i in dangerIds: needsRemove = [u for u in danger[i] if u not in removed] if len(needsRemove) == 3: removed.add(needsRemove[-1]) # every triplet of dangerous had something removed, so they aren't dangerous anymore assert len(removed) <= maxRemove return str(len(removed)) + "\n" + " ".join(map(str, removed)) if True: tracks = [] for i in range(1, 10 ** 4): tracks.append((i, 2 * i)) tracks.append((i, 2 * i + 1)) N = 2 * 10 ** 5 solve(N, len(tracks), tracks) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): N, M = [int(x) for x in input().split()] tracks = [[int(x) for x in input().split()] for i in range(M)] ans = solve(N, M, tracks) print(ans)
1592491500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2 2"]
44542e73195573debb4ab113bab5ee23
null
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.The river banks can be assumed to be vertical straight lines x = a and x = b (0 &lt; a &lt; b).The west village lies in a steppe at point O = (0, 0). There are n pathways leading from the village to the river, they end at points Ai = (a, yi). The villagers there are plain and simple, so their pathways are straight segments as well.The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points Bi = (b, y'i). The lengths of all these paths are known, the length of the path that leads from the eastern village to point Bi, equals li.The villagers want to choose exactly one point on the left bank of river Ai, exactly one point on the right bank Bj and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OAi| + |AiBj| + lj, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x1, y1) and (x2, y2) equals .Help them and find the required pair of points.
Print two integers β€” the numbers of points on the left (west) and right (east) banks, respectively, between which you need to build a bridge. You can assume that the points on the west bank are numbered from 1 to n, in the order in which they are given in the input. Similarly, the points on the east bank are numbered from 1 to m in the order in which they are given in the input. If there are multiple solutions, print any of them. The solution will be accepted if the final length of the path will differ from the answer of the jury by no more than 10 - 6 in absolute or relative value.
The first line contains integers n, m, a, b (1 ≀ n, m ≀ 105, 0 &lt; a &lt; b &lt; 106). The second line contains n integers in the ascending order: the i-th integer determines the coordinate of point Ai and equals yi (|yi| ≀ 106). The third line contains m integers in the ascending order: the i-th integer determines the coordinate of point Bi and equals y'i (|y'i| ≀ 106). The fourth line contains m more integers: the i-th of them determines the length of the path that connects the eastern village and point Bi, and equals li (1 ≀ li ≀ 106). It is guaranteed, that there is such a point C with abscissa at least b, that |BiC| ≀ li for all i (1 ≀ i ≀ m). It is guaranteed that no two points Ai coincide. It is guaranteed that no two points Bi coincide.
standard output
standard input
Python 3
Python
1,900
train_016.jsonl
f67ff61d0f2a1dbc5a5a44804acf4e6e
256 megabytes
["3 2 3 5\n-2 -1 4\n-1 2\n7 3"]
PASSED
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) n, m, a, b = mints() A = list(mints()) B = list(mints()) l = list(mints()) j = -1 r = (1e100,-1,-1) for i in range(m): while not((j == -1 or a*B[i]-b*A[j] >= 0) \ and (j+1 == n or a*B[i]-b*A[j+1] < 0)): j += 1 #print(j)#,a*B[i]-b*A[j],a*B[i]-b*A[j+1]) if j != -1: r = min(r,(l[i]+sqrt(a*a+A[j]*A[j])+sqrt((b-a)**2+(B[i]-A[j])**2),j,i)) if j+1 != n: r = min(r,(l[i]+sqrt(a*a+A[j+1]*A[j+1])+sqrt((b-a)**2+(B[i]-A[j+1])**2),j+1,i)) print(r[1]+1,r[2]+1)
1353938400
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
3 seconds
["15 33\n6 6"]
2d1ad0dc72496b767b9f3d901b6aa36a
NoteFor the sample test case, we have a minimum sum equal to $$$G = 15$$$. One way this can be achieved is with the following assignment: The first pair of people get assigned to houses $$$5$$$ and $$$6$$$, giving us $$$f(1) = 5$$$; The second pair of people get assigned to houses $$$1$$$ and $$$4$$$, giving us $$$f(2) = 6$$$; The third pair of people get assigned to houses $$$3$$$ and $$$2$$$, giving us $$$f(3) = 4$$$. Note that the sum of the $$$f(i)$$$ is $$$5 + 6 + 4 = 15$$$. We also have a maximum sum equal to $$$B = 33$$$. One way this can be achieved is with the following assignment: The first pair of people get assigned to houses $$$1$$$ and $$$4$$$, giving us $$$f(1) = 6$$$; The second pair of people get assigned to houses $$$6$$$ and $$$2$$$, giving us $$$f(2) = 14$$$; The third pair of people get assigned to houses $$$3$$$ and $$$5$$$, giving us $$$f(3) = 13$$$. Note that the sum of the $$$f(i)$$$ is $$$6 + 14 + 13 = 33$$$.
Welcome! Everything is fine.You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.You have a list of $$$k$$$ pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the $$$2k$$$ people into one of the $$$2k$$$ houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.Of course, in the neighborhood, it is possible to visit friends. There are $$$2k - 1$$$ roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.The truth is, these $$$k$$$ pairs of people are actually soulmates. We index them from $$$1$$$ to $$$k$$$. We denote by $$$f(i)$$$ the amount of time it takes for the $$$i$$$-th pair of soulmates to go to each other's houses.As we have said before, you will need to assign each of the $$$2k$$$ people into one of the $$$2k$$$ houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: The first mission, from The Good Place, is to assign the people into the houses such that the sum of $$$f(i)$$$ over all pairs $$$i$$$ is minimized. Let's define this minimized sum as $$$G$$$. This makes sure that soulmates can easily and efficiently visit each other; The second mission, from The Bad Place, is to assign the people into the houses such that the sum of $$$f(i)$$$ over all pairs $$$i$$$ is maximized. Let's define this maximized sum as $$$B$$$. This makes sure that soulmates will have a difficult time to visit each other. What are the values of $$$G$$$ and $$$B$$$?
For each test case, output a single line containing two space-separated integers $$$G$$$ and $$$B$$$.
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer $$$k$$$ denoting the number of pairs of people ($$$1 \le k \le 10^5$$$). The next $$$2k - 1$$$ lines describe the roads; the $$$i$$$-th of them contains three space-separated integers $$$a_i, b_i, t_i$$$ which means that the $$$i$$$-th road connects the $$$a_i$$$-th and $$$b_i$$$-th houses with a road that takes $$$t_i$$$ units of time to traverse ($$$1 \le a_i, b_i \le 2k$$$, $$$a_i \neq b_i$$$, $$$1 \le t_i \le 10^6$$$). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the $$$k$$$ in a single file is at most $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 2
Python
2,000
train_024.jsonl
74090ff2fd340b555706f0b301910bcc
256 megabytes
["2\n3\n1 2 3\n3 2 4\n2 4 3\n4 5 6\n5 6 5\n2\n1 2 1\n1 3 2\n1 4 3"]
PASSED
from collections import Counter,defaultdict from sys import stdin, stdout raw_input = stdin.readline pr = stdout.write for t in xrange(input()): n=input() d=defaultdict(list) n*=2 for i in xrange(n-1): u,v,w=map(int, raw_input().split()) d[u].append((v,w)) d[v].append((u,w)) par=[0]*(n+1) cst=[0]*(n+1) q=[1] pos=0 par[1]=1 while len(q)>pos: x=q[pos] pos+=1 for i,dis in d[x]: if par[i]: continue par[i]=x cst[i]=dis q.append(i) dp=[1]*(n+1) mx,mn=0,0 for i in q[::-1]: dp[par[i]]+=dp[i] mx+=cst[i]*min(dp[i],n-dp[i]) mn+=cst[i]*(dp[i]%2) pr(str(mn)+' '+str(mx)+'\n')
1576386300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3 seconds
["5", "3", "2"]
fade6204af3e346db543f59d40a70ad6
null
One day, ZS the Coder wrote down an array of integers a with elements a1,  a2,  ...,  an.A subarray of the array a is a sequence al,  al  +  1,  ...,  ar for some integers (l,  r) such that 1  ≀  l  ≀  r  ≀  n. ZS the Coder thinks that a subarray of a is beautiful if the bitwise xor of all the elements in the subarray is at least k.Help ZS the Coder find the number of beautiful subarrays of a!
Print the only integer c β€” the number of beautiful subarrays of the array a.
The first line contains two integers n and k (1 ≀ n ≀ 106, 1 ≀ k ≀ 109) β€” the number of elements in the array a and the value of the parameter k. The second line contains n integers ai (0 ≀ ai ≀ 109) β€” the elements of the array a.
standard output
standard input
PyPy 2
Python
2,100
train_055.jsonl
585078fcbaba8e6ad4ed8b2c74ab1446
512 megabytes
["3 1\n1 2 3", "3 2\n1 2 3", "3 3\n1 2 3"]
PASSED
import sys range = xrange input = raw_input L = [-1, -1] count = [0,0] def check(i): if L[i] == -1: L[i] = len(L) L.append(-1) L.append(-1) count.append(0) count.append(0) def add(x, i = 0, bits = 30): count[i] += 1 for bit in reversed(range(bits)): check(i) i = L[i] ^ (x >> bit & 1) count[i] += 1 # count (y xor x) > k def get_count(x, k, i = 0, bits = 30): ret = 0 for bit in reversed(range(bits)): i = L[i] ^ (x >> bit & 1) ^ (k >> bit & 1) if i < 0: return ret if k >> bit & 1 == 0: ret += count[i ^ 1] return ret inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 k = inp[ii] - 1; ii += 1 A = inp[ii:ii + n]; ii += n xor = [0] for a in A: xor.append(xor[-1] ^ a) xor.sort() ans = 0 for x in xor: add(x) ans += get_count(x, k) print ans
1461164400
[ "trees", "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 1 ]
1 second
["red\nred\ncyan\ncyan\ncyan\nred"]
5bc07d2efb7453e51f4931cc7ec3aac7
NoteIn the first example, there is one rearrangement that yields a number divisible by $$$60$$$, and that is $$$360$$$.In the second example, there are two solutions. One is $$$060$$$ and the second is $$$600$$$.In the third example, there are $$$6$$$ possible rearrangments: $$$025$$$, $$$052$$$, $$$205$$$, $$$250$$$, $$$502$$$, $$$520$$$. None of these numbers is divisible by $$$60$$$.In the fourth example, there are $$$3$$$ rearrangements: $$$228$$$, $$$282$$$, $$$822$$$.In the fifth example, none of the $$$24$$$ rearrangements result in a number divisible by $$$60$$$.In the sixth example, note that $$$000\dots0$$$ is a valid solution.
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $$$n$$$ of them how much effort they needed to reach red."Oh, I just spent $$$x_i$$$ hours solving problems", said the $$$i$$$-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($$$60 \cdot x_i$$$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes β€” for example, if some grandmaster answered that he had spent $$$2$$$ hours, Bob could write $$$000120$$$ instead of $$$120$$$.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently: rearranged its digits, or wrote a random number. This way, Alice generated $$$n$$$ numbers, denoted $$$y_1$$$, ..., $$$y_n$$$.For each of the numbers, help Bob determine whether $$$y_i$$$ can be a permutation of a number divisible by $$$60$$$ (possibly with leading zeroes).
Output $$$n$$$ lines. For each $$$i$$$, output the following. If it is possible to rearrange the digits of $$$y_i$$$ such that the resulting number is divisible by $$$60$$$, output "red" (quotes for clarity). Otherwise, output "cyan".
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 418$$$)Β β€” the number of grandmasters Bob asked. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains a single integer $$$y_i$$$Β β€” the number that Alice wrote down. Each of these numbers has between $$$2$$$ and $$$100$$$ digits '0' through '9'. They can contain leading zeroes.
standard output
standard input
Python 3
Python
1,000
train_001.jsonl
2ad746b6571d5eb1ab1f69d4a5e3eefe
256 megabytes
["6\n603\n006\n205\n228\n1053\n0000000000000000000000000000000000000000000000"]
PASSED
t = int(input()) for x in range(t): s = input() ans = 0 f = 0 fl = 0 for i in s: q = int(i) if i == '0': f += 1 elif q % 2 == 0 : fl = 1 ans += q if (ans % 3 == 0 and f and fl) or ans == 0 or (ans % 3 == 0 and f > 1): print('red') else: print('cyan')
1576595100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "0"]
a34f2aa89fe0e78b495b20400d73acf1
NoteThe first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex $$$5$$$ by applying a single operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$.In the second test case, the given tree is already a star with the center at vertex $$$4$$$, so no operations have to be performed.
You are given a tree with $$$n$$$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: Choose three vertices $$$a$$$, $$$b$$$, and $$$c$$$ such that $$$b$$$ is adjacent to both $$$a$$$ and $$$c$$$. For every vertex $$$d$$$ other than $$$b$$$ that is adjacent to $$$a$$$, remove the edge connecting $$$d$$$ and $$$a$$$ and add the edge connecting $$$d$$$ and $$$c$$$. Delete the edge connecting $$$a$$$ and $$$b$$$ and add the edge connecting $$$a$$$ and $$$c$$$. As an example, consider the following tree: The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$: It can be proven that after each operation, the resulting graph is still a tree.Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $$$n - 1$$$, called its center, and $$$n - 1$$$ vertices of degree $$$1$$$.
Print a single integer Β β€” the minimum number of operations needed to transform the tree into a star. It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most $$$10^{18}$$$ operations.
The first line contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) Β β€” the number of vertices in the tree. The $$$i$$$-th of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$) denoting that there exists an edge connecting vertices $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree.
standard output
standard input
PyPy 3
Python
2,800
train_005.jsonl
62ef7edca328924e63757b39c5d42156
256 megabytes
["6\n4 5\n2 6\n3 2\n1 2\n2 4", "4\n2 4\n4 1\n3 4"]
PASSED
import sys from collections import defaultdict def rl(): return sys.stdin.readline().strip() def BFS(s,nbrs): level = defaultdict(int) ind = 0 level[ind] += 1 frontier = [s] visited = {s} while frontier: next = [] ind += 1 for u in frontier: for v in nbrs[u]: if v not in visited: next.append(v) visited.add(v) level[ind] += 1 frontier = next return level n = int(rl()) vert = [] nbrs = defaultdict(list) for i in range(n-1): vert.append(list(map(int,rl().split()))) j = vert[-1][0] k = vert[-1][1] nbrs[j].append(k) nbrs[k].append(j) new = 0 counter = BFS(1,nbrs) for i in range(2,n-1,2): new += counter[i] ans = min(n-2-new,new) print(ans)
1593873900
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["-1\n6\n3\n2"]
a4be9b3484f3f24014392a1c3ad23f2f
NoteIn the first test case, there are no subarrays of length at least $$$2$$$, so the answer is $$$-1$$$.In the second test case, the whole array is dominated (by $$$1$$$) and it's the only dominated subarray.In the third test case, the subarray $$$a_4, a_5, a_6$$$ is the shortest dominated subarray.In the fourth test case, all subarrays of length more than one are dominated.
Let's call an array $$$t$$$ dominated by value $$$v$$$ in the next situation.At first, array $$$t$$$ should have at least $$$2$$$ elements. Now, let's calculate number of occurrences of each number $$$num$$$ in $$$t$$$ and define it as $$$occ(num)$$$. Then $$$t$$$ is dominated (by $$$v$$$) if (and only if) $$$occ(v) &gt; occ(v')$$$ for any other number $$$v'$$$. For example, arrays $$$[1, 2, 3, 4, 5, 2]$$$, $$$[11, 11]$$$ and $$$[3, 2, 3, 2, 3]$$$ are dominated (by $$$2$$$, $$$11$$$ and $$$3$$$ respectevitely) but arrays $$$[3]$$$, $$$[1, 2]$$$ and $$$[3, 3, 2, 2, 1]$$$ are not.Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.You are given array $$$a_1, a_2, \dots, a_n$$$. Calculate its shortest dominated subarray or say that there are no such subarrays.The subarray of $$$a$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_i, a_{i + 1}, \dots, a_j$$$ for some $$$1 \le i \le j \le n$$$.
Print $$$T$$$ integers β€” one per test case. For each test case print the only integer β€” the length of the shortest dominated subarray, or $$$-1$$$ if there are no such subarrays.
The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) β€” the number of test cases. Each test case consists of two lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) β€” the corresponding values of the array $$$a$$$. It's guaranteed that the total length of all arrays in one test doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 2
Python
1,200
train_003.jsonl
039259d4e1197bfc0723d0a5937e69e9
256 megabytes
["4\n1\n1\n6\n1 2 3 4 5 1\n9\n4 1 2 4 5 4 3 2 1\n4\n3 3 3 3"]
PASSED
def count(b): freq={} for i in b: if(i in freq): freq[i]+=1 else: freq[i]=1 return freq if __name__=="__main__": t=int(input()) while t!=0: t-=1 n=int(input()) a=list() a=raw_input() if n==1: print(-1) continue a=list(map(int,a.split(' '))) index=[0]*(n+1) x=0 minv=n+2; for i in a: x+=1 if index[i]!=0: minv=min(minv,x-index[i]+1) index[i]=x if(minv==n+2): print(-1) else: print(minv)
1573655700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n1 1 1\n2\n2 1\n11\n4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6"]
c3cd949c99e96c9da186a34d49bd6197
NoteIn the first test case, $$$\gcd(6,10)=2$$$, $$$\gcd(6,15)=3$$$ and $$$\gcd(10,15)=5$$$. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement.
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than $$$1$$$. For example, the following numbers are composite: $$$6$$$, $$$4$$$, $$$120$$$, $$$27$$$. The following numbers aren't: $$$1$$$, $$$2$$$, $$$3$$$, $$$17$$$, $$$97$$$.Alice is given a sequence of $$$n$$$ composite numbers $$$a_1,a_2,\ldots,a_n$$$.She wants to choose an integer $$$m \le 11$$$ and color each element one of $$$m$$$ colors from $$$1$$$ to $$$m$$$ so that: for each color from $$$1$$$ to $$$m$$$ there is at least one element of this color; each element is colored and colored exactly one color; the greatest common divisor of any two elements that are colored the same color is greater than $$$1$$$, i.e. $$$\gcd(a_i, a_j)&gt;1$$$ for each pair $$$i, j$$$ if these elements are colored the same color. Note that equal elements can be colored different colorsΒ β€” you just have to choose one of $$$m$$$ colors for each of the indices from $$$1$$$ to $$$n$$$.Alice showed already that if all $$$a_i \le 1000$$$ then she can always solve the task by choosing some $$$m \le 11$$$.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$.
For each test case print $$$2$$$ lines. The first line should contain a single integer $$$m$$$ ($$$1 \le m \le 11$$$) β€” the number of used colors. Consider colors to be numbered from $$$1$$$ to $$$m$$$. The second line should contain any coloring that satisfies the above conditions. Print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le m$$$), where $$$c_i$$$ is the color of the $$$i$$$-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$. Remember that each color from $$$1$$$ to $$$m$$$ should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than $$$1$$$).
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the amount of numbers in a sequence $$$a$$$. The second line of the test case contains $$$n$$$ composite integers $$$a_1,a_2,\ldots,a_n$$$ ($$$4 \le a_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^4$$$.
standard output
standard input
PyPy 3
Python
1,400
train_010.jsonl
7968018c0d576e10c8520a27ce7d92d5
512 megabytes
["3\n3\n6 10 15\n2\n4 9\n23\n437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961"]
PASSED
def answer(n,A): dp=[1]*32 dp[0]=dp[1]=0 for i in range(2,32): if dp[i]==1: p=2*i while p<=31: if dp[p]==1: dp[p]=0 p+=i count=1 res=[0]*n for i in range(2,32): if dp[i]==1: flag=0 for j in range(n): if res[j]==0 and A[j]%i==0: flag=1 res[j]=count if flag==1: count+=1 return count,res t=int(input()) for i in range(t): n=int(input()) arr=list(map(int,input().split())) a,b=answer(n,arr) print(a-1) print(*b)
1585661700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["4\n5\n6\n0\n12"]
7458f44802c134de6fed7b4de84ea68c
NoteIn the first test case, there exists only $$$3$$$ strings of length $$$3$$$, which has exactly $$$1$$$ symbol, equal to "1". These strings are: $$$s_1 = $$$"100", $$$s_2 = $$$"010", $$$s_3 = $$$"001". The values of $$$f$$$ for them are: $$$f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$$$, so the maximum value is $$$4$$$ and the answer is $$$4$$$.In the second test case, the string $$$s$$$ with the maximum value is "101".In the third test case, the string $$$s$$$ with the maximum value is "111".In the fourth test case, the only string $$$s$$$ of length $$$4$$$, which has exactly $$$0$$$ symbols, equal to "1" is "0000" and the value of $$$f$$$ for that string is $$$0$$$, so the answer is $$$0$$$.In the fifth test case, the string $$$s$$$ with the maximum value is "01010" and it is described as an example in the problem statement.
Ayoub thinks that he is a very smart person, so he created a function $$$f(s)$$$, where $$$s$$$ is a binary string (a string which contains only symbols "0" and "1"). The function $$$f(s)$$$ is equal to the number of substrings in the string $$$s$$$ that contains at least one symbol, that is equal to "1".More formally, $$$f(s)$$$ is equal to the number of pairs of integers $$$(l, r)$$$, such that $$$1 \leq l \leq r \leq |s|$$$ (where $$$|s|$$$ is equal to the length of string $$$s$$$), such that at least one of the symbols $$$s_l, s_{l+1}, \ldots, s_r$$$ is equal to "1". For example, if $$$s = $$$"01010" then $$$f(s) = 12$$$, because there are $$$12$$$ such pairs $$$(l, r)$$$: $$$(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$$$.Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $$$n$$$ and $$$m$$$ and asked him this problem. For all binary strings $$$s$$$ of length $$$n$$$ which contains exactly $$$m$$$ symbols equal to "1", find the maximum value of $$$f(s)$$$.Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
For every test case print one integer numberΒ β€” the maximum value of $$$f(s)$$$ over all strings $$$s$$$ of length $$$n$$$, which has exactly $$$m$$$ symbols, equal to "1".
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) Β β€” the number of test cases. The description of the test cases follows. The only line for each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^{9}$$$, $$$0 \leq m \leq n$$$)Β β€” the length of the string and the number of symbols equal to "1" in it.
standard output
standard input
PyPy 3
Python
1,700
train_010.jsonl
4da03af02b617c514d497ffc15be614b
256 megabytes
["5\n3 1\n3 2\n3 3\n4 0\n5 2"]
PASSED
""" #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import collections as col import math, string def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) MOD = 10**9+7 """ Strings of length 1 is always M Strings of length 2 can be maximised by having the 1s at least 1 zero apart where necessary If M >= floor(N//2), then every substring except some of the 1s works Otherwise, M 1s, N-M 0s. We want to split the 0s as evenly as possible 00100100 Partition the 0s into M+1 groups 000100100 f(1) = 2 f(2) = 4 f(3) = 6 f(4) = 6 f(5) = 5 f(6) = 4 f(7) = 3 f(8) = 2 f(9) = 1 001000100 f(1) = 2 f(2) = 4 f(3) = 6 f(4) = 6 00010000 max gap = ceil((N-M)/(M+1)) for x < max gap, contribution is M*x for x >= max gap, contribution is N-x+1 so we want sum x = 1 to max_gap (M*x) + sum x = max_gap+1 to N (N-x+1) Obviously M = 0 => 0 M = 1 => """ def solve(): N, M = getInts() if M == 0: return 0 gap = math.ceil((N-M)/(M+1)) ans = (M+1)*gap*(gap+1)//2 + (N-gap)*(N+1) - N*(N+1)//2 return ans for _ in range(getInt()): print(solve())
1581604500
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["5.000000000000000\n3.000000000000000\n0.000000000000000\n1.500000000000000\n2.000000000000000"]
2863d7304de4a07a8f6cd95bffaf590c
Note The 1-st point is always in the shade; the 2-nd point is in the shade while light source is moving from $$$(3, -3)$$$ to $$$(6, -3)$$$; the 3-rd point is in the shade while light source is at point $$$(6, -3)$$$. the 4-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and at point $$$(6, -3)$$$; the 5-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and from $$$(5.5, -3)$$$ to $$$(6, -3)$$$;
There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $$$(a, s_y)$$$ to the $$$(b, s_y)$$$ $$$(s_y &lt; 0)$$$ with speed equal to $$$1$$$ unit per second. The trajectory of this light source is a straight segment connecting these two points. There is also a fence on $$$OX$$$ axis represented as $$$n$$$ segments $$$(l_i, r_i)$$$ (so the actual coordinates of endpoints of each segment are $$$(l_i, 0)$$$ and $$$(r_i, 0)$$$). The point $$$(x, y)$$$ is in the shade if segment connecting $$$(x,y)$$$ and the current position of the light source intersects or touches with any segment of the fence. You are given $$$q$$$ points. For each point calculate total time of this point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$.
Print $$$q$$$ lines. The $$$i$$$-th line should contain one real number β€” total time of the $$$i$$$-th point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$. The answer is considered as correct if its absolute of relative error doesn't exceed $$$10^{-6}$$$.
First line contains three space separated integers $$$s_y$$$, $$$a$$$ and $$$b$$$ ($$$-10^9 \le s_y &lt; 0$$$, $$$1 \le a &lt; b \le 10^9$$$) β€” corresponding coordinates of the light source. Second line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” number of segments in the fence. Next $$$n$$$ lines contain two integers per line: $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i &lt; r_i \le 10^9$$$, $$$r_{i - 1} &lt; l_i$$$) β€” segments in the fence in increasing order. Segments don't intersect or touch each other. Next line contains single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) β€” number of points to check. Next $$$q$$$ lines contain two integers per line: $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le 10^9$$$) β€” points to process.
standard output
standard input
PyPy 2
Python
2,400
train_056.jsonl
970ad33eb15b8e23250c2b5a384d1b58
256 megabytes
["-3 1 6\n2\n2 4\n6 7\n5\n3 1\n1 3\n6 1\n6 4\n7 6"]
PASSED
from __future__ import division import sys range = xrange input = sys.stdin.readline sy,a,b = [int(x) for x in input().split()] n = int(input()) inp = [int(x) for line in sys.stdin for x in line.split()] ii = 0 L = [] R = [] for _ in range(n): l = inp[ii] r = inp[ii+1] ii+=2 L.append(l) R.append(r) Lsum = [0] for l in L: Lsum.append(Lsum[-1]+l) Rsum = [0] for r in R: Rsum.append(Rsum[-1]+r) out = [] q = inp[ii] ii+=1 for _ in range(q): px = inp[ii] py = inp[ii+1] ii+=2 shade = 0 # L' = px + (l-px)/py*(py-sy) # R' = px + (l-px)/py*(py-sy) A = 0 B = len(L) while A<B: M = (A+B)//2 l = L[M] l = px + (l-px)/py*(py-sy) if l<a: A = M+1 else: B = M ind1 = A if ind1==n: lista = [ind1-1] else: A = ind1-1 B = len(R)-1 while A<B: M = (A+B+1)//2 r = R[M] r = px + (r-px)/py*(py-sy) if b<r: B = M-1 else: A = M ind2 = A if ind2==ind1-1: lista = [ind1-2,ind1-1,ind1,ind1+1] else: l = Lsum[ind2+1]-Lsum[ind1] r = Rsum[ind2+1]-Rsum[ind1] l = (l)/py*(py-sy) r = (r)/py*(py-sy) shade += r-l lista = [ind1-1,ind2+1] for i in lista: if i<0 or i>=n: continue l = L[i] r = R[i] l = px + (l-px)/py*(py-sy) r = px + (r-px)/py*(py-sy) if l<=a: l = a if b<=r: r = b shade += max(r-l,0) out.append('%.10f'%(shade)) print '\n'.join(out)
1533307500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["42", "428101984"]
0ffa96d83e63d20bdfa2ecbf535adcdd
NoteConsider the first example.Vova can choose to remove $$$1$$$, $$$0$$$, $$$7$$$, $$$10$$$, $$$07$$$, or $$$107$$$. The results are $$$07$$$, $$$17$$$, $$$10$$$, $$$7$$$, $$$1$$$, $$$0$$$. Their sum is $$$42$$$.
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $$$n$$$, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.For example, is Sasha names $$$1213121$$$, Vova can remove the substring $$$1312$$$, and the result is $$$121$$$.It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be $$$0$$$.Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.Help Sasha to compute this sum. Since the answer can be very large, print it modulo $$$10^9 + 7$$$.
In the only line print the required sum modulo $$$10^9 + 7$$$.
The first and only line contains a single integer $$$n$$$ ($$$1 \le n &lt; 10^{10^5}$$$).
standard output
standard input
PyPy 3
Python
1,700
train_037.jsonl
f8d95d09ad196d044975066ebe7d6ff3
256 megabytes
["107", "100500100500"]
PASSED
s=input() mod=int(1e9+7) l=len(s) a,b=0,0 ss=s[::-1] for i in range(l): c=int(ss[i]) p=l-1-i a+=p*(p+1)//2*c*pow(10,i,mod) a+=b*c a%=mod b+=(i+1)*pow(10,i,mod) b%=mod print(a)
1601827500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 3 2", "4 1 2 3", "3 1 2 4 5"]
e29742df22068606228db4dda8a40df5
null
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.You should assign labels to all vertices in such a way that: Labels form a valid permutation of length n β€” an integer sequence such that each integer from 1 to n appears exactly once in it. If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu. Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.
Print n numbers β€” lexicographically smallest correct permutation of labels of vertices.
The first line contains two integer numbers n, m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105). Next m lines contain two integer numbers v and u (1 ≀ v, u ≀ n, v ≠ u) β€” edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.
standard output
standard input
Python 3
Python
2,300
train_011.jsonl
64f42ac1dda18e3277357e596e642c32
256 megabytes
["3 3\n1 2\n1 3\n3 2", "4 5\n3 1\n4 1\n2 3\n3 4\n2 4", "5 4\n3 1\n2 1\n2 3\n4 5"]
PASSED
from queue import Queue import heapq n, m = input().split() n = int(n) m = int(m) f = [0] * (n + 1) sol = [0] * (n + 1) adya = [[] for _ in range(n + 1)] for i in range(m): n1, n2 = input().split() n1 = int(n1) n2 = int(n2) adya[n2].append(n1) f[n1] += 1 cola = [] cnt = 0 for i in range(1, n + 1): if(f[i] == 0): heapq.heappush(cola, -1 * i) cnt += 1 num = int(n) while(cnt > 0): v = heapq.heappop(cola) v *= -1 sol[v] = num cnt -= 1 num -= 1 for to in adya[v]: f[to] -= 1 if(f[to] == 0): heapq.heappush(cola, -1 * to) cnt += 1 stringOut = "" for i in range(1, n + 1): stringOut += str(sol[i]) if(i != n): stringOut += ' ' print(stringOut)
1500217500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1", "2"]
3def8503f4e7841d33be5b4890065526
NoteIn the first example it is possible that only the first worker made a mistake. Then: the immediate superior of the first worker is the second worker, the immediate superior of the third worker is the first worker, the second worker is the chief.
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.
Print the minimum number of workers that could make a mistake.
The first line contains two positive integers n and s (1 ≀ n ≀ 2Β·105, 1 ≀ s ≀ n)Β β€” the number of workers and the id of the chief. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ n - 1), where ai is the number of superiors (not only immediate) the worker with id i reported about.
standard output
standard input
Python 3
Python
1,900
train_022.jsonl
739f033b377b434d25dd47a805d3a7f5
256 megabytes
["3 2\n2 0 2", "5 3\n1 0 0 4 1"]
PASSED
n,s=[int(i) for i in input().split()] s-=1 n-=1 d=0 l=[int(i) for i in input().split()] if l[s]!=0:d+=1 l=l[:s]+l[s+1:] for i in range(0,len(l)): if(l[i]==0):l[i]=n+5 l.sort() j=0 i=0 c=0 while 1: while i<len(l) and j==l[i]: i+=1 if i>=len(l): break elif l[i]-j==1: j+=1 i+=1 continue else: l.pop() d+=1 j+=1 print(d) # Made By Mostafa_Khaled
1479632700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1-3,6", "1-3", "10,20,30"]
3969ba3e3eb55a896663d2c5a5bc4a84
null
Β«BersoftΒ» company is working on a new version of its most popular text editor β€” Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).Your task is to write a part of the program, responsible for Β«standardizationΒ» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 &lt; li + 1 for all i from 1 to k - 1, and li ≀ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as Β«li - liΒ».For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.
Output the sequence in the required format.
The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.
standard output
standard input
Python 2
Python
1,300
train_002.jsonl
fae3026ac6742bdd7582c5651dca3f3e
256 megabytes
["1,2,3,1,1,2,6,6,2", "3,2,1", "30,20,10"]
PASSED
inp = raw_input() #inp = '996,999,998,984,989,1000,996,993,1000,983,992,999,999,1000,979,992,987,1000,996,1000,1000,989,981,996,995,999,999,989,999,1000' num_list = sorted(set(map(int, inp.split(',')))) #print num_list result = [] finish = True for elem in num_list: if finish: start = elem end = elem finish = False elif elem == end + 1: end = elem elif start == end: result.append('%s' % start) #print 'st:%s' % start start = elem end = elem else: result.append('%s-%s' % (start, end)) #print 'st:%s %s' % (start, end) start = elem end = elem if start == end: result.append('%s' % start) else: result.append('%s-%s' % (start, end)) print ','.join(result)
1286802000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["5", "1", "3"]
bbc2683d207f147a2a0abedc67ff157a
NoteIn the first sample the following substrings have the sought digital root: s[1... 2] = "3 2", s[1... 3] = "3 2 0", s[3... 4] = "0 5", s[4... 4] = "5" and s[2... 6] = "2 0 5 6 1".
You know that the Martians use a number system with base k. Digit b (0 ≀ b &lt; k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.For example, d(35047) = d((3 + 5 + 0 + 4)7) = d(157) = d((1 + 5)7) = d(67) = 67. In this sample the calculations are performed in the 7-base notation.If a number's digital root equals b, the Martians also call this number lucky.You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.Note that substring s[i... j] of the string s = a1a2... an (1 ≀ i ≀ j ≀ n) is the string aiai + 1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1 ≠ i2 or j1 ≠ j2.
Print a single integer β€” the number of substrings that are lucky numbers. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line contains three integers k, b and n (2 ≀ k ≀ 109, 0 ≀ b &lt; k, 1 ≀ n ≀ 105). The second line contains string s as a sequence of n integers, representing digits in the k-base notation: the i-th integer equals ai (0 ≀ ai &lt; k) β€” the i-th digit of string s. The numbers in the lines are space-separated.
standard output
standard input
Python 3
Python
2,000
train_070.jsonl
31ce615f8a97d028795e56076994ba2d
256 megabytes
["10 5 6\n3 2 0 5 6 1", "7 6 4\n3 5 0 4", "257 0 3\n0 0 256"]
PASSED
k, b, n = map(int, input().split()) digits = list(map(int, input().split())) def ans0(): j = -1 answer = 0 for i in range(n): if digits[i] != 0 or i < j: continue j = i while j < n and digits[j] == 0: j += 1 r = j - i answer += r * (r + 1) // 2 return answer if b == 0: print(ans0()) else: count = dict() count[0] = 1 pref_sum = 0 answer = 0 if b == k - 1: b = 0 answer -= ans0() for d in digits: pref_sum = (pref_sum + d) % (k - 1) need = (pref_sum - b) % (k - 1) answer += count.get(need, 0) count[pref_sum] = count.get(pref_sum, 0) + 1 print(answer)
1344958200
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["0\n3\n1000000\n0\n1\n0"]
f98d1d426f68241bad437eb221f617f4
NoteIn the first test case (picture above), if we set the coordinate of $$$B$$$ as $$$2$$$ then the absolute difference will be equal to $$$|(2 - 0) - (4 - 2)| = 0$$$ and we don't have to move $$$A$$$. So the answer is $$$0$$$.In the second test case, we can increase the coordinate of $$$A$$$ by $$$3$$$ and set the coordinate of $$$B$$$ as $$$0$$$ or $$$8$$$. The absolute difference will be equal to $$$|8 - 0| = 8$$$, so the answer is $$$3$$$.
We have a point $$$A$$$ with coordinate $$$x = n$$$ on $$$OX$$$-axis. We'd like to find an integer point $$$B$$$ (also on $$$OX$$$-axis), such that the absolute difference between the distance from $$$O$$$ to $$$B$$$ and the distance from $$$A$$$ to $$$B$$$ is equal to $$$k$$$. The description of the first test case. Since sometimes it's impossible to find such point $$$B$$$, we can, in one step, increase or decrease the coordinate of $$$A$$$ by $$$1$$$. What is the minimum number of steps we should do to make such point $$$B$$$ exist?
For each test case, print the minimum number of steps to make point $$$B$$$ exist.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 6000$$$)Β β€” the number of test cases. The only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$0 \le n, k \le 10^6$$$)Β β€” the initial position of point $$$A$$$ and desirable absolute difference.
standard output
standard input
Python 3
Python
900
train_007.jsonl
98be7d52ce17342be19d418150db536f
256 megabytes
["6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000"]
PASSED
T = int(input()) for _ in range(T): n, k = tuple(map(int, input().split())) if n < k: print(k - n) continue if n == k: print(0) continue if n > k: if n % 2 == k % 2: print(0) else: print(1)
1598020500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["12", "13", "11"]
1fb69f26fb14076df31534c77bf40c1e
NoteIn the first example you can obtain the text "TB or not TB".In the second example you can obtain the text "a AAAB AAAB c".In the third example you can obtain the text "AB aa AB bb".
You are given a text consisting of $$$n$$$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $$$w_i$$$ is the $$$i$$$-th word of text. All words consist only of lowercase Latin letters.Let's denote a segment of words $$$w[i..j]$$$ as a sequence of words $$$w_i, w_{i + 1}, \dots, w_j$$$. Two segments of words $$$w[i_1 .. j_1]$$$ and $$$w[i_2 .. j_2]$$$ are considered equal if $$$j_1 - i_1 = j_2 - i_2$$$, $$$j_1 \ge i_1$$$, $$$j_2 \ge i_2$$$, and for every $$$t \in [0, j_1 - i_1]$$$ $$$w_{i_1 + t} = w_{i_2 + t}$$$. For example, for the text "to be or not to be" the segments $$$w[1..2]$$$ and $$$w[5..6]$$$ are equal, they correspond to the words "to be".An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words $$$w[2..4]$$$ and $$$w[6..8]$$$ with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words $$$w[2..5]$$$ and $$$w[6..9]$$$ with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".What is the minimum length of the text after at most one abbreviation?
Print one integer β€” the minimum length of the text after at most one abbreviation.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) β€” the number of words in the text. The next line contains $$$n$$$ space-separated words of the text $$$w_1, w_2, \dots, w_n$$$. Each word consists only of lowercase Latin letters. It is guaranteed that the length of text does not exceed $$$10^5$$$.
standard output
standard input
PyPy 2
Python
2,200
train_045.jsonl
1bf899395b53d8820b0b15dc0beceef4
256 megabytes
["6\nto be or not to be", "10\na ab a a b ab a a b c", "6\naa bb aa aa bb bb"]
PASSED
n = int(raw_input()) arr = raw_input() final = len(arr) arr = arr.split() lens = [0 for x in range(n)] visit = [0 for x in range(n)] cnt = 0 ans = 0 for i in range(n): if visit[i]: continue lens[cnt] = len(arr[i]) for j in range(i+1,n): if arr[j]==arr[i]: arr[j] = cnt visit[j] = 1 arr[i] = cnt cnt += 1 for i in range(n): for j in range(i,n): temp = arr[i:j+1] ind = 1 found = 0 len2 = j-i+1 cur = 0 kmp = [0 for x in range(len2)] while ind < len2: if temp[ind] == temp[cur]: cur += 1 kmp[ind] = cur ind += 1 else: if cur != 0: cur -= 1 else: kmp[ind] = 0 ind += 1 ind = 0 cur = 0 while ind < n: if arr[ind] == temp[cur]: ind += 1 cur += 1 if cur == len2: found += 1 cur = 0 elif ind < n and temp[cur] != arr[ind]: if cur != 0: cur = kmp[cur-1] else: ind += 1 if found>1: res = 0 for k in temp: res += (lens[k]-1)*(found) res += (len(temp)-1)*(found) ans = max(ans,res) print final-ans
1530628500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
6 seconds
["1", "3"]
6090c7745184ede5a9997dc0dff39ac2
NoteIn the first example, there is only $$$1$$$ fence. That fence is interesting since its area is $$$4$$$ and there is $$$1$$$ enclosed cow, marked in red. In the second example, there are $$$3$$$ interesting fences. $$$(0,0)$$$ β€” $$$(30,14)$$$ β€” $$$(2,10)$$$ $$$(2,16)$$$ β€” $$$(30,14)$$$ β€” $$$(2,10)$$$ $$$(30,14)$$$ β€” $$$(4,6)$$$ β€” $$$(2,10)$$$
This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are even.There are $$$n$$$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.There are an infinite number of cows on the plane, one at every point with integer coordinates.Gregor is a member of the Illuminati, and wants to build a triangular fence, connecting $$$3$$$ distinct existing fence posts. A cow strictly inside the fence is said to be enclosed. If there are an odd number of enclosed cows and the area of the fence is an integer, the fence is said to be interesting.Find the number of interesting fences.
Print a single integer, the number of interesting fences. Two fences are considered different if they are constructed with a different set of three fence posts.
The first line contains the integer $$$n$$$ ($$$3 \le n \le 6000$$$), the number of fence posts which Gregor can choose to form the vertices of a fence. Each of the next $$$n$$$ line contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x,y \le 10^7$$$, $$$x$$$ and $$$y$$$ are even), where $$$(x,y)$$$ is the coordinate of a fence post. All fence posts lie at distinct coordinates. No three fence posts are on the same line.
standard output
standard input
PyPy 3-64
Python
2,300
train_083.jsonl
139bc23aab5f49407a7c642c59ce233a
256 megabytes
["3\n0 0\n2 0\n0 4", "5\n0 0\n2 16\n30 14\n4 6\n2 10"]
PASSED
import sys input = sys.stdin.readline n = int(input()) a = 0 b = 0 c = 0 d = 0 for i in range(n): x, y = [int(xx) for xx in input().split()] if x % 4 and y % 4: a += 1 elif y % 4: b += 1 elif x % 4: c += 1 else: d += 1 print(a * (a - 1) // 2 * (b + c + d) + b * (b - 1) // 2 * (a + c + d) + c * (c - 1) // 2 * (a + b + d) + d * (d - 1) // 2 * (a + b + c) + a * (a - 1) * (a - 2) // 6 + b * (b - 1) * (b - 2) // 6 + c * (c - 1) * (c - 2) // 6 + d * (d - 1) * (d - 2) // 6)
1627828500
[ "number theory", "math", "geometry" ]
[ 0, 1, 0, 1, 1, 0, 0, 0 ]
2 seconds
["possible", "impossible"]
5fde461bbb54302cfa5e8d5d3e29b9db
NoteIn the first sample, there are n = 5 vertices. The degree of vertex 1 should be k = 2. All conditions are satisfied for a tree with edges 1 - 5, 5 - 2, 1 - 3 and 3 - 4.In the second sample, Limak remembers that none of the following edges existed: 1 - 2, 1 - 3, 1 - 4, 1 - 5 and 1 - 6. Hence, vertex 1 couldn't be connected to any other vertex and it implies that there is no suitable tree.
A tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.Limak is a little polar bear. He once had a tree with n vertices but he lost it. He still remembers something about the lost tree though.You are given m pairs of vertices (a1, b1), (a2, b2), ..., (am, bm). Limak remembers that for each i there was no edge between ai and bi. He also remembers that vertex 1 was incident to exactly k edges (its degree was equal to k).Is it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions.
Print "possible" (without quotes) if there exists at least one tree satisfying the given conditions. Otherwise, print "impossible" (without quotes).
The first line of the input contains three integers n, m and k ()Β β€” the number of vertices in Limak's tree, the number of forbidden pairs of vertices, and the degree of vertex 1, respectively. The i-th of next m lines contains two distinct integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi)Β β€” the i-th pair that is forbidden. It's guaranteed that each pair of vertices will appear at most once in the input.
standard output
standard input
Python 2
Python
2,400
train_012.jsonl
285ec371e9d40d7dc9d2c86d6dfea1d5
256 megabytes
["5 4 2\n1 2\n2 3\n4 2\n4 1", "6 5 3\n1 2\n1 3\n1 4\n1 5\n1 6"]
PASSED
import sys n,m,k = map(int, sys.stdin.readline().split(' ')) V = map(set, [set()]*n) for _ in range(m): u,v = map(int, sys.stdin.readline().rstrip('\n').split(' ')) u-=1 v-=1 V[u].add(v) V[v].add(u) if n-1-len(V[0])<k: print 'impossible' exit() visited = set(range(1,n)) comp = 0 for i in range(1,n): if i in visited: visited.remove(i) comp += 1 if comp>k: print 'impossible' exit() can_connect_to_root = False stack = [i] for s in stack: can_connect_to_root |= s not in V[0] removed = set() for x in visited: if x not in V[s]: removed.add(x) stack.append(x) visited.difference_update(removed) if not can_connect_to_root: print 'impossible' exit() print 'possible'
1458376500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
0.5 second
["a@a,a@a", "No solution", "No solution"]
71b4674e91e0bc5521c416cfc570a090
null
Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in Β«BersoftΒ» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.
If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.
The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters Β«@Β».
standard output
standard input
PyPy 2
Python
1,500
train_005.jsonl
21461df770b0c62aabc8ca7ecd96f87e
256 megabytes
["a@aa@a", "a@a@a", "@aa@a"]
PASSED
import sys, re s = raw_input().strip() match = re.match('^(\w+@\w+)+$', s) if not match: print('No solution') sys.exit() previous = 0 last_at = None result = [] for pos, ch in enumerate(s): if ch == '@': result.append(s[previous:pos + 2]) previous = pos + 2 last_at = pos result[-1] += s[last_at + 2:] print(','.join(result))
1285599600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["0.500000 0.500000", "1.000000 0.000000 0.000000 0.000000 0.000000"]
da2d76d47c1ed200982495dc4a234014
null
n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.
Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.
The first line contains integer n (1 ≀ n ≀ 18) β€” the amount of fish in the lake. Then there follow n lines with n real numbers each β€” matrix a. aij (0 ≀ aij ≀ 1) β€” the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.
standard output
standard input
PyPy 3
Python
1,900
train_075.jsonl
5ba7e1e664325b63ff3a545a4f2004b4
128 megabytes
["2\n0 0.5\n0.5 0", "5\n0 1 1 1 1\n0 0 0.5 0.5 0.5\n0 0.5 0 0.5 0.5\n0 0.5 0.5 0 0.5\n0 0.5 0.5 0.5 0"]
PASSED
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) prob = [tuple(map(float, input().split())) for _ in range(n)] full_bit = (1 << n) - 1 dp = [0.0] * full_bit + [1.0] for bit in range(full_bit, 0, -1): popcount = len([1 for i in range(n) if (1 << i) & bit]) if popcount == 1 or dp[bit] == 0.0: continue div = 1 / ((popcount * (popcount - 1)) >> 1) for i in range(n): if ((1 << i) & bit) == 0: continue for j in range(i + 1, n): if ((1 << j) & bit) == 0: continue dp[bit - (1 << j)] += dp[bit] * prob[i][j] * div dp[bit - (1 << i)] += dp[bit] * prob[j][i] * div print(*(dp[1 << i] for i in range(n)))
1275570000
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
1 second
["2", "1"]
6d940cb4b54f63a7aaa82f21e4c5b994
NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?
You should output the number of trees in the forest where PolandBall lives.
The first line contains single integer n (1 ≀ n ≀ 104)Β β€” the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≀ pi ≀ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1 ≀ n ≀ 104)Β β€” the number of Balls and the integer m (0 ≀ m &lt; n)Β β€” the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5
standard output
standard input
Python 2
Python
1,300
train_001.jsonl
1377c4c1bef490fcb75430c63cce3ad8
256 megabytes
["5\n2 1 5 3 3", "1\n1"]
PASSED
import sys sys.setrecursionlimit(10000000) nBalls = int(raw_input()) edge = [None] + map(int, raw_input().split()) group = [0] * (nBalls + 1) def dfs(ball): if not group[ball]: group[ball] = groupNum dfs(edge[ball]) groupNum = 0 for ball in xrange(1, nBalls + 1): if not group[ball]: if group[edge[ball]]: group[ball] = group[edge[ball]] else: groupNum += 1 dfs(ball) print groupNum
1484499900
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["3\n6\n1\n1287\n1287\n715"]
930b296d11d6d5663a14144a491f2c0a
NoteIn the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.
Cirno gave AquaMoon a chessboard of size $$$1 \times n$$$. Its cells are numbered with integers from $$$1$$$ to $$$n$$$ from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.In each operation, AquaMoon can choose a cell $$$i$$$ with a pawn, and do either of the following (if possible): Move pawn from it to the $$$(i+2)$$$-th cell, if $$$i+2 \leq n$$$ and the $$$(i+1)$$$-th cell is occupied and the $$$(i+2)$$$-th cell is unoccupied. Move pawn from it to the $$$(i-2)$$$-th cell, if $$$i-2 \geq 1$$$ and the $$$(i-1)$$$-th cell is occupied and the $$$(i-2)$$$-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo $$$998\,244\,353$$$.
For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo $$$998\,244\,353$$$.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) β€” the number of test cases. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) β€” the size of the chessboard. The second line contains a string of $$$n$$$ characters, consists of characters "0" and "1". If the $$$i$$$-th character is "1", the $$$i$$$-th cell is initially occupied; otherwise, the $$$i$$$-th cell is initially unoccupied. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,900
train_086.jsonl
4a2f24c837119edcbae8adfb580f9c58
256 megabytes
["6\n4\n0110\n6\n011011\n5\n01010\n20\n10001111110110111000\n20\n00110110100110111101\n20\n11101111011000100010"]
PASSED
import sys input = lambda: sys.stdin.readline().strip() ints = lambda: list(map(int, input().split())) Int = lambda: int(input()) MOD = 998244353 def inv(a, m): if a == 1: return 1 return inv(m % a, m) * (m - m // a) % m F = [1] rF = [1] for i in range(1, 100000+1): F.append(F[-1] * i % MOD) rF.append(rF[-1] * inv(i, MOD) % MOD) T = Int() while T: T -= 1 n = Int() s = input() a = [0] * n cnt = 0 for i, x in enumerate(s): if x == "1" and i > 0 and s[i - 1] == "1" and a[i - 1] == 0: cnt += 1 a[i] = 1 a[i - 1] = 1 cnt2 = s.count("0") print(F[cnt + cnt2] * rF[cnt] % MOD * rF[cnt2] % MOD)
1626012300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1.5 seconds
["40", "5", "0"]
8c5d9b4fd297706fac3be83fc85028a0
NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro billsΒ β€” $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help himΒ β€” write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.
Output one integerΒ β€” the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.
The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$)Β β€” the initial sum in rubles Andrew has. The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$)Β β€” the price of one dollar in rubles. The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$)Β β€” the price of one euro in rubles.
standard output
standard input
PyPy 3
Python
1,400
train_018.jsonl
c4bfd7b31f76b2331b4f20ba6396be3e
512 megabytes
["100\n60\n70", "410\n55\n70", "600\n60\n70"]
PASSED
n = int(input()) d = int(input()) e = int(input()) dollar = 1*d euro = 5*e # using_dollar = n%dollar # using_euro = n%euro # using_dollar_euro = using_dollar % euro # using_euro_dollar = using_euro % dollar # print(min(using_dollar, using_euro, using_dollar_euro, using_euro_dollar)) ans = 1e15 temp = 0 while (temp<=n): ans = min(ans, (n-temp)%dollar) temp += euro print(ans)
1567587900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["FIRST\n1 0 1 1", "SECOND"]
a7fa7a5ab71690fb3b5301bebc19956b
null
Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before.Obviously, the game ends when the entire sheet is cut into 1 × 1 blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers.You are given an n × m piece of paper, somebody has already made k cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.
If the second player wins, print "SECOND". Otherwise, in the first line print "FIRST", and in the second line print any winning move of the first player (the coordinates of the cut ends, follow input format to print them).
The first line contains three integers n, m, k (1 ≀ n, m ≀ 109, 0 ≀ k ≀ 105) β€” the sizes of the piece of paper and the number of cuts. Then follow k lines, each containing 4 integers xbi, ybi, xei, yei (0 ≀ xbi, xei ≀ n, 0 ≀ ybi, yei ≀ m) β€” the coordinates of the ends of the existing cuts. It is guaranteed that each cut has a non-zero length, is either vertical or horizontal and doesn't go along the sheet border. The cuts may intersect, overlap and even be the same. That is, it is not guaranteed that the cuts were obtained during any correct game.
standard output
standard input
Python 2
Python
2,400
train_069.jsonl
cb2fe6e222a22ee09939e5d7c2db22ad
256 megabytes
["2 1 0", "2 2 4\n0 1 2 1\n0 1 2 1\n1 2 1 0\n1 1 1 2"]
PASSED
from sys import stdin from collections import defaultdict def emp(l, a): cnt = pos = x = 0 for y in a: if y[1]: cnt -= 1 else: if not cnt: x += y[0] - pos cnt += 1 pos = y[0] x += l - pos return x def check(x, b): return x ^ b < x def f(x, b): return x - (x ^ b) def main(): n, m, k = map(int, stdin.readline().split()) xcut = defaultdict(list) ycut = defaultdict(list) for i in xrange(k): xb, yb, xe, ye = map(int, stdin.readline().split()) if xb == xe: xcut[xb].extend([(min(yb, ye), 0), (max(yb, ye), 1)]) else: ycut[yb].extend([(min(xb, xe), 0), (max(xb, xe), 1)]) b = 0 xb = dict() yb = dict() for t in xcut.keys(): xcut[t].sort() xb[t] = emp(m, xcut[t]) b ^= xb[t] if (n - 1 - len(xcut)) % 2: b ^= m for t in ycut.keys(): ycut[t].sort() yb[t] = emp(n, ycut[t]) b ^= yb[t] if (m - 1 - len(ycut)) % 2: b ^= n if b == 0: print "SECOND" return else: print "FIRST" if n - 1 - len(xcut) and check(m, b): for i in xrange(1, n): if i not in xcut: print i, 0, i, f(m, b) return if m - 1 - len(ycut) and check(n, b): for i in xrange(1, m): if i not in ycut: print 0, i, f(n, b), i return for t, a in xcut.items(): if not check(xb[t], b): continue c = f(xb[t], b) cnt = pos = x = 0 for y in a: if y[1] == 0: if cnt == 0: if x <= c <= x + y[0] - pos: print t, 0, t, pos + c - x return x += y[0] - pos cnt += 1 else: cnt -= 1 pos = y[0] print t, 0, t, pos + c - x return for t, a in ycut.items(): if not check(yb[t], b): continue c = f(yb[t], b) cnt = pos = x = 0 for y in a: if y[1] == 0: if cnt == 0: if x <= c <= x + y[0] - pos: print 0, t, pos + c - x, t return x += y[0] - pos cnt += 1 else: cnt -= 1 pos = y[0] print 0, t, pos + c - x, t return main()
1362065400
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["3", "-2", "5", "No solution"]
8a9adc116abbd387a6a64dd754436f8a
null
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative β€” it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X β€” the coefficient of income growth during one year. This coefficient should satisfy the equation:AΒ·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.
Output the required integer coefficient X, or Β«No solutionΒ», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.
The input contains three integers A, B, n (|A|, |B| ≀ 1000, 1 ≀ n ≀ 10).
standard output
standard input
Python 3
Python
1,400
train_024.jsonl
aa90364ec139c411aaf5b63af1f824d8
256 megabytes
["2 18 2", "-1 8 3", "0 0 10", "1 16 5"]
PASSED
a,b,n = map(int,input().split()) ans = "No solution" if a == 0 and b == 0: ans =5 elif a == 0 and b!= 0: ans elif a != 0 and b == 0: ans = 0 elif b%a != 0: ans else: a = b / a if a < 0 : a = abs(a) b = 0 for i in range(1001): if i ** n == a: ans = i if b == 0 :ans = - ans print(ans)
1285340400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1.5 seconds
["2 2\n1 2\n2 3", "2 1\n1 2", "2 1\n3 4"]
bc8b4b74c2f2d486e2d2f03982ef1013
null
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b β€” the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space β€” indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.
The first line of the input data contains two integer numbers separated by a space n (1 ≀ n ≀ 105) and k (0 ≀ k ≀ 106) β€” the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≀ hi ≀ 106) is the height of the i-th book in millimeters.
standard output
standard input
Python 3
Python
1,900
train_019.jsonl
b95cf3dbc11991755548cba067a87d36
64 megabytes
["3 3\n14 12 10", "2 0\n10 10", "4 5\n8 19 10 13"]
PASSED
from bisect import * n,k=map(int,input().split()) h=list(map(int,input().split())) l=[] q=[] aa=-1 j=0 for i in range(n): l.insert(bisect(l,h[i]),h[i]) while l[-1]-l[0]>k: l.pop(bisect(l,h[j])-1) j+=1 if i-j+1>aa: aa=i-j+1 q=[] if i-j+1==aa: q.append([j+1,i+1]) print(aa,len(q)) for i in q: print(i[0],i[1])
1269673200
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["499122177 0", "499122193 249561095 249561092 873463811 499122178 124780545 623902721 0"]
a3a14dbb486a26d015b69187f87c53d4
NoteIn the first example the exact values of minimum expected values are: $$$\frac 1 2$$$, $$$\frac 0 2$$$.In the second example the exact values of minimum expected values are: $$$\frac{132} 8$$$, $$$\frac{54} 8$$$, $$$\frac{30} 8$$$, $$$\frac{17} 8$$$, $$$\frac{12} 8$$$, $$$\frac 7 8$$$, $$$\frac 3 8$$$, $$$\frac 0 8$$$.
You are creating a level for a video game. The level consists of $$$n$$$ rooms placed in a circle. The rooms are numbered $$$1$$$ through $$$n$$$. Each room contains exactly one exit: completing the $$$j$$$-th room allows you to go the $$$(j+1)$$$-th room (and completing the $$$n$$$-th room allows you to go the $$$1$$$-st room).You are given the description of the multiset of $$$n$$$ chests: the $$$i$$$-th chest has treasure value $$$c_i$$$.Each chest can be of one of two types: regular chestΒ β€” when a player enters a room with this chest, he grabs the treasure and proceeds to the next room; mimic chestΒ β€” when a player enters a room with this chest, the chest eats him alive, and he loses. The player starts in a random room with each room having an equal probability of being chosen. The players earnings is equal to the total value of treasure chests he'd collected before he lost.You are allowed to choose the order the chests go into the rooms. For each $$$k$$$ from $$$1$$$ to $$$n$$$ place the chests into the rooms in such a way that: each room contains exactly one chest; exactly $$$k$$$ chests are mimics; the expected value of players earnings is minimum possible. Please note that for each $$$k$$$ the placement is chosen independently.It can be shown that it is in the form of $$$\frac{P}{Q}$$$ where $$$P$$$ and $$$Q$$$ are non-negative integers and $$$Q \ne 0$$$. Report the values of $$$P \cdot Q^{-1} \pmod {998244353}$$$.
Print $$$n$$$ integersΒ β€” the $$$k$$$Β -th value should be equal to the minimum possible expected value of players earnings if the chests are placed into the rooms in some order and exactly $$$k$$$ of the chests are mimics. It can be shown that it is in the form of $$$\frac{P}{Q}$$$ where $$$P$$$ and $$$Q$$$ are non-negative integers and $$$Q \ne 0$$$. Report the values of $$$P \cdot Q^{-1} \pmod {998244353}$$$.
The first contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$)Β β€” the number of rooms and the number of chests. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^6$$$)Β β€” the treasure values of each chest.
standard output
standard input
PyPy 2
Python
2,600
train_066.jsonl
e36f04e429be1e796479b688dff526df
256 megabytes
["2\n1 2", "8\n10 4 3 6 5 10 7 5"]
PASSED
# Author: yumtam # Created at: 2020-09-11 00:33 from __future__ import division, print_function _interactive = False def main(): n = int(input()) ar = [ModInt(int(c)) for c in input().split()] ar.sort() prfsum = [ModInt(0)] for x in ar: prfsum.append(prfsum[-1]+x) def rsum(l, r): return prfsum[r]-prfsum[l] for d in range(1, n): r = n-d mult = ModInt(1) ans = ModInt(0) while True: l = max(0, r-d) ans = ans + mult*rsum(l, r) r = l mult += 1 if l == 0: break print(ans//n, end=' ') print(0) # Constants INF = float('inf') MOD = 998244353 # Python3 equivalent names import os, sys, itertools if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip # print-flush in interactive problems if _interactive: flush = sys.stdout.flush def printf(*args, **kwargs): print(*args, **kwargs) flush() # Debug print, only works on local machine LOCAL = "LOCAL_" in os.environ debug_print = (print) if LOCAL else (lambda *x, **y: None) # Fast IO if (not LOCAL) and (not _interactive): from io import BytesIO from atexit import register 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') # Some utility functions(Input, N-dimensional lists, ...) def input_as_list(): return [int(x) for x in input().split()] def input_with_offset(o): return [int(x)+o for x in input().split()] def input_as_matrix(n, m): return [input_as_list() for _ in range(n)] def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f() # Start of external code templates... # End of external code templates. from __pypy__.intop import * class ModInt(int): def __new__(cls, v): return int.__new__(cls, v%MOD) def __add__(self, other): return ModInt(int_mod(int_add(self, other), MOD)) def __sub__(self, other): return ModInt(int_mod(int_sub(self, other), MOD)) def __mul__(self, other): return ModInt(int_mulmod(self, other, MOD)) def __div__(self, other): return ModInt(int_mulmod(self, pow(other, MOD-2, MOD), MOD)) __truediv__ = __floordiv__ = __div__ def __pow__(self, power, modulo=MOD): return ModInt(int.__pow__(self, power, modulo)) main()
1594565100
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
3 seconds
["YES\nNO\nNO"]
146c856f8de005fe280e87f67833c063
null
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
The first line contains two non-negative numbers n and m (0 ≀ n ≀ 3Β·105, 0 ≀ m ≀ 3Β·105) β€” the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.
standard output
standard input
PyPy 3
Python
2,000
train_002.jsonl
d84cd12087f44d4a7f680d22ff9701f0
256 megabytes
["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"]
PASSED
from collections import defaultdict from math import ceil,floor import sys memory = set() mod = 1000000000000000003 p = 3 def hash_(s): pp = p result = 0 for ch in s: result += pp*(ord(ch)-ord('a')-1) pp = (pp*p)%mod; result %= mod return result % mod; def find(q): hash_0 = hash_(q) k = len(q) pw = p ext = 0 for j in range(len(q)): for ch in 'abc': if ch != q[j]: if ((hash_0 % mod + ((ord(ch)-ord(q[j]))*pw)% mod ) % mod) in memory: sys.stdout.write('YES\n') ext = 1 break if ext: break pw = (p * pw) % mod; if not ext: sys.stdout.write('NO\n') def main(): n,m = [int(i) for i in input().split()] for i in range(n): memory.add(hash_(sys.stdin.readline().strip())) for i in range(m): find(sys.stdin.readline().strip()) if __name__ == "__main__": ##sys.stdin = open("in.txt",'r') ##sys.stdout = open("out.txt",'w') main() ##sys.stdin.close() ##sys.stdout.close()
1423931400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["YES\n1 -2 3 -4\nNO\nYES\n1 1 -1 1 -1\nYES\n-40 13 40 0 -9 -31"]
e57345f5757654749b411727ebb99c80
NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds: The first element of $$$b$$$ is $$$1$$$. The sum of the first two elements of $$$b$$$ is $$$-1$$$. The sum of the first three elements of $$$b$$$ is $$$2$$$. The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds: The first element of $$$b$$$ is $$$1$$$. The sum of the first two elements of $$$b$$$ is $$$2$$$. The sum of the first three elements of $$$b$$$ is $$$1$$$. The sum of the first four elements of $$$b$$$ is $$$2$$$. The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds: The first element of $$$b$$$ is $$$-40$$$. The sum of the first two elements of $$$b$$$ is $$$-27$$$. The sum of the first three elements of $$$b$$$ is $$$13$$$. The sum of the first four elements of $$$b$$$ is $$$13$$$. The sum of the first five elements of $$$b$$$ is $$$4$$$. The sum of the first six elements of $$$b$$$ is $$$-27$$$.
You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that: The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$. For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.
For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$. If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) β€” the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$) Β β€” the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$) Β β€” the elements of $$$a$$$.
standard output
standard input
Python 3
Python
900
train_008.jsonl
ef311609473c6aac1e10ffc4056a6e90
256 megabytes
["4\n4\n1 -2 3 -4\n3\n0 0 0\n5\n1 -1 1 -1 1\n6\n40 -31 -9 0 13 -40"]
PASSED
def all_perms(elements): if len(elements) <= 1: yield elements else: for perm in all_perms(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] tests_no = int(input()) for _ in range(tests_no): n = int(input()) a = list(map(int, input().split())) whole_sum = sum(a) if whole_sum == 0: print("NO") elif whole_sum < 0: ri = n-1 li = 0 b = [0]*n for i in range(n): if a[i] >= 0: b[ri] = a[i] ri -= 1 else: b[li] = a[i] li += 1 print("YES") print(*b) else: ri = n - 1 li = 0 b = [0] * n for i in range(n): if a[i] <= 0: b[ri] = a[i] ri -= 1 else: b[li] = a[i] li += 1 print("YES") print(*b) ''' 100 1 -2 1 -1 1 0 1 1 1 2 2 -2 -2 2 -1 -2 2 0 -2 2 1 -2 2 2 -2 2 -2 -1 2 -1 -1 2 0 -1 2 1 -1 2 2 -1 2 -2 0 2 -1 0 2 0 0 2 1 0 2 2 0 2 -2 1 2 -1 1 2 0 1 2 1 1 '''
1602341400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["YES\n2 3 1 1", "YES\n1 1 1 1 1", "NO"]
bb7ecc5dbb922007bc0c25491aaa53d9
NoteFor the first sample, x1 = 2, x2 = 3, x3 = x4 = 1 is a valid labeling. Indeed, (3, 4), (1, 2), (1, 3), (1, 4) are the only pairs of cities with difference of labels not greater than 1, and these are precisely the roads of Bankopolia.For the second sample, all pairs of cities have difference of labels not greater than 1 and all pairs of cities have a road connecting them.For the last sample, it is impossible to construct a labeling satisfying the given constraints.
Oleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.Oleg wants to give a label to each city. Suppose the label of city i is equal to xi. Then, it must hold that for all pairs of cities (u, v) the condition |xu - xv| ≀ 1 holds if and only if there is a road connecting u and v.Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.
If the required labeling is not possible, output a single line containing the string "NO" (without quotes). Otherwise, output the string "YES" (without quotes) on the first line. On the next line, output n space-separated integers, x1, x2, ..., xn. The condition 1 ≀ xi ≀ 109 must hold for all i, and for all pairs of cities (u, v) the condition |xu - xv| ≀ 1 must hold if and only if there is a road connecting u and v.
The first line of input contains two space-separated integers n and m (2 ≀ n ≀ 3Β·105, 1 ≀ m ≀ 3Β·105)Β β€” the number of cities and the number of roads. Next, m lines follow. The i-th line contains two space-separated integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities and it is possible to travel from any city to any other city using some roads.
standard output
standard input
PyPy 2
Python
2,400
train_027.jsonl
8e64cfedd36167546a8c39a145640b9d
256 megabytes
["4 4\n1 2\n1 3\n1 4\n3 4", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n5 4", "4 3\n1 2\n1 3\n1 4"]
PASSED
import collections import sys readline = sys.stdin.readline write = sys.stdout.write n, m = map(int, readline().split()) g = [[i] for i in xrange(n)] for i in xrange(m): u, v = map(int, readline().split()) g[u-1].append(v-1) g[v-1].append(u-1) for i in xrange(n): g[i] = tuple(sorted(g[i])) s = {e: i for i, e in enumerate({e for e in g})} sn = len(s) sg = [set() for i in xrange(sn)] used = [0]*sn for v in xrange(n): lv = g[v] i = s[lv] if not used[i]: used[i] = 1 for t in g[v]: lt = g[t] if hash(lt) != hash(lv): j = s[lt] sg[i].add(j) sg[j].add(i) intwo = 1 one = 0; one_node = None for i in xrange(sn): if len(sg[i]) > 2: intwo = 0 break if len(sg[i]) <= 1: one = 1 one_node = i if intwo and one: used = [0]*sn deq = collections.deque() used[one_node] = 1 v = one_node ans = [-1]*sn cur = 1 while 1: ans[v] = cur cur += 1 for t in sg[v]: if not used[t]: used[t] = 1 v = t break else: break write("YES\n") write(" ".join(str(ans[s[e]]) for e in g)) write("\n") else: write("NO\n")
1494668100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["010", "010", "0000000", "0011001100001011101000"]
b52cecae4e40e652523d05b002af1c3d
NoteIn the first example: For the substrings of the length $$$1$$$ the length of the longest non-decreasing subsequnce is $$$1$$$; For $$$l = 1, r = 2$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{2}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{2}$$$ is $$$01$$$; For $$$l = 1, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{3}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{3}$$$ is $$$00$$$; For $$$l = 2, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{2}s_{3}$$$ is $$$1$$$ and the longest non-decreasing subsequnce of the substring $$$t_{2}t_{3}$$$ is $$$1$$$; The second example is similar to the first one.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.Kirk has a binary string $$$s$$$ (a string which consists of zeroes and ones) of length $$$n$$$ and he is asking you to find a binary string $$$t$$$ of the same length which satisfies the following conditions: For any $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) the length of the longest non-decreasing subsequence of the substring $$$s_{l}s_{l+1} \ldots s_{r}$$$ is equal to the length of the longest non-decreasing subsequence of the substring $$$t_{l}t_{l+1} \ldots t_{r}$$$; The number of zeroes in $$$t$$$ is the maximum possible.A non-decreasing subsequence of a string $$$p$$$ is a sequence of indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$i_1 &lt; i_2 &lt; \ldots &lt; i_k$$$ and $$$p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$$$. The length of the subsequence is $$$k$$$.If there are multiple substrings which satisfy the conditions, output any.
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
The first line contains a binary string of length not more than $$$2\: 000$$$.
standard output
standard input
Python 3
Python
2,000
train_024.jsonl
093c5cedf31c29750615bd45bd0ebc66
256 megabytes
["110", "010", "0001111", "0111001100111011101000"]
PASSED
s=input() s=list(s) l=len(s)-1 z=0 for i in range(l,-1,-1): if(s[i]=='0'): z=z+1 elif z: z-=1 else: s[i]='0' s="".join(s) print(s)
1566311700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["9", "4"]
566b91c278449e8eb3c724a6f00797e8
NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample: For example, the following movements can get the car from point (1, 0) to point (0, 0):
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) β€” "R", to point (x, y - 1) β€” "D", to point (x, y + 1) β€” "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).
Print a single integer β€” the number of different possible locations of the gang's headquarters.
The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the number of the car's movements from the headquarters to the stall. Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR". All movements are given in chronological order. Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.
standard output
standard input
Python 3
Python
1,700
train_024.jsonl
db4ff7f3d05bac3fd8858b5203fa2958
256 megabytes
["3\nUR\nUL\nULDR", "2\nDR\nDL"]
PASSED
#!/usr/local/bin/python3 n = int(input()) w = 1 h = 1 for _ in range(n): s = input() if s == 'ULDR': w += 1 h += 1 continue if s == 'UR' or s == 'DL': w += 1 continue h += 1 print(w * h)
1335532800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2", "2"]
783df1df183bf182bf9acbb99208cdb7
NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.
Output the answer to the problem.
The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| &gt; 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).
standard output
standard input
Python 3
Python
1,700
train_007.jsonl
a4cd8626e886baf95565e9f52dc16b6e
256 megabytes
["1 1\n-1 -1\n2\n0 1 0\n1 0 0", "1 1\n-1 -1\n3\n1 0 0\n0 1 0\n1 1 -3"]
PASSED
def town(): x1, y1= [int(i) for i in input().split()] x2, y2= [int(i) for i in input().split()] n= int(input()) ans= 0 for i in range(n): a, b, c= [int(k) for k in input().split()] if (a*x1 + b*y1 + c< 0 and a*x2 + b*y2 + c> 0) or (a*x1 + b*y1 + c> 0 and a*x2 + b*y2 + c< 0): ans+= 1 print(ans) return town()
1419438600
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2 3 1", "4 1 3 2"]
0da021cfe88c5a333db99064de12acbf
NoteIn the first example, $$$p = [2, 3, 4, 1]$$$, $$$m = 3$$$ and given swaps are $$$[(1, 4), (2, 1), (1, 3)]$$$.There is only one correct order of swaps i.e $$$[2, 3, 1]$$$. First we perform the swap $$$2$$$ from the input i.e $$$(2, 1)$$$, $$$p$$$ becomes $$$[3, 2, 4, 1]$$$. Then we perform the swap $$$3$$$ from the input i.e $$$(1, 3)$$$, $$$p$$$ becomes $$$[4, 2, 3, 1]$$$. Finally we perform the swap $$$1$$$ from the input i.e $$$(1, 4)$$$ and $$$p$$$ becomes $$$[1, 2, 3, 4]$$$ which is sorted. In the second example, $$$p = [6, 5, 1, 3, 2, 4]$$$, $$$m = 4$$$ and the given swaps are $$$[(3, 1), (2, 5), (6, 3), (6, 4)]$$$.One possible correct order of swaps is $$$[4, 2, 1, 3]$$$. Perform the swap $$$4$$$ from the input i.e $$$(6, 4)$$$, $$$p$$$ becomes $$$[6, 5, 1, 4, 2, 3]$$$. Perform the swap $$$2$$$ from the input i.e $$$(2, 5)$$$, $$$p$$$ becomes $$$[6, 2, 1, 4, 5, 3]$$$. Perform the swap $$$1$$$ from the input i.e $$$(3, 1)$$$, $$$p$$$ becomes $$$[1, 2, 6, 4, 5, 3]$$$. Perform the swap $$$3$$$ from the input i.e $$$(6, 3)$$$ and $$$p$$$ becomes $$$[1, 2, 3, 4, 5, 6]$$$ which is sorted. There can be other possible answers such as $$$[1, 2, 4, 3]$$$.
Alice had a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Alice can swap a pair $$$(x, y)$$$ which means swapping elements at positions $$$x$$$ and $$$y$$$ in $$$p$$$ (i.e. swap $$$p_x$$$ and $$$p_y$$$). Alice recently learned her first sorting algorithm, so she decided to sort her permutation in the minimum number of swaps possible. She wrote down all the swaps in the order in which she performed them to sort the permutation on a piece of paper. For example, $$$[(2, 3), (1, 3)]$$$ is a valid swap sequence by Alice for permutation $$$p = [3, 1, 2]$$$ whereas $$$[(1, 3), (2, 3)]$$$ is not because it doesn't sort the permutation. Note that we cannot sort the permutation in less than $$$2$$$ swaps. $$$[(1, 2), (2, 3), (2, 4), (2, 3)]$$$ cannot be a sequence of swaps by Alice for $$$p = [2, 1, 4, 3]$$$ even if it sorts the permutation because $$$p$$$ can be sorted in $$$2$$$ swaps, for example using the sequence $$$[(4, 3), (1, 2)]$$$. Unfortunately, Bob shuffled the sequence of swaps written by Alice.You are given Alice's permutation $$$p$$$ and the swaps performed by Alice in arbitrary order. Can you restore the correct sequence of swaps that sorts the permutation $$$p$$$? Since Alice wrote correct swaps before Bob shuffled them up, it is guaranteed that there exists some order of swaps that sorts the permutation.
Print a permutation of $$$m$$$ integers Β β€” a valid order of swaps written by Alice that sorts the permutation $$$p$$$. See sample explanation for better understanding. In case of multiple possible answers, output any.
The first line contains $$$2$$$ integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le n - 1)$$$ Β β€” the size of permutation and the minimum number of swaps required to sort the permutation. The next line contains $$$n$$$ integers $$$p_1, p_2, ..., p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) Β β€” the elements of $$$p$$$. It is guaranteed that $$$p$$$ forms a permutation. Then $$$m$$$ lines follow. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ Β β€” the $$$i$$$-th swap $$$(x_i, y_i)$$$. It is guaranteed that it is possible to sort $$$p$$$ with these $$$m$$$ swaps and that there is no way to sort $$$p$$$ with less than $$$m$$$ swaps.
standard output
standard input
Python 3
Python
2,700
train_101.jsonl
64057e6bf83be5025b9ae84095a2ff5f
256 megabytes
["4 3\n2 3 4 1\n1 4\n2 1\n1 3", "6 4\n6 5 1 3 2 4\n3 1\n2 5\n6 3\n6 4"]
PASSED
import copy import gc import itertools from array import array from fractions import Fraction import heapq import math import operator import os, sys import profile import cProfile import random import re import string from bisect import bisect_left, bisect_right from collections import defaultdict, deque, Counter from functools import reduce, lru_cache from io import IOBase, BytesIO from itertools import count, groupby, accumulate, permutations, combinations_with_replacement, product from math import gcd from operator import xor, add from typing import List # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # print = lambda d: sys.stdout.write(str(d)+"\n") def read_int_list(): return list(map(int, input().split())) def read_int_tuple(): return tuple(map(int, input().split())) def read_int(): return int(input()) # endregion ### CODE HERE # f = open('inputs', 'r') # def input(): return f.readline().rstrip("\r\n") def solve(n, nums, m, edges): seen = [False] * n gs = [] for i in range(n): if seen[i]: continue gl = [] while not seen[i]: gl.append(i) seen[i] = True i = nums[i] if len(gl) > 1: gs.append(gl) for group in gs: d = {u: i for i, u in enumerate(group)} for u in group: edges[u].sort(key=lambda t: (d[t[0]] - d[u]) % n) top_graph = [[] for _ in range(m)] indeg = [0] * m for es in edges: if len(es) < 2: continue for i in range(len(es) - 1): u, v = es[i][1], es[i + 1][1] top_graph[u].append(v) indeg[v] += 1 q = deque([u for u in range(m) if indeg[u] == 0]) res = [] while q: u = q.popleft() res.append(u + 1) for v in top_graph[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) print(*res) def main(): for _ in range(1): n, m = read_int_tuple() nums = [x - 1 for x in read_int_list()] edges = [[] for _ in range(n)] for i in range(m): u, v = read_int_tuple() edges[u - 1].append((v - 1, i)) edges[v - 1].append((u - 1, i)) solve(n, nums, m, edges) if __name__ == "__main__": main() # cProfile.run("main()")
1653230100
[ "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 1 ]
2 seconds
["1 1 3 8\n-1\n0 0 0 0 0"]
f4b790bef9a6cbcd5d1f9235bcff7c8f
NoteIn the second example, there are two suitable arrays: $$$[2, 8, 5]$$$ and $$$[2, 8, 11]$$$.
For an array of non-negative integers $$$a$$$ of size $$$n$$$, we construct another array $$$d$$$ as follows: $$$d_1 = a_1$$$, $$$d_i = |a_i - a_{i - 1}|$$$ for $$$2 \le i \le n$$$.Your task is to restore the array $$$a$$$ from a given array $$$d$$$, or to report that there are multiple possible arrays.
For each test case, print the elements of the array $$$a$$$, if there is only one possible array $$$a$$$. Otherwise, print $$$-1$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$)Β β€” the size of the arrays $$$a$$$ and $$$d$$$. The second line contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$0 \le d_i \le 100$$$)Β β€” the elements of the array $$$d$$$. It can be shown that there always exists at least one suitable array $$$a$$$ under these constraints.
standard output
standard input
PyPy 3-64
Python
1,100
train_109.jsonl
ebd0536d3f01c09266c968c2c9e3844a
256 megabytes
["3\n\n4\n\n1 0 2 5\n\n3\n\n2 6 3\n\n5\n\n0 0 0 0 0"]
PASSED
for _ in range(int(input())): n=int(input()) d=list(map(int,input().split())) ans=[] ans.append(d[0]) count=0 # print(ans[1]+d[2]) for i in range(1,n): first=ans[i-1]+d[i] second=ans[i-1]-d[i] if first>=0 and second>=0 and first!=second: count+=1 break else: ans.append(first) if count==0: print(*ans) else: print(-1)
1664462100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["BAAAABAB", "ABAAAABBBAABAAB"]
cd22a61e8288275abac47ee68d6098c3
NoteIn the first sample, if Bob puts the token on the number (not position): $$$1$$$: Alice can move to any number. She can win by picking $$$7$$$, from which Bob has no move. $$$2$$$: Alice can move to $$$3$$$ and $$$5$$$. Upon moving to $$$5$$$, Bob can win by moving to $$$8$$$. If she chooses $$$3$$$ instead, she wins, as Bob has only a move to $$$4$$$, from which Alice can move to $$$8$$$. $$$3$$$: Alice can only move to $$$4$$$, after which Bob wins by moving to $$$8$$$. $$$4$$$, $$$5$$$, or $$$6$$$: Alice wins by moving to $$$8$$$. $$$7$$$, $$$8$$$: Alice has no move, and hence she loses immediately.
After a long day, Alice and Bob decided to play a little game. The game board consists of $$$n$$$ cells in a straight line, numbered from $$$1$$$ to $$$n$$$, where each cell contains a number $$$a_i$$$ between $$$1$$$ and $$$n$$$. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $$$i$$$ to cell $$$j$$$ only if the following two conditions are satisfied: the number in the new cell $$$j$$$ must be strictly larger than the number in the old cell $$$i$$$ (i.e. $$$a_j &gt; a_i$$$), and the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $$$|i-j|\bmod a_i = 0$$$). Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.
Print $$$s$$$Β β€” a string of $$$n$$$ characters, where the $$$i$$$-th character represents the outcome of the game if the token is initially placed in the cell $$$i$$$. If Alice wins, then $$$s_i$$$ has to be equal to "A"; otherwise, $$$s_i$$$ has to be equal to "B".
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). Furthermore, there are no pair of indices $$$i \neq j$$$ such that $$$a_i = a_j$$$.
standard output
standard input
PyPy 3
Python
1,600
train_036.jsonl
032fca37d8c85d7751ead9e0b08db985
256 megabytes
["8\n3 6 5 4 2 7 1 8", "15\n3 11 2 5 10 9 7 13 15 8 4 12 6 1 14"]
PASSED
n=int(input()) a=[*map(int,input().split())] s=[0]*n m=n while m: for i,x in enumerate(a): if s[i]==0: r=range(i%x,n,x) if all(a[j]<=x or s[j]=='A'for j in r):s[i]='B';m-=1 if any(a[j]>x and s[j]=='B'for j in r):s[i]='A';m-=1 print(''.join(s))
1538931900
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
c9d07fdf0d3293d5564275ebbabbcf12
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
standard output
standard input
PyPy 2
Python
1,700
train_003.jsonl
d149f7c4d7e511a632579b453f282d36
256 megabytes
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
PASSED
from collections import defaultdict def all_path_shortest(adj_list): src_to_dst = {node: defaultdict(lambda: float('inf')) for node in adj_list} for src in adj_list: for dest in adj_list[src]: src_to_dst[src][dest] = 1 for src in adj_list: src_to_dst[src][src] = 0 # Using node k, can we get from src to dest faster for k in adj_list: for src in adj_list: for dest in adj_list: if src_to_dst[src][k] + src_to_dst[k][dest] < src_to_dst[src][dest]: src_to_dst[src][dest] = src_to_dst[src][k] + src_to_dst[k][dest] return src_to_dst # Input parsing n = int(raw_input()) adj_matrix = [raw_input() for _ in range(n)] raw_input() path = [int(e) - 1 for e in raw_input().split()] adj_list = {i: [k for k in range(n) if adj_matrix[i][k] == '1'] for i in range(n)} shortest_paths = all_path_shortest(adj_list) res_path = [] hops = 0 for i, curr_node in enumerate(path): if i == 0 or i == len(path) - 1: res_path.append(curr_node) hops = 0 else: last_added_node = res_path[-1] next_node = path[i + 1] dist_between = shortest_paths[last_added_node][next_node] if dist_between < hops + 1: res_path.append(curr_node) hops = 0 # How many hops have we had since last adding node? hops += 1 print len(res_path) print ' '.join(str(e + 1) for e in res_path)
1566311700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nNO\nYES"]
b116ab1cae8d64608641b339b8654e21
NoteThe first test case is pictured above.In the second test case, the tree is a path. We can show that the snake cannot reverse itself.In the third test case, we can show that the snake cannot reverse itself.In the fourth test case, an example solution is:$$$(15,12)\to (16,11)\to (15,13)\to (10,14)\to (8,13)\to (4,11)\to (1,10)$$$$$$\to (2,8)\to (3,4)\to (2,5)\to (1,6)\to (4,7)\to (8,6)\to (10,5)$$$$$$\to (11,4)\to (13,8)\to (14,10)\to (13,15)\to (11,16)\to (12,15)$$$.
There is an undirected tree of $$$n$$$ vertices, connected by $$$n-1$$$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $$$a$$$ and its tail is at vertex $$$b$$$. The snake's body occupies all vertices on the unique simple path between $$$a$$$ and $$$b$$$.The snake wants to know if it can reverse itself Β β€” that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail. Let's denote a snake position by $$$(h,t)$$$, where $$$h$$$ is the index of the vertex with the snake's head, $$$t$$$ is the index of the vertex with the snake's tail. This snake can reverse itself with the movements $$$(4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4)$$$. Determine if it is possible to reverse the snake with some sequence of operations.
For each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise.
The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$) Β β€” the number of test cases. The next lines contain descriptions of test cases. The first line of each test case contains three integers $$$n,a,b$$$ ($$$2\le n\le 10^5,1\le a,b\le n,a\ne b$$$). Each of the next $$$n-1$$$ lines contains two integers $$$u_i,v_i$$$ ($$$1\le u_i,v_i\le n,u_i\ne v_i$$$), indicating an edge between vertices $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
3,000
train_060.jsonl
ed674f9696a8d18b4dde49ca909a2d3c
256 megabytes
["4\n8 4 7\n1 2\n2 3\n1 4\n4 5\n4 6\n1 7\n7 8\n4 3 2\n4 3\n1 2\n2 3\n9 3 5\n1 2\n2 3\n3 4\n1 5\n5 6\n6 7\n1 8\n8 9\n16 15 12\n1 2\n2 3\n1 4\n4 5\n5 6\n6 7\n4 8\n8 9\n8 10\n10 11\n11 12\n11 13\n13 14\n10 15\n15 16"]
PASSED
from sys import stdin import itertools input = stdin.readline def getint(): return int(input()) def getints(): return list(map(int, input().split())) def getint1(): return list(map(lambda x: int(x) - 1, input().split())) def getstr(): return input()[:-1] def solve(): n, a, b = getint1() n += 1 adj = [[] for _ in range(n)] for _ in range(n - 1): u, v = getint1() adj[u].append(v) adj[v].append(u) # dfs 1 max_child = [[-1] * 3 for _ in range(n)] stack = [(a, -1, 1)] # (node, parent) while stack: u, p, flag = stack.pop() if p != -1 and len(adj[u]) < 2: max_child[u][0] = 1 continue if flag == 1: stack.append((u, p, 0)) for v in adj[u]: if v == p: continue stack.append((v, u, 1)) else: for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > max_child[u][0]: max_child[u][2] = max_child[u][1] max_child[u][1] = max_child[u][0] max_child[u][0] = len_v elif len_v > max_child[u][1]: max_child[u][2] = max_child[u][1] max_child[u][1] = len_v elif len_v > max_child[u][2]: max_child[u][2] = len_v # end of dfs 1 # dfs 2 body = [] ret = [False] * n max_parent = [-1] * n stack.clear() stack = [(a, -1, 0)] # (node, parent, max len from parent) while stack: u, p, mxp = stack.pop() if mxp >= 0: stack.append((u, p, -1)) if p != -1 and len(adj[u]) < 2: continue max_parent[u] = mxp + 1 chlen = [max_parent[u], -3] for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > chlen[0]: chlen[1] = chlen[0] chlen[0] = len_v elif len_v > chlen[1]: chlen[1] = len_v for v in adj[u]: if v == p: continue stack.append( (v, u, chlen[int(max_child[v][0] + 1 == chlen[0])])) else: is_body = (u == b) if not is_body: for v in adj[u]: if v != p and ret[v]: is_body = True break if is_body: body.append(u) ret[u] = is_body del ret # end of dfs2 ok = False body_len = len(body) can_turn = [False] * n for i in range(n): if 3 <= sum(1 for l in max_child[i] + [max_parent[i]] if l >= body_len): can_turn[i] = True ok = True if not ok: print("NO") return treelen = [1] * body_len # print(body) for i in range(body_len): cur = body[i] pre = -1 if i == 0 else body[i - 1] nxt = -1 if i + 1 == body_len else body[i + 1] for v in adj[cur]: if v == pre or v == nxt: continue treelen[i] = max(treelen[i], max_child[v][0] + 1) if can_turn[v]: can_turn[cur] = True continue # dfs 3 stack = [(v, cur)] while stack and not can_turn[cur]: u, p = stack.pop() for w in adj[u]: if w == p: continue if can_turn[w]: can_turn[cur] = True break stack.append((w, u)) stack.clear() # end of dfs 3 # print(i, cur, can_turn[cur]) # use two pointer to find if we can enter the turing point # print(body_len, treelen) l = 0 r = body_len - 1 lmax = treelen[r] - 1 rmin = body_len - treelen[l] ok = (can_turn[body[l]] or can_turn[body[r]]) while not ok and (l < lmax or rmin < r): if l < lmax: l += 1 rmin = min(rmin, l + (body_len - treelen[l])) if rmin < r: r -= 1 lmax = max(lmax, r - (body_len - treelen[r])) if can_turn[body[l]] or can_turn[body[r]]: ok = True ## print("YES" if ok else "NO") return # end of solve if __name__ == "__main__": # solve() # for t in range(getint()): # print('Case #', t + 1, ': ', sep='') # solve() for _ in range(getint()): solve()
1595342100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["8", "0", "10000800015"]
0e162ea665732714283317e7c052e234
null
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.Sticks with lengths a1, a2, a3 and a4 can make a rectangle if the following properties are observed: a1 ≀ a2 ≀ a3 ≀ a4 a1 = a2 a3 = a4 A rectangle can be made of sticks with lengths of, for example, 3Β 3Β 3Β 3 or 2Β 2Β 4Β 4. A rectangle cannot be made of, for example, sticks 5Β 5Β 5Β 7.Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.You have to answer the question β€” what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?
The first line of the output must contain a single non-negative integerΒ β€”Β the maximum total area of the rectangles that Ilya can make from the available sticks.
The first line of the input contains a positive integer n (1 ≀ n ≀ 105)Β β€”Β the number of the available sticks. The second line of the input contains n positive integers li (2 ≀ li ≀ 106)Β β€”Β the lengths of the sticks.
standard output
standard input
Python 3
Python
1,600
train_010.jsonl
8931ecfe16ea421314b2adfadf7456d7
256 megabytes
["4\n2 4 4 2", "4\n2 2 3 5", "4\n100003 100004 100005 100006"]
PASSED
n=int(input()) l=list(map(int,input().split())) l=sorted(l) l=l[::-1] k=0 b=-1 for i in range(n-1) : if l[i]==l[i+1] and b==-1 : b=l[i] l[i+1]=-1 if l[i]==l[i+1] and b!=-1 : k+=b*l[i] b=-1 l[i+1]=-1 if l[i]==l[i+1]+1 and b==-1: b=l[i]-1 l[i+1]=-1 if l[i]==l[i+1]+1 and b!=-1 : k+=b*(l[i]-1) b=-1 l[i+1]=-1 print(k)
1427387400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 2", "0 0", "0 3"]
19a0c05eb2d1559ccfe60e210c6fcd6a
null
The map of Bertown can be represented as a set of $$$n$$$ intersections, numbered from $$$1$$$ to $$$n$$$ and connected by $$$m$$$ one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection $$$v$$$ to another intersection $$$u$$$ is the path that starts in $$$v$$$, ends in $$$u$$$ and has the minimum length among all such paths.Polycarp lives near the intersection $$$s$$$ and works in a building near the intersection $$$t$$$. Every day he gets from $$$s$$$ to $$$t$$$ by car. Today he has chosen the following path to his workplace: $$$p_1$$$, $$$p_2$$$, ..., $$$p_k$$$, where $$$p_1 = s$$$, $$$p_k = t$$$, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from $$$s$$$ to $$$t$$$.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection $$$s$$$, the system chooses some shortest path from $$$s$$$ to $$$t$$$ and shows it to Polycarp. Let's denote the next intersection in the chosen path as $$$v$$$. If Polycarp chooses to drive along the road from $$$s$$$ to $$$v$$$, then the navigator shows him the same shortest path (obviously, starting from $$$v$$$ as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection $$$w$$$ instead, the navigator rebuilds the path: as soon as Polycarp arrives at $$$w$$$, the navigation system chooses some shortest path from $$$w$$$ to $$$t$$$ and shows it to Polycarp. The same process continues until Polycarp arrives at $$$t$$$: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path $$$[1, 2, 3, 4]$$$ ($$$s = 1$$$, $$$t = 4$$$): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at $$$1$$$, the system chooses some shortest path from $$$1$$$ to $$$4$$$. There is only one such path, it is $$$[1, 5, 4]$$$; Polycarp chooses to drive to $$$2$$$, which is not along the path chosen by the system. When Polycarp arrives at $$$2$$$, the navigator rebuilds the path by choosing some shortest path from $$$2$$$ to $$$4$$$, for example, $$$[2, 6, 4]$$$ (note that it could choose $$$[2, 3, 4]$$$); Polycarp chooses to drive to $$$3$$$, which is not along the path chosen by the system. When Polycarp arrives at $$$3$$$, the navigator rebuilds the path by choosing the only shortest path from $$$3$$$ to $$$4$$$, which is $$$[3, 4]$$$; Polycarp arrives at $$$4$$$ along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get $$$2$$$ rebuilds in this scenario. Note that if the system chose $$$[2, 3, 4]$$$ instead of $$$[2, 6, 4]$$$ during the second step, there would be only $$$1$$$ rebuild (since Polycarp goes along the path, so the system maintains the path $$$[3, 4]$$$ during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?
Print two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le m \le 2 \cdot 10^5$$$) β€” the number of intersections and one-way roads in Bertown, respectively. Then $$$m$$$ lines follow, each describing a road. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) denoting a road from intersection $$$u$$$ to intersection $$$v$$$. All roads in Bertown are pairwise distinct, which means that each ordered pair $$$(u, v)$$$ appears at most once in these $$$m$$$ lines (but if there is a road $$$(u, v)$$$, the road $$$(v, u)$$$ can also appear). The following line contains one integer $$$k$$$ ($$$2 \le k \le n$$$) β€” the number of intersections in Polycarp's path from home to his workplace. The last line contains $$$k$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_k$$$ ($$$1 \le p_i \le n$$$, all these integers are pairwise distinct) β€” the intersections along Polycarp's path in the order he arrived at them. $$$p_1$$$ is the intersection where Polycarp lives ($$$s = p_1$$$), and $$$p_k$$$ is the intersection where Polycarp's workplace is situated ($$$t = p_k$$$). It is guaranteed that for every $$$i \in [1, k - 1]$$$ the road from $$$p_i$$$ to $$$p_{i + 1}$$$ exists, so the path goes along the roads of Bertown.
standard output
standard input
Python 3
Python
1,700
train_007.jsonl
e631289020649365f59f8d4d2dc8f7ba
512 megabytes
["6 9\n1 5\n5 4\n1 2\n2 3\n3 4\n4 1\n2 6\n6 4\n4 2\n4\n1 2 3 4", "7 7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 1\n7\n1 2 3 4 5 6 7", "8 13\n8 7\n8 6\n7 5\n7 4\n6 5\n6 4\n5 3\n5 2\n4 3\n4 2\n3 1\n2 1\n1 8\n5\n8 7 5 2 1"]
PASSED
from collections import deque n, m = map(int, input().split()) graph = [[] for _ in range(n + 1)] inverse = [[] for _ in range(n + 1)] for _ in range(m): u, v = map(int, input().split()) graph[u].append(v) inverse[v].append(u) k = int(input()) way = list(map(int, input().split())) s = way[0] t = way[-1] queue = deque() queue.append(t) d = [0] * (n + 1) used = [False] * (n + 1) used[t] = True while len(queue): cur = queue[0] queue.popleft() for to in inverse[cur]: if not used[to]: d[to] = d[cur] + 1 queue.append(to) used[to] = True ans_max = 0 ans_min = 0 for i in range(k - 1): if d[way[i]] > d[way[i + 1]]: to_min = -1 for to in graph[way[i]]: if to != way[i + 1] and d[to] <= d[way[i + 1]]: to_min = to if to_min != -1: ans_max += 1 else: ans_max += 1 ans_min += 1 print(ans_min, ans_max)
1583068500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["3 1", "3 1", "9 3", "18 4", "No solution"]
763aa950a9a8e5c975a6028e014de20f
NoteIn the first sample there is only one longest good substring: "Abo" itself. The other good substrings are "b", "Ab", "bo", but these substrings have shorter length.In the second sample there is only one longest good substring: "EIS". The other good substrings are: "S", "IS".
Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v ≀ 2c.The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.
Print on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print "No solution" without the quotes. Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.
The only input line contains a non-empty string s consisting of no more than 2Β·105 uppercase and lowercase Latin letters. We shall regard letters "a", "e", "i", "o", "u" and their uppercase variants as vowels.
standard output
standard input
Python 2
Python
2,000
train_035.jsonl
0f18aae08a1e206c4f427e500a355de7
256 megabytes
["Abo", "OEIS", "auBAAbeelii", "AaaBRAaaCAaaDAaaBRAaa", "EA"]
PASSED
line = raw_input().lower() line_len = len(line) f = [[0,i] for i in xrange(line_len+1)] for index in xrange(line_len): f[index+1][0] = f[index][0] f[index+1][0] += -1 if line[index] in 'aeiou' else 2 f.sort() ans_len, ans_cnt = 0, 0 min_used = f[0][1] for index in xrange(1,line_len+1): if f[index][1]-min_used > ans_len: ans_len = f[index][1]-min_used ans_cnt = 1 elif f[index][1]-min_used == ans_len: ans_cnt += 1 min_used = min(min_used, f[index][1]) if ans_len: print ans_len, ans_cnt else: print 'No solution'
1324015200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2", "0", "1"]
64d85fcafab0e1b477bc888408f54eb5
NoteThe tree corresponding to the first example: The answer is $$$2$$$, some of the possible answers are the following: $$$[(1, 5), (1, 6)]$$$, $$$[(1, 4), (1, 7)]$$$, $$$[(1, 6), (1, 7)]$$$.The tree corresponding to the second example: The answer is $$$0$$$.The tree corresponding to the third example: The answer is $$$1$$$, only one possible way to reach it is to add the edge $$$(1, 3)$$$.
You are given an undirected tree consisting of $$$n$$$ vertices. An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $$$1$$$ to any other vertex is at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.
Print a single integer β€” the minimum number of edges you have to add in order to make the shortest distance from the vertex $$$1$$$ to any other vertex at most $$$2$$$. Note that you are not allowed to add loops and multiple edges.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β€” the number of vertices in the tree. The following $$$n - 1$$$ lines contain edges: edge $$$i$$$ is given as a pair of vertices $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
standard output
standard input
PyPy 2
Python
2,100
train_014.jsonl
102d89c3bc1df14041a2a244925bac17
256 megabytes
["7\n1 2\n2 3\n2 4\n4 5\n4 6\n5 7", "7\n1 2\n1 3\n2 4\n2 5\n3 6\n1 7", "7\n1 2\n2 3\n3 4\n3 5\n3 6\n3 7"]
PASSED
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) root = 0 found = [0]*n found[root] = 1 bfs = [root] for _ in range(2): for node in list(bfs): for nei in coupl[node]: if not found[nei]: found[nei] = 1 bfs.append(nei) P = [-1]*n P[root] = root bfs = [root] for node in bfs: for nei in coupl[node]: if P[nei] == -1: P[nei] = node bfs.append(nei) marker = [0]*n deg = [len(c) for c in coupl] found2 = [0]*n for node in reversed(bfs): if found[node] or marker[node] or any(marker[nei] for nei in coupl[node]): continue node = P[node] marker[node] = 1 found2[node] = 1 for nei in coupl[node]: found2[nei] = 1 print sum(marker)
1535122200
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["3\nhello test one \nok bye two \na b", "2\na \nA a A a A", "4\nA K M \nB F H L N O \nC D G I P \nE J"]
da08dd34ac3c05af58926f70abe5acd0
NoteThe first example is explained in the statements.
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: at first, the text of the comment is written; after that the number of comments is written, for which this comment is a parent comment (i.Β e. the number of the replies to this comments); after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: at first, print a integer dΒ β€” the maximum depth of nesting comments; after that print d lines, the i-th of them corresponds to nesting level i; for the i-th row print comments of nesting level i in the order of their appearance in the Policarp's comments feed, separated by space.
Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input.
The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros. The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid.
standard output
standard input
Python 3
Python
1,700
train_009.jsonl
031560f123208442d5117ddda142778d
256 megabytes
["hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0", "a,5,A,0,a,0,A,0,a,0,A,0", "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0"]
PASSED
#!/usr/bin/env python3 import collections def solve(): comments = input().split(",") comments_by_depth = collections.defaultdict(list) current_depth = 0 current_depth_limit = [10000000] cur_cmt = [0] * 2 for i, item in enumerate(comments): cur_cmt[i % 2] = item if i % 2 == 1: while current_depth_limit[-1] == 0: current_depth_limit.pop() current_depth -= 1 text = cur_cmt[0] child_count = int(cur_cmt[1]) comments_by_depth[current_depth].append(text) current_depth_limit[-1] -= 1 if child_count > 0: current_depth += 1 current_depth_limit.append(child_count) depths = list(sorted(comments_by_depth.keys())) if depths: print(depths[-1] + 1) else: print(0) for d in depths: print(" ".join(comments_by_depth[d])) if __name__ == '__main__': solve()
1482113100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["6\n5\n375000012\n500000026\n958557139\n0\n49735962"]
32ab22abbbce760be53ea8928876431c
NoteIn the first test case, the entire game has $$$3$$$ turns, and since $$$m = 3$$$, Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is $$$k = 2$$$, every turn.In the third test case, Alice has a strategy to guarantee a score of $$$\frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}$$$.In the fourth test case, Alice has a strategy to guarantee a score of $$$\frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}$$$.
This is the hard version of the problem. The difference is the constraints on $$$n$$$, $$$m$$$ and $$$t$$$. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers $$$n$$$, $$$m$$$ and $$$k$$$, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially $$$0$$$. The game consists of $$$n$$$ turns. Each turn, Alice picks a real number from $$$0$$$ to $$$k$$$ (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least $$$m$$$ out of the $$$n$$$ turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?
For each test case output a single integer number β€” the score of the optimal game modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9 + 7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x &lt; M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
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. Each test case consists of a single line containing the three integers, $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le m \le n \le 10^6, 0 \le k &lt; 10^9 + 7$$$) β€” the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
2,400
train_093.jsonl
066d4783637a1bd8ba08968ced234c5f
256 megabytes
["7\n\n3 3 2\n\n2 1 10\n\n6 3 10\n\n6 4 10\n\n100 1 1\n\n4 4 0\n\n69 4 20"]
PASSED
import sys import os from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") MOD=10**9+7 facts=[1 for _ in range(10**6+1)] for i in range(1,10**6+1): facts[i]=(facts[i-1]*i)%MOD factinvs=[1 for _ in range(10**6+1)] factinvs[-1]=pow(facts[-1],MOD-2,MOD) temp=factinvs[-1] for i in range(10**6,1,-1): factinvs[i-1]=(factinvs[i]*i)%MOD powinvs=[1 for _ in range(10**6+1)] inv_2=pow(2,MOD-2,MOD) for i in range(1,10**6+1): powinvs[i]=powinvs[i-1]*inv_2%MOD def binom(n,m): return facts[n]*factinvs[m]*factinvs[n-m]%MOD def solve(): n,m,k=map(int,input().split()) if n==m: print((m*k)%MOD) return res=0 for i in range(1,m+1): c=binom(n-i-1,m-i) p=powinvs[n-i] res+=(c*p*i*k)%MOD res%=MOD print(res) for _ in range(int(input())):solve()
1642862100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["2", "3"]
05f251de93536024c05fbd77ed01b70b
null
Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed. It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.
Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).
The first line contains two integers n and m (2 ≀ n, m ≀ 106).
standard output
standard input
Python 2
Python
2,100
train_056.jsonl
e8a4b8e7484a3d8edb2be847208d4ae0
256 megabytes
["3 4", "3 3"]
PASSED
def gcd(x,y): return y and gcd(y,x%y) or x n,m=map(int,raw_input().split()) print gcd(n-1,m-1)+1
1302879600
[ "number theory", "graphs" ]
[ 0, 0, 1, 0, 1, 0, 0, 0 ]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
3336662e6362693b8ac9455d4c2fe158
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) β€” the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) β€” the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
standard output
standard input
PyPy 2
Python
1,300
train_026.jsonl
eaa1e3df065007dc9c2e536e873df6d4
256 megabytes
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
PASSED
#!/usr/bin/env pypy from __future__ import division, print_function from collections import defaultdict, Counter, deque from future_builtins import ascii, filter, hex, map, oct, zip from itertools import imap as map, izip as zip from __builtin__ import xrange as range from math import ceil, log from _continuation import continulet from cStringIO import StringIO from io import IOBase import __pypy__ from pprint import pprint from bisect import bisect, insort, bisect_left, bisect_right import sys import os import re inf = float('inf') mod = int(1e9) + 7 mod_ = 998244353 ''' Check for special cases (n=1) One wrong submission = 10 mins penalty! do smth instead of nothing and stay organized ''' def solve(n, s): swaps = [] for i in range(n-1): if s[i] == '0' and s[i] == s[i+1]: swaps.append(i+1) s[i] = '1' s[i+1] = '1' if s.count('0')%2 == 1: return [-1] i = 0 while i < n: if s[i] == '0': j = s.index('0', i+1) swaps += list(range(i+1, j+1)) i = j+1 else: i += 1 return swaps def main(): n = int(input()) s = input() if len(set(s)) == 1: print(0) return s = s.replace('B', '1') s = s.replace('W', '0') ans1 = solve(n, list(s)) s = list(s) for i in range(n): if s[i] == '1': s[i] = '0' else: s[i] = '1' ans2 = solve(n, list(s)) if ans1 != [-1] and len(ans1) <= 3*n: print(len(ans1)) print(*ans1) elif ans2 != [-1] and len(ans2) <= 3*n: print(len(ans2)) print(*ans2) else: print(-1) BUFSIZE = 8192 class FastI(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = StringIO() self.newlines = 0 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("\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() class FastO(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = __pypy__.builders.StringBuilder() self.write = lambda s: self._buffer.append(s) def flush(self): os.write(self._fd, self._buffer.build()) self._buffer = __pypy__.builders.StringBuilder() def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() def gcd(x, y): while y: x, y = y, x % y return x sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": def bootstrap(cont): call, arg = cont.switch() while True: call, arg = cont.switch(to=continulet( lambda _, f, args: f(*args), call, arg)) cont = continulet(bootstrap) cont.switch() main()
1576401300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3 2", "0 0"]
9a365e26f58ecb22a1e382fad3062387
NoteIn the first sample the game went like this: R - R. Draw. P - S. Nikephoros loses. S - P. Polycarpus loses. R - P. Nikephoros loses. P - R. Polycarpus loses. S - S. Draw. R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
The first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
standard output
standard input
Python 3
Python
1,300
train_043.jsonl
d87b306ee5562691c3987bc0c9d98ef1
256 megabytes
["7\nRPS\nRSPP", "5\nRRRRRRRR\nR"]
PASSED
n = int(input()) a = input() b = input() ai = 0 alen = len(a) bi = 0 blen = len(b) nik = 0 pol = 0 if alen == blen: rnd = alen else: rnd = alen*blen numofrounds = 0 for i in range(n): #print(i,rnd) if i == rnd: numofrounds = n//rnd # print(numofrounds) nik *= numofrounds pol *= numofrounds break #print(a[ai%alen], b[bi%blen]) if a[ai] == b[bi]: pass elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S' and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'): pol += 1 else: nik += 1 ai = (ai+1)%alen bi = (bi+1)%blen if n%rnd != 0 and numofrounds != 0: n -= rnd*numofrounds ai = 0 bi = 0 for i in range(n): if a[ai] == b[bi]: pass elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S' and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'): pol += 1 else: nik += 1 ai = (ai+1)%alen bi = (bi+1)%blen print(nik, pol)
1333724400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2 2\n1 3", "3 3\n3 4 7"]
f1121338e84c757d1165d1d645bb26ed
NoteThere are two simple cycles in the first example: $$$1 \rightarrow 5 \rightarrow 2 \rightarrow 1$$$ and $$$2 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 2$$$. One traffic controller can only reverse the road $$$2 \rightarrow 1$$$ and he can't destroy the second cycle by himself. Two traffic controllers can reverse roads $$$2 \rightarrow 1$$$ and $$$2 \rightarrow 3$$$ which would satisfy the condition.In the second example one traffic controller can't destroy the cycle $$$ 1 \rightarrow 3 \rightarrow 2 \rightarrow 1 $$$. With the help of three controllers we can, for example, reverse roads $$$1 \rightarrow 3$$$ ,$$$ 2 \rightarrow 4$$$, $$$1 \rightarrow 5$$$.
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip. Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.
In the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads $$$k$$$ which should be reversed. $$$k$$$ should not be minimized. In the next line output $$$k$$$ integers separated by spaces β€” numbers of roads, the directions of which should be reversed. The roads are numerated from $$$1$$$ in the order they are written in the input. If there are many solutions, print any of them.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 100\,000$$$)Β β€” the number of crossroads and the number of roads in the city, respectively. Each of the following $$$m$$$ lines contain three integers $$$u_{i}$$$, $$$v_{i}$$$ and $$$c_{i}$$$ ($$$1 \leq u_{i}, v_{i} \leq n$$$, $$$1 \leq c_{i} \leq 10^9$$$, $$$u_{i} \ne v_{i}$$$)Β β€” the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.
standard output
standard input
PyPy 2
Python
2,200
train_011.jsonl
9235da61381a1a77c30b68120ea2f0db
256 megabytes
["5 6\n2 1 1\n5 2 6\n2 3 2\n3 4 3\n4 5 5\n1 5 4", "5 7\n2 1 5\n3 2 3\n1 3 3\n2 4 1\n4 3 5\n5 4 1\n1 5 3"]
PASSED
import sys import random, math from collections import defaultdict #n=int(raw_input()) #arr = [int(_) for _ in raw_input().split()] #a = [int(_) for _ in raw_input().split()] N,M = [int(_) for _ in raw_input().split()] table=[] for i in range(M): s,t,c=[int(_) for _ in raw_input().split()] s,t=s-1,t-1 table.append((s,t,c)) def check(k): Lin=[0]*N edge=[[] for i in range(N)] for s,t,c in table: if c>k: Lin[t]+=1 edge[s].append(t) Haco=list() ans=[] for i in range(N): if Lin[i]==0: ans.append(i) Haco.append(i) while Haco: x = Haco.pop() for y in edge[x]: Lin[y]-=1 if Lin[y]==0: ans.append(y) Haco.append(y) return ans ma=10**9+7 mi=-1 while ma-mi>1: mid=(ma+mi)//2 if len(check(mid))==N: ma=mid else: mi=mid ans=check(ma) dd={} for i in ans: dd[ans[i]]=i num=0 answer=[] for i in range(M): s, t, c=table[i] if dd[s]>dd[t] and c<=ma: answer.append(i+1) num+=1 print('{} {}'.format(str(ma),str(num))) print(' '.join(map(str,answer)))
1547390100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["6\n3\n5\n4\n15\n10"]
819aebac427c2c0f96e58bca60b81e33
NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads "abzyo".
The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): And the following necklaces cannot be assembled from beads sold in the store: The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabetΒ β€” each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.
Output $$$t$$$ answers to the test cases. Each answer is a positive integerΒ β€” the maximum length of the $$$k$$$-beautiful necklace you can assemble.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English lettersΒ β€” the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.
standard output
standard input
Python 3
Python
1,900
train_009.jsonl
9bd5ec1239b41d2b14aaf4ca36aeb98a
256 megabytes
["6\n6 3\nabcbac\n3 6\naaa\n7 1000\nabczgyo\n5 4\nababa\n20 10\naaebdbabdbbddaadaadc\n20 5\necbedececacbcbccbdec"]
PASSED
import math import collections t = int(input()) for _ in range(t): n,k = map(int, input().split()) s = input() ctr = collections.Counter(s) ans = 0 for i in range(1,n+1): g = math.gcd(i, k) l = i // g cnt = sum([(v//l)*l for v in ctr.values()]) if cnt >= i: ans = i print(ans)
1592318100
[ "number theory", "graphs" ]
[ 0, 0, 1, 0, 1, 0, 0, 0 ]
1 second
["3", "2"]
a548737890b4bf322d0f8989e5cd25ac
NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
Print the number of operations needed to destroy all towers.
The first line contains single integer n (1 ≀ n ≀ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≀ hi ≀ 109) β€” sizes of towers.
standard output
standard input
Python 2
Python
1,600
train_007.jsonl
72b7f3ac2843bef89f104f31d346b51f
256 megabytes
["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"]
PASSED
N = raw_input() N = int(N) h = raw_input().split(' ') for i in range(len(h)): h[i] = int(h[i]) k = [0]*N for i in range(len(h)): if i != 0 and i != N-1: k[i] = min(k[i-1] + 1, h[i]) else: k[i] = 1 for i in range(len(h)): if i != 0 and i != N-1: k[N - i - 1] = min(k[N-i] + 1, k[N - i - 1]) else: k[i] = 1 print(max(k))
1440865800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3", "2"]
89c27a5c76f4ddbd14af2d30ac8b6330
null
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cuΒ :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.
Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.
The first line contains two space-separated integers n, m (1 ≀ n, m ≀ 105) β€” the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≀ ci ≀ 105) β€” the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) β€” the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges.
standard output
standard input
PyPy 2
Python
1,600
train_005.jsonl
4894047dbffb65f6bd1c8b2f40e557cd
256 megabytes
["6 6\n1 1 2 3 5 8\n1 2\n3 2\n1 4\n4 3\n4 5\n4 6", "5 6\n4 2 5 2 4\n1 2\n2 3\n3 1\n5 3\n5 4\n3 4"]
PASSED
n,m=map(int,raw_input().split()) c=map(int,raw_input().split()) adj=[[] for i in xrange(n+1)] for i in xrange(m): u,v=map(int,raw_input().split()) adj[u].append(v) adj[v].append(u) ans=111111111111111111111111111111111111111111111111111111111111111110 color=[set() for i in xrange(100010)] count=-1 vis=set() for i in xrange(1,n+1): vis.add(c[i-1]) for j in adj[i]: if c[j-1] == c[i-1]: continue else: color[c[i-1]].add(c[j-1]) #print i,c[i-1],len(cc) #print cc vis=list(vis) vis=sorted(vis) for i in vis: if len(color[i]) > count: count=len(color[i]) ans=i print ans
1353511800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
4 seconds
["2\n1\n5\n3\n1"]
f260d0885319a146904b43f89e253f0c
null
You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times: choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$; remove the edge $$$(v, u)$$$; add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?
For each testcase, print a single integerΒ β€” the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.
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 $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$)Β β€” the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i &lt; i$$$)Β β€” the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,900
train_109.jsonl
5c9aa84b9f75bae04351012635ff0310
256 megabytes
["5\n\n5 1\n\n1 1 2 2\n\n5 2\n\n1 1 2 2\n\n6 0\n\n1 2 3 4 5\n\n6 1\n\n1 2 3 4 5\n\n4 3\n\n1 1 1"]
PASSED
for _ in range(int(input())): n,k=map(int,input().split()) arr=[-1,0]+[int(i) for i in input().split()] l,r=1,n-1 while l<r: mid=(l+r)//2 tot=0 h=[0]*(n+1) for i in range(n,1,-1): if h[i]==mid-1 and arr[i]!=1: tot+=1 else: h[arr[i]]=max(h[arr[i]],h[i]+1) if tot<=k: r=mid else: l=mid+1 print(l)
1664462100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3 seconds
["1\n3\n1", "1", "547558588\n277147129\n457421435\n702277623"]
0afd29ef1b720d2baad2f1c91a583933
NoteIn the first example: The first query is only the empty path β€” length $$$0$$$; The second query are paths $$$[(12, 4), (4, 2), (2, 1)]$$$ (length $$$3+1+1=5$$$), $$$[(12, 6), (6, 2), (2, 1)]$$$ (length $$$2+2+1=5$$$) and $$$[(12, 6), (6, 3), (3, 1)]$$$ (length $$$2+2+1=5$$$). The third query is only the path $$$[(3, 1), (1, 2), (2, 4)]$$$ (length $$$1+1+1=3$$$).
You are given a positive integer $$$D$$$. Let's build the following graph from it: each vertex is a divisor of $$$D$$$ (not necessarily prime, $$$1$$$ and $$$D$$$ itself are also included); two vertices $$$x$$$ and $$$y$$$ ($$$x &gt; y$$$) have an undirected edge between them if $$$x$$$ is divisible by $$$y$$$ and $$$\frac x y$$$ is a prime; the weight of an edge is the number of divisors of $$$x$$$ that are not divisors of $$$y$$$. For example, here is the graph for $$$D=12$$$: Edge $$$(4,12)$$$ has weight $$$3$$$ because $$$12$$$ has divisors $$$[1,2,3,4,6,12]$$$ and $$$4$$$ has divisors $$$[1,2,4]$$$. Thus, there are $$$3$$$ divisors of $$$12$$$ that are not divisors of $$$4$$$ β€” $$$[3,6,12]$$$.There is no edge between $$$3$$$ and $$$2$$$ because $$$3$$$ is not divisible by $$$2$$$. There is no edge between $$$12$$$ and $$$3$$$ because $$$\frac{12}{3}=4$$$ is not a prime.Let the length of the path between some vertices $$$v$$$ and $$$u$$$ in the graph be the total weight of edges on it. For example, path $$$[(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)]$$$ has length $$$1+2+2+3+1+2=11$$$. The empty path has length $$$0$$$.So the shortest path between two vertices $$$v$$$ and $$$u$$$ is the path that has the minimal possible length.Two paths $$$a$$$ and $$$b$$$ are different if there is either a different number of edges in them or there is a position $$$i$$$ such that $$$a_i$$$ and $$$b_i$$$ are different edges.You are given $$$q$$$ queries of the following form: $$$v$$$ $$$u$$$ β€” calculate the number of the shortest paths between vertices $$$v$$$ and $$$u$$$. The answer for each query might be large so print it modulo $$$998244353$$$.
Print $$$q$$$ integers β€” for each query output the number of the shortest paths between the two given vertices modulo $$$998244353$$$.
The first line contains a single integer $$$D$$$ ($$$1 \le D \le 10^{15}$$$) β€” the number the graph is built from. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) β€” the number of queries. Each of the next $$$q$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le D$$$). It is guaranteed that $$$D$$$ is divisible by both $$$v$$$ and $$$u$$$ (both $$$v$$$ and $$$u$$$ are divisors of $$$D$$$).
standard output
standard input
PyPy 2
Python
2,200
train_056.jsonl
12061450f6c37e564559281f95b37b1c
256 megabytes
["12\n3\n4 4\n12 1\n3 4", "1\n1\n1 1", "288807105787200\n4\n46 482955026400\n12556830686400 897\n414 12556830686400\n4443186242880 325"]
PASSED
import sys, __pypy__ range = xrange input = raw_input MOD = 998244353 mulmod = __pypy__.intop.int_mulmod inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 D = inp[ii]; ii += 1 q = inp[ii]; ii += 1 U = inp[ii + 0: ii + 2 * q: 2] V = inp[ii + 1: ii + 2 * q: 2] Pdiv = [] if D & 1 == 0: Pdiv.append(2) while D & 1 == 0: D >>= 1 i = 3 while i * i <= D: if D % i == 0: while D % i == 0: D //= i Pdiv.append(i) i += 2 if D > 1: Pdiv.append(D) fac = [1] for i in range(1,200): fac.append(mulmod(fac[-1], i, MOD)) ifac = [pow(f, MOD-2, MOD) for f in fac] def multi(A): prod = fac[sum(A)] for a in A: prod = mulmod(prod, ifac[a], MOD) return prod out = [] for _ in range(q): u = U[_] v = V[_] if u > v: v,u = u,v add = [] rem = [] for p in Pdiv: cu = 0 while u % p == 0: u //= p cu += 1 cv = 0 while v % p == 0: v //= p cv += 1 if cu > cv: rem.append(cu - cv) elif cu < cv: add.append(cv - cu) out.append(mulmod(multi(add), multi(rem), MOD)) print '\n'.join(str(x) for x in out)
1586529300
[ "number theory", "math", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 0 ]
1 second
["4\n10\n420\n9969128"]
a24aac9152417527d43b9b422e3d2303
NoteIn the first test case, $$$4 \bmod 4 = 8 \bmod 4 = 0$$$.In the second test case, $$$10 \bmod 4 = 2 \bmod 10 = 2$$$.In the third test case, $$$420 \bmod 420 = 420 \bmod 420 = 0$$$.
YouKn0wWho has two even integers $$$x$$$ and $$$y$$$. Help him to find an integer $$$n$$$ such that $$$1 \le n \le 2 \cdot 10^{18}$$$ and $$$n \bmod x = y \bmod n$$$. Here, $$$a \bmod b$$$ denotes the remainder of $$$a$$$ after division by $$$b$$$. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.
For each test case, print a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^{18}$$$) that satisfies the condition mentioned in the statement. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) Β β€” the number of test cases. The first and only line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$2 \le x, y \le 10^9$$$, both are even).
standard output
standard input
PyPy 3-64
Python
1,600
train_083.jsonl
cbf2879d49a74d458942c14af7d8f3e7
256 megabytes
["4\n4 8\n4 2\n420 420\n69420 42068"]
PASSED
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict,deque from math import ceil,floor,sqrt,log2,gcd,pi from heapq import heappush,heappop from bisect import bisect_left,bisect from functools import reduce from copy import deepcopy from itertools import permutations # from itertools import zip import sys abc='abcdefghijklmnopqrstuvwxyz' ABC="ABCDEFGHIJKLMNOPQRSTUVWXYZ" for _ in range(int(input())): a,b=map(int,input().split()) if a>b: print(a+b) else: print(b-((b%a)//2))
1635604500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["11\n10\n14\n13"]
add040eecd8322630fbbce0a2a1de45e
NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer Β β€” maximum among integers , , , and .
Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: "+ x"Β β€” add integer x to multiset A. "- x"Β β€” erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x"Β β€” you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.
For each query of the type '?' print one integerΒ β€” the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.
The first line of the input contains a single integer q (1 ≀ q ≀ 200 000)Β β€” the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≀ xi ≀ 109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.
standard output
standard input
PyPy 3
Python
1,800
train_008.jsonl
d489a1b855cc03857894602daa8d2ff0
256 megabytes
["10\n+ 8\n+ 9\n+ 11\n+ 6\n+ 1\n? 3\n- 8\n? 3\n? 8\n? 11"]
PASSED
# Why do we fall ? So we can learn to pick ourselves up. class Node: def __init__(self): self.left = None self.right = None self.cnt = 0 class Trie: def __init__(self): self.root = Node() def insert(self,x): self.temp = self.root for i in range(31,-1,-1): curbit = (x>>i)&1 if curbit: if not self.temp.right: self.temp.right = Node() self.temp = self.temp.right self.temp.cnt += 1 else: if not self.temp.left: self.temp.left = Node() self.temp = self.temp.left self.temp.cnt += 1 def remove(self,x): self.temp = self.root for i in range(31,-1,-1): curbit = (x>>i)&1 if curbit: self.temp = self.temp.right self.temp.cnt -= 1 else: self.temp = self.temp.left self.temp.cnt -= 1 def maxxor(self,x): self.temp = self.root self.ss = 0 for i in range(31,-1,-1): curbit = (x>>i)&1 if curbit: if self.temp.left and self.temp.left.cnt: self.ss += (1<<i) self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.cnt: self.ss += (1<<i) self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left return self.ss q = int(input()) trie = Trie() trie.insert(0) for _ in range(0,q): qq = input().split() if qq[0] == '+': trie.insert(int(qq[1])) elif qq[0] == '-': trie.remove(int(qq[1])) else: print(trie.maxxor(int(qq[1]))) """ 10 + 8 + 9 + 11 + 6 + 1 ? 3 - 8 ? 3 ? 8 ? 11 10 ? 1 + 1 + 8 - 1 + 2 + 7 + 4 + 7 + 3 ? 7 """
1470933300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["6\n1 3 2", "-1", "9\n1 3 2 1 3"]
644f1469a9a9dcdb94144062ba616c59
NoteAll vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $$$1$$$, the second vertex β€” into color $$$3$$$, and the third vertex β€” into color $$$2$$$. The cost of this painting is $$$3 + 2 + 1 = 6$$$.
You are given a tree consisting of $$$n$$$ vertices. A tree is an undirected connected acyclic graph. Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $$$(x, y, z)$$$ such that $$$x \neq y, y \neq z, x \neq z$$$, $$$x$$$ is connected by an edge with $$$y$$$, and $$$y$$$ is connected by an edge with $$$z$$$. The colours of $$$x$$$, $$$y$$$ and $$$z$$$ should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
If there is no good painting, print $$$-1$$$. Otherwise, print the minimum cost of a good painting in the first line. In the second line print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 3)$$$, where the $$$i$$$-th integer should denote the color of the $$$i$$$-th vertex. If there are multiple good paintings with minimum cost, print any of them.
The first line contains one integer $$$n$$$ $$$(3 \le n \le 100\,000)$$$ β€” the number of vertices. The second line contains a sequence of integers $$$c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$$$ $$$(1 \le c_{1, i} \le 10^{9})$$$, where $$$c_{1, i}$$$ is the cost of painting the $$$i$$$-th vertex into the first color. The third line contains a sequence of integers $$$c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$$$ $$$(1 \le c_{2, i} \le 10^{9})$$$, where $$$c_{2, i}$$$ is the cost of painting the $$$i$$$-th vertex into the second color. The fourth line contains a sequence of integers $$$c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$$$ $$$(1 \le c_{3, i} \le 10^{9})$$$, where $$$c_{3, i}$$$ is the cost of painting the $$$i$$$-th vertex into the third color. Then $$$(n - 1)$$$ lines follow, each containing two integers $$$u_j$$$ and $$$v_j$$$ $$$(1 \le u_j, v_j \le n, u_j \neq v_j)$$$ β€” the numbers of vertices connected by the $$$j$$$-th undirected edge. It is guaranteed that these edges denote a tree.
standard output
standard input
Python 3
Python
1,800
train_009.jsonl
bc63fee3ecd6696c16bd08868c23f52f
256 megabytes
["3\n3 2 3\n4 3 2\n3 1 3\n1 2\n2 3", "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 3", "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 4"]
PASSED
from collections import defaultdict, deque from itertools import permutations class Graph: def __init__(self): self.E = {} self.V = defaultdict(list) def put(self, v1, v2): if v1 not in self.E: self.E[v1] = 1 if v2 not in self.E: self.E[v2] = 1 self.V[v1].append(v2) self.V[v2].append(v1) def _adj(self, v1): return self.V[v1] def bfs(self, v): visited = set([v]) path = [v] q = deque([v]) while q: v1 = q.pop() for v2 in self._adj(v1): if v2 not in visited: visited.add(v2) path.append(v2) q.appendleft(v2) return path if __name__ == '__main__': n = int(input()) cp = [] for _ in range(3): cp.append(list(map(int, input().split(' ')))) inv = False vert = defaultdict(int) graph = Graph() for _ in range(n - 1): v1, v2 = map(int, input().split(' ')) vert[v1] += 1 if vert[v1] > 2: inv = True break vert[v2] += 1 if vert[v2] > 2: inv = True break graph.put(v1, v2) if inv: print(-1) else: for key in vert: if vert[key] == 1: start = key break path = graph.bfs(start) min_cost = float('inf') min_cost_perm = (0, 1, 2) for p in permutations([0, 1, 2]): cur_cost = 0 for i, v in enumerate(path): cur_cost += cp[p[i % 3]][v - 1] if cur_cost < min_cost: min_cost_perm = p min_cost = cur_cost # print(path, graph.V) ans = [0]*n for i, v in enumerate(path): ans[v - 1] = min_cost_perm[i % 3] + 1 print(min_cost) print(' '.join(map(str, ans)))
1570957500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["7\n20"]
996b7f2afdf868dd04b40888008241c8
NoteIn the first example, Polycarp can get score of $$$7$$$ as follows: Firstly he trains for $$$4$$$ minutes, increasing $$$s$$$ to the value of $$$5$$$; Then he decides to solve $$$4$$$-th problem: he watches one episode in $$$10$$$ minutes, his skill level decreases to $$$s=5*0.9=4.5$$$ and then he solves the problem in $$$5/s=5/4.5$$$, which is roughly $$$1.111$$$ minutes; Finally, he decides to solve $$$2$$$-nd problem: he watches one episode in $$$10$$$ minutes, his skill level decreases to $$$s=4.5*0.9=4.05$$$ and then he solves the problem in $$$20/s=20/4.05$$$, which is roughly $$$4.938$$$ minutes. This way, Polycarp uses roughly $$$4+10+1.111+10+4.938=30.049$$$ minutes, to get score of $$$7$$$ points. It is not possible to achieve larger score in $$$31$$$ minutes.In the second example, Polycarp can get $$$20$$$ points as follows: Firstly he trains for $$$4$$$ minutes, increasing $$$s$$$ to the value of $$$5$$$; Then he decides to solve $$$1$$$-st problem: he watches one episode in $$$10$$$ minutes, his skill decreases to $$$s=5*0.9=4.5$$$ and then he solves problem in $$$1/s=1/4.5$$$, which is roughly $$$0.222$$$ minutes. Finally, he decides to solve $$$2$$$-nd problem: he watches one episode in $$$10$$$ minutes, his skill decreases to $$$s=4.5*0.9=4.05$$$ and then he solves the problem in $$$10/s=10/4.05$$$, which is roughly $$$2.469$$$ minutes. This way, Polycarp gets score of $$$20$$$ in $$$4+10+0.222+10+2.469=26.691$$$ minutes. It is not possible to achieve larger score in $$$30$$$ minutes.
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $$$n$$$ problems and lasts for $$$T$$$ minutes. Each of the problems is defined by two positive integers $$$a_i$$$ and $$$p_i$$$Β β€” its difficulty and the score awarded by its solution.Polycarp's experience suggests that his skill level is defined with positive real value $$$s$$$, and initially $$$s=1.0$$$. To solve the $$$i$$$-th problem Polycarp needs $$$a_i/s$$$ minutes.Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by $$$10\%$$$, that is skill level $$$s$$$ decreases to $$$0.9s$$$. Each episode takes exactly $$$10$$$ minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for $$$a_i/s$$$ minutes, where $$$s$$$ is his current skill level. In calculation of $$$a_i/s$$$ no rounding is performed, only division of integer value $$$a_i$$$ by real value $$$s$$$ happens.Also, Polycarp can train for some time. If he trains for $$$t$$$ minutes, he increases his skill by $$$C \cdot t$$$, where $$$C$$$ is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed before solving the first problem.
Print $$$tc$$$ integersΒ β€” the maximum possible score in each test case.
The first line contains one integer $$$tc$$$ ($$$1 \le tc \le 20$$$)Β β€” the number of test cases. Then $$$tc$$$ test cases follow. The first line of each test contains one integer $$$n$$$ ($$$1 \le n \le 100$$$)Β β€” the number of problems in the contest. The second line of the test contains two real values $$$C, T$$$ ($$$0 &lt; C &lt; 10$$$, $$$0 \le T \le 2 \cdot 10^5$$$), where $$$C$$$ defines the efficiency of the training and $$$T$$$ is the duration of the contest in minutes. Value $$$C, T$$$ are given exactly with three digits after the decimal point. Each of the next $$$n$$$ lines of the test contain characteristics of the corresponding problem: two integers $$$a_i, p_i$$$ ($$$1 \le a_i \le 10^4$$$, $$$1 \le p_i \le 10$$$)Β β€” the difficulty and the score of the problem. It is guaranteed that the value of $$$T$$$ is such that changing it by the $$$0.001$$$ in any direction will not change the test answer. Please note that in hacks you can only use $$$tc = 1$$$.
standard output
standard input
PyPy 3
Python
2,500
train_054.jsonl
c3f27ca0911a958189e297b39edd9117
256 megabytes
["2\n4\n1.000 31.000\n12 3\n20 6\n30 1\n5 1\n3\n1.000 30.000\n1 10\n10 10\n20 8"]
PASSED
from math import sqrt class pro(object): def __init__(self,dif,sc): self.dif=dif self.sc=sc def __lt__(self,other): return self.dif>other.dif T=int(input()) mul=[1] for i in range(100): mul.append(mul[i]*10/9) inf=1000000007 for t in range(T): n=int(input()) effi,tim=map(float,input().split()) prob=[] for i in range(n): x,y=map(int,input().split()) prob.append(pro(x,y)) prob.sort() f=[[inf for i in range(n+1)] for j in range(1001)] f[0][0]=0 totsc=0 for i in range(n): totsc+=prob[i].sc for j in range(totsc,prob[i].sc-1,-1): for k in range(1,i+2): f[j][k]=min(f[j][k],f[j-prob[i].sc][k-1]+prob[i].dif*mul[k]) for i in range(totsc,-1,-1): flag=False for j in range(n+1): if sqrt(effi*f[i][j])>=1: res=2*sqrt(f[i][j]/effi)-1/effi+10*j else: res=f[i][j]+10*j if res<=tim: print(i) flag=True break if flag==True: break
1543163700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
afb43928545743b497b1a9975768f8e5
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ β€” a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$T$$$ lines contain test cases β€” one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) β€” the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,800
train_002.jsonl
85ba21ba1cf20679f6b2fa61b85b452e
256 megabytes
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
PASSED
def solve(): n, l, r = [int(i) for i in input().split()] seq = [] i = 1 while l <= r: while l > 2 * n - 2: if l == 3: i = 1 break l -= 2 * n - 2 r -= 2 * n - 2 n -= 1 i += 1 if l%2 == 0: seq.append(l // 2 + i) else: seq.append(i) l += 1 return " ".join(str(i) for i in seq) T = int(input()) for _ in range(T): print(solve())
1586529300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO\nYES\nNO\nNO"]
6fbf41dc32d1c28351d78a9ec5fc0026
NoteIn the first test case, one possible solution is $$$a_1=qw$$$ and $$$a_2=q$$$.In the third test case, one possible solution is $$$a_1=i$$$ and $$$a_2=o$$$.In the fifth test case, one possible solution is $$$a_1=dokidokiliteratureclub$$$.
Kawashiro Nitori is a girl who loves competitive programming.One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.Given a string $$$s$$$ and a parameter $$$k$$$, you need to check if there exist $$$k+1$$$ non-empty strings $$$a_1,a_2...,a_{k+1}$$$, such that $$$$$$s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}).$$$$$$ Here $$$+$$$ represents concatenation. We define $$$R(x)$$$ as a reversed string $$$x$$$. For example $$$R(abcd) = dcba$$$. Note that in the formula above the part $$$R(a_{k+1})$$$ is intentionally skipped.
For each test case, print "YES" (without quotes), if it is possible to find $$$a_1,a_2,\ldots,a_{k+1}$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$) Β β€” the number of test cases. The description of the test cases follows. The first line of each test case description contains two integers $$$n$$$, $$$k$$$ ($$$1\le n\le 100$$$, $$$0\le k\le \lfloor \frac{n}{2} \rfloor$$$) Β β€” the length of the string $$$s$$$ and the parameter $$$k$$$. The second line of each test case description contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.
standard output
standard input
Python 3
Python
900
train_104.jsonl
e4cb3baf5bbc56a627985e73b5d1c1e1
256 megabytes
["7\n5 1\nqwqwq\n2 1\nab\n3 1\nioi\n4 2\nicpc\n22 0\ndokidokiliteratureclub\n19 8\nimteamshanghaialice\n6 3\naaaaaa"]
PASSED
ans_list = [] for i in range(int(input())): n, k = map(int, input().split()) strings = input() skip = False if(n == 2 * k): ans_list.append("NO") continue for i in range(k): if(strings[i] == strings[n - 1 - i]): pass else: ans_list.append("NO") skip = True break if(skip == False): ans_list.append("YES") for ans in ans_list: print(ans)
1615377900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1", "0"]
cb4dbff31d967c3dab8fe0495eb871dc
null
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
The first line of input contains a single integer n (1 ≀ n ≀ 100) β€” the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≀ xi, yi ≀ 1000) β€” the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
standard output
standard input
Python 3
Python
1,200
train_004.jsonl
ed64ae5b7587331da7cbaff06c56186c
256 megabytes
["2\n2 1\n1 2", "2\n2 1\n4 1"]
PASSED
n = int(input()) coodenadas = [] for i in range(n): x, y = [ int(i) for i in input().split() ] coodenadas.append({ 'x': { x }, 'y': { y } }) for i in range(n-1, -1, -1): j = i - 1 while j >= 0 and i < len(coodenadas): if len(coodenadas[j]['x'].intersection(coodenadas[i]['x'])) or len(coodenadas[j]['y'].intersection(coodenadas[i]['y'])): coodenadas[i]['x'].update(coodenadas[j]['x']) coodenadas[i]['y'].update(coodenadas[j]['y']) coodenadas.pop(j) j -= 1 print(len(coodenadas) - 1)
1345273500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1 2\n2 1\n1 2"]
49a78893ea2849aa59647846b4eaba7c
null
Note that girls in Arpa’s land are really attractive.Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair. There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: Each person had exactly one type of food, No boy had the same type of food as his girlfriend, Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
If there is no solution, print -1. Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2. If there are multiple solutions, print any of them.
The first line contains an integer n (1  ≀  n  ≀  105)Β β€” the number of pairs of guests. The i-th of the next n lines contains a pair of integers ai and bi (1  ≀ ai, bi ≀  2n)Β β€” the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
standard output
standard input
Python 2
Python
2,600
train_018.jsonl
c5022f2cbc3af8dfbc8a7267a7cf5d05
256 megabytes
["3\n1 4\n2 5\n3 6"]
PASSED
n=int(raw_input()) g=[[]for i in range(n+n)] c=[-1 for i in range(n+n)] e=[] for i in range(n): u,v=map(int,raw_input().split()) u-=1 v-=1 e.append([u,v]) g[u].append(v) g[v].append(u) for i in range(n): g[2*i].append(2*i+1) g[2*i+1].append(2*i) q=[-1 for i in range(2*n)] for i in range(2*n): if c[i]!=-1:continue h,t=0,1 q[0]=i c[i]=0 while h<t: u=q[h] h+=1 for v in g[u]: if c[v]==-1: c[v]=c[u]^1 q[t]=v t+=1 for x in e: print "{0} {1}".format(c[x[0]]+1,c[x[1]]+1)
1481034900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["3.000000000000000\n3.666666666666667\n2.047619047619048\n329737645.750000000000000\n53.700000000000000"]
700cfc8d20794ca38d73ccff31e5292c
NoteIn the first test case cars will meet in the coordinate $$$5$$$.The first car will be in the coordinate $$$1$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.The second car will be in the coordinate $$$9$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.In the second test case after $$$1$$$ second the first car will be in the coordinate $$$1$$$ and will have the speed equal to $$$2$$$ meters per second, the second car will be in the coordinate $$$9$$$ and will have the speed equal to $$$1$$$ meter per second. So, they will meet after $$$\frac{9-1}{2+1} = \frac{8}{3}$$$ seconds. So, the answer is equal to $$$1 + \frac{8}{3} = \frac{11}{3}$$$.
There is a road with length $$$l$$$ meters. The start of the road has coordinate $$$0$$$, the end of the road has coordinate $$$l$$$.There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.Initially, they will drive with a speed of $$$1$$$ meter per second. There are $$$n$$$ flags at different coordinates $$$a_1, a_2, \ldots, a_n$$$. Each time when any of two cars drives through a flag, the speed of that car increases by $$$1$$$ meter per second.Find how long will it take for cars to meet (to reach the same coordinate).
For each test case print a single real number: the time required for cars to meet. Your answer will be considered correct, if its absolute or relative error does not exceed $$$10^{-6}$$$. More formally, if your answer is $$$a$$$ and jury's answer is $$$b$$$, your answer will be considered correct if $$$\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$$$.
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$l$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l \leq 10^9$$$): the number of flags and the length of the road. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in the increasing order ($$$1 \leq a_1 &lt; a_2 &lt; \ldots &lt; a_n &lt; l$$$). It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,500
train_035.jsonl
7c288c41453450f015d064cd8289f43b
256 megabytes
["5\n2 10\n1 9\n1 10\n1\n5 7\n1 2 3 4 6\n2 1000000000\n413470354 982876160\n9 478\n1 10 25 33 239 445 453 468 477"]
PASSED
for __ in range(int(input())): n,l=map(int,input().split()) a=list(map(int,input().split())) a.insert(0,0) a.append(l) i,j,va,vb,pra,prb,ta,tb=1,n,1,1,0,l,0,0 res,t=0,0 while True: if abs(j-i)==0: res=1 tempa=(a[i]-pra)/va tempb=(prb-a[j])/vb ta+=tempa tb+=tempb if ta<tb: tb-=tempb va+=1 pra=a[i] i+=1 elif ta>tb: ta-=tempa vb+=1 prb=a[j] j-=1 else: va+=1 vb+=1 pra=a[i] prb=a[j] i+=1 j-=1 if i>j: res=1 if res: if ta>tb: prb-=(ta-tb)*vb print(ta+(abs(pra-prb)/(va+vb))) elif ta==tb: print(ta+(abs(pra-prb)/(va+vb))) else: pra+=(tb-ta)*va print(tb+(abs(pra-prb)/(va+vb))) break
1601476500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5", "47", "62"]
04f75aa0ae4a015b87ac8521cd1d34fc
NoteIn the first example, the chandeliers will have different colors at days $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. That's why the answer is $$$5$$$.
Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistakeΒ β€” they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some daysΒ β€” different. Of course, it looks poor and only annoys Vasya. As a result, at the $$$k$$$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.
Print the single integerΒ β€” the index of day when Vasya will become angry.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$)Β β€” the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya. The second line contains $$$n$$$ different integers $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$) that describe the first chandelier's sequence of colors. The third line contains $$$m$$$ different integers $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$) that describe the second chandelier's sequence of colors. At the $$$i$$$-th day, the first chandelier has a color $$$a_x$$$, where $$$x = ((i - 1) \mod n) + 1)$$$ and the second one has a color $$$b_y$$$, where $$$y = ((i - 1) \mod m) + 1)$$$. It's guaranteed that sequence $$$a$$$ differs from sequence $$$b$$$, so there are will be days when colors of chandeliers differs.
standard output
standard input
Python 3
Python
2,200
train_095.jsonl
e11402d340c85be30e177cd0869d8ab6
256 megabytes
["4 2 4\n4 2 3 1\n2 1", "3 8 41\n1 3 2\n1 6 4 3 5 7 2 8", "1 2 31\n1\n1 2"]
PASSED
def mcd(a,b): if a==0: return(b) if b==0: return(a) return mcd(b,a%b) def solve(n,m,k,a,b): d = mcd(n,m) mcm = n*m//d [x,y] = BuscarIndices(n,m,d) collection = {} matchings = [] for i in range(n): collection[a[i]] = i for j in range(m): if b[j] in collection and (collection[b[j]] - j) % d == 0: if m == 1: matchings += [collection[b[j]]] else: matchings+=[DevuelvePos(collection[b[j]],j,n,m,d,mcm,x,y)] matchings.sort() diasSinProcesar = k cantidadFinalDias = 0 if k > mcm - len(matchings): cantidadFinalDias = ((k-1)//(mcm - len(matchings))) * mcm diasSinProcesar = (k-1)%(mcm - len(matchings)) + 1 posicion_inicial = 0 start,end = 0,len(matchings)-1 while start<=end: med = (start+end)//2 dias_rep = med - start total_dias_intervalo = matchings[med] - posicion_inicial dias_noRep = total_dias_intervalo - dias_rep if dias_noRep >= diasSinProcesar: end = med - 1 else: cantidadFinalDias += total_dias_intervalo + 1 diasSinProcesar -= dias_noRep posicion_inicial = matchings[med] + 1 start = med + 1 cantidadFinalDias += diasSinProcesar return cantidadFinalDias def DevuelvePos(i,j,n,m,d,mcm,x,y): return ((i+j + (j-i)*(x*n + y*m)//d)//2)%mcm def BuscarIndices(n,m,d): x,y=0,0 for i in range(1, m): if (i * n - d) % m == 0: x = i y = (i * n - d) // m break return [x,y] def main(): [n,m,k] = input().split(" ") n,m,k = int(n), int(m), int(k) a = list(map(int,input().split())) b = list(map(int,input().split())) if n<m: n,m,a,b = m,n,b,a print(solve(n,m,k,a,b)) main()
1615626300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["Yes\nYes\nNo\nNo\nNo\nNo\nYes"]
76b3667cce9e23675e21caf6926f608d
NoteIn the first test case, $$$[1,2,3]$$$ is already sorted in non-descending order.In the second test case, we can choose $$$i = 1,j = 2,k = 3$$$. Since $$$a_1 \le a_3$$$, swap $$$a_2$$$ and $$$a_3$$$, the array then becomes $$$[1,2,3]$$$, which is sorted in non-descending order.In the seventh test case, we can do the following operations successively: Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 \le a_7$$$, swap $$$a_6$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,4,5,3]$$$. Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 &gt; a_7$$$, replace $$$a_5$$$ with $$$a_5+a_6=9$$$, the array then becomes $$$[1,2,6,7,9,5,3]$$$. Choose $$$i = 2,j = 5,k = 7$$$. Since $$$a_2 \le a_7$$$, swap $$$a_5$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,3,5,9]$$$. Choose $$$i = 2,j = 4,k = 6$$$. Since $$$a_2 \le a_6$$$, swap $$$a_4$$$ and $$$a_6$$$, the array then becomes $$$[1,2,6,5,3,7,9]$$$. Choose $$$i = 1,j = 3,k = 5$$$. Since $$$a_1 \le a_5$$$, swap $$$a_3$$$ and $$$a_5$$$, the array then becomes $$$[1,2,3,5,6,7,9]$$$, which is sorted in non-descending order. In the third, the fourth, the fifth and the sixth test cases, it can be shown that the array cannot be sorted in non-descending order.
You are given a permutation $$$a_1, a_2, \ldots, a_n$$$ of size $$$n$$$, where each integer from $$$1$$$ to $$$n$$$ appears exactly once.You can do the following operation any number of times (possibly, zero): Choose any three indices $$$i, j, k$$$ ($$$1 \le i &lt; j &lt; k \le n$$$). If $$$a_i &gt; a_k$$$, replace $$$a_i$$$ with $$$a_i + a_j$$$. Otherwise, swap $$$a_j$$$ and $$$a_k$$$. Determine whether you can make the array $$$a$$$ sorted in non-descending order.
For each test case, output "Yes" (without quotes) if the array can be sorted in non-descending order, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "YES", "yEs" and "yes" will be recognized as a positive response).
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) β€” the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10$$$) β€” the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1 \le a_i \le n$$$, $$$a_i \neq a_j$$$ if $$$i \neq j$$$) β€” the elements of the array $$$a$$$.
standard output
standard input
Python 3
Python
800
train_101.jsonl
ca3636b92d4fcabeec673b443e461109
256 megabytes
["7\n\n3\n\n1 2 3\n\n3\n\n1 3 2\n\n7\n\n5 3 4 7 6 2 1\n\n7\n\n7 6 5 4 3 2 1\n\n5\n\n2 1 4 5 3\n\n5\n\n2 1 3 4 5\n\n7\n\n1 2 6 7 4 3 5"]
PASSED
for i in range(int(input())): n=int(input()) x=list(map(int,input().split())) if x[0]==min(x): print('YES') else: print('NO')
1667745300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "0", "4"]
fd6b73a2c15f5b009fa350eea9bf0c0a
NoteIn the first example Arkady should block at least one hole. After that, $$$\frac{10 \cdot 2}{6} \approx 3.333$$$ liters of water will flow out of the first hole, and that suits Arkady.In the second example even without blocking any hole, $$$\frac{80 \cdot 3}{10} = 24$$$ liters will flow out of the first hole, that is not less than $$$20$$$.In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $$$n$$$ flowers and so it looks like a pipe with $$$n$$$ holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour $$$A$$$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $$$s_1, s_2, \ldots, s_n$$$. In other words, if the sum of sizes of non-blocked holes is $$$S$$$, and the $$$i$$$-th hole is not blocked, $$$\frac{s_i \cdot A}{S}$$$ liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least $$$B$$$ liters of water flow out of the first hole?
Print a single integerΒ β€” the number of holes Arkady should block.
The first line contains three integers $$$n$$$, $$$A$$$, $$$B$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le B \le A \le 10^4$$$)Β β€” the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^4$$$)Β β€” the sizes of the holes.
standard output
standard input
Python 3
Python
1,000
train_024.jsonl
25e036cc498fe7bbc17317a3c7d98d72
256 megabytes
["4 10 3\n2 2 2 2", "4 80 20\n3 2 1 4", "5 10 10\n1000 1 1 1 1"]
PASSED
I = lambda: map(int, input().split()) n, A, B = I() s1, *S = I() if S: S = sorted(S) total = s1 i = 0 while i < n-1 and s1*A >= B*(total+S[i]): total += S[i] i += 1 print(n-i-1) else: print(0)
1525007700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\n1 5\n1 4\n5 3\n4 3\n5 4", "YES\n3 1\n3 2\n5 3\n3 4\n4 5", "NO"]
29a9015981b39df9db40d41c73286e9f
NoteIn the first example, the array $$$b$$$ will change as follows: $$$[0,0,0,0,0] \rightarrow [-1,0,0,1,0] \rightarrow [-2,0,0,1,1] \rightarrow [-2,0,1,0,1] \rightarrow [-2,0,2,0,0] \rightarrow [-2,0,2,1,-1]$$$. $$$a_i = b_i$$$ for all indices $$$i$$$ from $$$1$$$ to $$$5$$$.In the second example, it is enough for us that $$$b_2 = 1$$$ at the end, since only $$$s_2 = 1$$$.In the third example, the operations cannot be performed as required.
Oh no, on the first exam Madoka got this hard problem:Given integer $$$n$$$ and $$$m$$$ pairs of integers ($$$v_i, u_i$$$). Also there is an array $$$b_1, b_2, \ldots, b_n$$$, initially filled with zeros.Then for each index $$$i$$$, where $$$1 \leq i \leq m$$$, perform either $$$b_{v_i} := b_{v_i} - 1$$$ and $$$b_{u_i} := b_{u_i} + 1$$$, or $$$b_{v_i} := b_{v_i} + 1$$$ and $$$b_{u_i} := b_{u_i} - 1$$$. Note that exactly one of these operations should be performed for every $$$i$$$.Also there is an array $$$s$$$ of length $$$n$$$ consisting of $$$0$$$ and $$$1$$$. And there is an array $$$a_1, a_2, \ldots, a_n$$$, where it is guaranteed, that if $$$s_i = 0$$$ holds, then $$$a_i = 0$$$.Help Madoka and determine whenever it is possible to perform operations in such way that for every $$$i$$$, where $$$s_i = 1$$$ it holds that $$$a_i = b_i$$$. If it possible you should also provide Madoka with a way to perform operations.
In the first line print "YES" if it is possible to perform operations in the required way, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer). In case you printed "YES", print $$$m$$$ pairs of integers. If for pair $$$(v_i, u_i)$$$ we should perform $$$b_{v_i} := b_{v_i} - 1$$$ and $$$b_{u_i} := b_{u_i} + 1$$$, print $$$(v_i, u_i)$$$. Otherwise print $$$(u_i, v_i)$$$. If there are multiple ways to get the correct answer, you can print any of them. You can print pairs in any order.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 10000, 1 \leq m \leq 10000$$$) β€” the length of the array $$$a$$$ and the number of pair of integers. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots s_n$$$ ($$$0 \le s_i \le 1$$$) β€” the elements of the array $$$s$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$|a_i| \leq m$$$) β€” the elements of the array $$$a$$$. It is guaranteed that if $$$s_i = 0$$$ holds, then $$$a_i = 0$$$. $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \leq v_i, u_i \leq n, v_i \ne u_i$$$) β€” the indexes of the elements of the array $$$b$$$ to which the operation is performed. It is also guaranteed that there are no two indices $$$i$$$ and $$$j$$$, where $$$1 \le i &lt; j \le m$$$, such that $$$(v_i, u_i) = (v_j, u_j)$$$ or $$$(v_i, u_i) = (u_j, v_j)$$$.
standard output
standard input
PyPy 3-64
Python
2,500
train_104.jsonl
1daf45157599c0131049e21058c209db
256 megabytes
["5 5\n1 1 1 1 1\n-2 0 2 1 -1\n1 5\n1 4\n3 5\n3 4\n4 5", "5 5\n0 1 0 1 0\n0 1 0 0 0\n1 3\n2 3\n3 5\n3 4\n4 5", "4 4\n1 1 1 1\n0 2 -2 2\n1 3\n1 4\n2 3\n2 4"]
PASSED
from collections import deque import sys sys.setrecursionlimit(10**4+10) class mf_graph: n=1 g=[[] for i in range(1)] pos=[] def __init__(self,N): self.n=N self.g=[[] for i in range(N)] self.pos=[] def add_edge(self,From,To,cap): assert 0<=From and From<self.n assert 0<=To and To<self.n assert 0<=cap m=len(self.pos) self.pos.append((From,len(self.g[From]))) self.g[From].append({"to":To,"rev":len(self.g[To]),"cap":cap}) self.g[To].append({"to":From,"rev":len(self.g[From])-1,"cap":0}) return m def get_edge(self,i): m=len(self.pos) assert 0<=i and i<m _e=self.g[self.pos[i][0]][self.pos[i][1]] _re=self.g[_e["to"]][_e["rev"]] return {"from":self.pos[i][0], "to":_e["to"], "cap":_e["cap"]+_re["cap"], "flow":_re["cap"]} def edges(self): m=len(self.pos) result=[] for i in range(m): result.append(self.get_edge(i)) return result def change_edge(self,i,new_cap,new_flow): m=len(self.pos) assert 0<=i and i<m assert 0<=new_flow and new_flow<=new_cap _e=self.g[self.pos[i][0]][self.pos[i][1]] _re=self.g[_e["to"]][_e["rev"]] _e["cap"]=new_cap-new_flow _re["cap"]=new_flow def flow(self,s,t,flow_limit=(1<<63)-1): assert 0<=s and s<self.n assert 0<=t and t<self.n level=[0 for i in range(self.n)] Iter=[0 for i in range(self.n)] que=deque([]) def bfs(): for i in range(self.n):level[i]=-1 level[s]=0 que=deque([]) que.append(s) while(len(que)>0): v=que.popleft() for e in self.g[v]: if e["cap"]==0 or level[e["to"]]>=0:continue level[e["to"]]=level[v]+1 if e["to"]==t:return que.append(e["to"]) def dfs(func,v,up): if (v==s):return up res=0 level_v=level[v] for i in range(Iter[v],len(self.g[v])): e=self.g[v][i] if (level_v<=level[e["to"]] or self.g[e["to"]][e["rev"]]["cap"]==0):continue d=func(func,e["to"],min(up-res,self.g[e["to"]][e["rev"]]["cap"])) if d<=0:continue self.g[v][i]["cap"]+=d self.g[e["to"]][e["rev"]]["cap"]-=d res+=d if res==up:return res level[v]=self.n return res flow=0 while(flow<flow_limit): bfs() if level[t]==-1:break for i in range(self.n):Iter[i]=0 while(flow<flow_limit): f=dfs(dfs,t,flow_limit-flow) if not(f):break flow+=f return flow def min_cut(self,s): visited=[False for i in range(self.n)] que=deque([]) que.append(s) while(len(que)>0): p=que.popleft() visited[p]=True for e in self.g[p]: if e["cap"] and not(visited[e["to"]]): visited[e["to"]]=True que.append(e["to"]) return from sys import stdin input=lambda :stdin.readline()[:-1] n,m=map(int,input().split()) s=list(map(int,input().split())) a=list(map(int,input().split())) g=mf_graph(n+m+2) S=n+m T=S+1 tmp=[0]*n edges=[] edge1=[] edge2=[] for i in range(m): x,y=map(lambda x:int(x)-1,input().split()) tmp[x]+=1 tmp[y]+=1 if s[x]==1 and s[y]==1: edge1.append((x,y,i)) elif s[x]==1 or s[y]==1: edge2.append((x,y,i)) edges.append((x,y)) cnt=0 for i in range(n): if s[i]==1: if a[i]>tmp[i] or (tmp[i]-a[i])%2==1: print('NO') exit() t=(tmp[i]-a[i])//2 if t!=0: g.add_edge(i,T,t) cnt+=t for x,y,i in edge1: g.add_edge(S,n+i,1) g.add_edge(n+i,x,1) g.add_edge(n+i,y,1) ans_flow=g.flow(S,T) for x,y,i in edge2: g.add_edge(S,n+i,1) g.add_edge(n+i,x,1) g.add_edge(n+i,y,1) ans_flow+=g.flow(S,T) if ans_flow!=cnt: print('NO') exit() ans=[-1]*m for e in g.edges(): frm=e['from']-n if 0<=frm<m: to=e['to'] if e['flow']!=0: ans[frm]=to ANS=[] for i in range(m): x,y=edges[i] if ans[i]!=-1: if ans[i]==x: ANS.append((x,y)) else: ANS.append((y,x)) else: if s[x]==0: ANS.append((x,y)) elif s[y]==0: ANS.append((y,x)) else: print('NO') exit() print('YES') for x,y in ANS: print(x+1,y+1)
1662129300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2", "5"]
bc1e2d9dba07b2ac6b0a118bdbdd063b
NoteIn the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.To do this, Amr can do two different kind of operations. Choose some chemical i and double its current volume so the new volume will be 2ai Choose some chemical i and divide its volume by two (integer division) so the new volume will be Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?
Output one integer the minimum number of operations required to make all the chemicals volumes equal.
The first line contains one number n (1 ≀ n ≀ 105), the number of chemicals. The second line contains n space separated integers ai (1 ≀ ai ≀ 105), representing the initial volume of the i-th chemical in liters.
standard output
standard input
Python 3
Python
1,900
train_015.jsonl
18e205aef950064cb982cc96b64c37f2
256 megabytes
["3\n4 8 2", "3\n3 5 6"]
PASSED
n = int(input()) s = list(map(int, input().split())) l = [bin(i)[2:] for i in s] length = [len(i) for i in l] maxLen = max(length) minLen = min(length) loc = 0 flag = False for j in range(minLen): for i in range(n): if l[i][j] != l[0][j]: flag = True break if flag: break loc += 1 result = sum(length) - loc * n best = result change = n*[-1] for j in range(loc, maxLen): for i in range(n): if j >= length[i] or l[i][j] == '1': change[i] = 1 result += sum(change) if result > best: break best = result print(best)
1436886600
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
4 seconds
["10", "12", "8", "2"]
5d0a985a0dced0734aff6bb0cd1b695d
NoteThese are possible progressions for the first test of examples: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10. These are possible progressions for the second test of examples: 6, 7; 6, 8; 6, 9; 7, 6; 7, 8; 7, 9; 8, 6; 8, 7; 8, 9; 9, 6; 9, 7; 9, 8. These are possible progressions for the third test of examples: 1, 2, 4; 1, 3, 9; 2, 4, 8; 4, 2, 1; 4, 6, 9; 8, 4, 2; 9, 3, 1; 9, 6, 4. These are possible progressions for the fourth test of examples: 4, 6, 9; 9, 6, 4.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l ≀ ai ≀ r and ai ≠ aj , where a1, a2, ..., an is the geometrical progression, 1 ≀ i, j ≀ n and i ≠ j.Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is .Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 ≀ i ≀ n) that ai ≠ bi.
Print the integer KΒ β€” is the answer to the problem.
The first and the only line cotains three integers n, l and r (1 ≀ n ≀ 107, 1 ≀ l ≀ r ≀ 107).
standard output
standard input
PyPy 2
Python
2,400
train_054.jsonl
71a8f34b5c20ddb936bed761459a216e
256 megabytes
["1 1 10", "2 6 9", "3 1 10", "3 3 10"]
PASSED
rr=raw_input rrI = lambda: int(rr()) rrM = lambda: map(int,rr().split()) debug=0 if debug: fi = open('t.txt','r') rr=lambda: fi.readline().replace('\n','') from fractions import gcd def multi(lower, upper, factor): #How many x: lower <= x <= upper #have factor divide them? return int(upper / factor) - int((lower-1)/factor) def solve(N, L, R): if N > 24: return 0 if N == 1: return R-L+1 if N == 2: Z = R-L+1 return Z*(Z-1) zeta = int( R**(1/float(N-1)) ) while (zeta+1)**(N-1) <= R: zeta += 1 ans = 0 for p in xrange(1, zeta+1): for q in xrange(p+1, zeta+1): if gcd(p,q) == 1: numer = R * p**(N-1) denom = q**(N-1) upper = numer / denom #print 'ya', L, upper, denom count = multi(L, upper, p**(N-1)) count = max(count, 0) #print 'yo', count, p, q ans += count return ans * 2 print solve(*rrM())
1484838300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"]
cb8895ddd54ffbd898b1bf5e169feb63
NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$.
You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$.
Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$.
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β€” the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.
standard output
standard input
PyPy 3
Python
1,800
train_003.jsonl
46ae57b411205531acb24f463a626d40
256 megabytes
["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"]
PASSED
# NOT MY CODE # https://codeforces.com/contest/1324/submission/73179914 ## PYRIVAL BOOTSTRAP # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py # This decorator allows for recursion without actually doing recursion from types import GeneratorType 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 ###################### import math from bisect import bisect_left, bisect_right from sys import stdin, stdout, setrecursionlimit from collections import Counter input = lambda: stdin.readline().strip() print = stdout.write #setrecursionlimit(10**6) n = int(input()) ls = list(map(int, input().split())) children = {} for i in range(1, n+1): children[i] = [] for i in range(n-1): a, b = map(int, input().split()) children[a].append(b) children[b].append(a) parent = [-1] ans = [-1] for i in range(1, n+1): parent.append(-1) ans.append(-1) visited = [False] for i in range(1, n+1): visited.append(False) @bootstrap def dfs(node): visited[node] = True ans[node] = 1 if ls[node-1] else -1 for i in children[node]: if not visited[i]: parent[i] = node tmp = (yield dfs(i)) if tmp>0: ans[node]+=tmp ans[node] = max(ans[node], 1 if ls[node-1] else -1) yield ans[node] dfs(1) visited = [False] for i in range(1, n+1): visited.append(False) @bootstrap def dfs(node): visited[node] = True if node!=1: ans[node] = max(ans[node], ans[parent[node]] if ans[node]>=0 else ans[parent[node]]-1) for i in children[node]: if not visited[i]: yield dfs(i) yield dfs(1) for i in range(1, n+1): print(str(ans[i])+' ') print('\n')
1584018300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["3\n4 6 12", "-1"]
dfe5af743c9e23e98e6c9c5c319d2126
NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n.
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.
If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1, a2, ..., an (1 ≀ ai ≀ 106)Β β€” the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.
The first line contains a single integer m (1 ≀ m ≀ 1000)Β β€” the size of the set S. The second line contains m integers s1, s2, ..., sm (1 ≀ si ≀ 106)Β β€” the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 &lt; s2 &lt; ... &lt; sm.
standard output
standard input
Python 3
Python
1,900
train_012.jsonl
39544a59f4811e66a7ba6090a916e087
256 megabytes
["4\n2 4 6 12", "2\n2 3"]
PASSED
n=int(input()) a=list(map(int,input().split())) cur=a[-1] from math import gcd for i in range(1,n-1): cur=gcd(cur,a[i]) if (cur %a[0]!=0) and (a[0]!=1): print(-1) else: print(2*n) for i in a: print(i,a[0],end=' ')
1511099700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3"]
52863d45ad223687e6975344ab9d3124
NoteSample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Print a single number β€” the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
The first line contains three space-separated integers n, m and d (1 ≀ m ≀ n ≀ 100000;Β 0 ≀ d ≀ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≀ pi ≀ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.
standard output
standard input
Python 3
Python
2,000
train_017.jsonl
02ee61856c25477c51d643db6e14d300
256 megabytes
["6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6"]
PASSED
import collections class Graph: def __init__(self, n, dir): self.node_cnt = n self.__directed = dir self.__adjList = [] for i in range(n): self.__adjList.append([]) def addEdge(self, u, v): self.__adjList[u].append(v) if not self.__directed: self.__adjList[v].append(u) def getDistances(self, start, end=None): assert (0 <= start and start < self.node_cnt) dist = [-1] * self.node_cnt q = collections.deque() dist[start] = 0 q.append(start) while len(q) > 0: z, breakable = q.popleft(), False if end == z: break for t in self.__adjList[z]: if dist[t] == -1: dist[t] = dist[z] + 1 q.append(t) if t == end: breakable = True break if breakable: break return dist def getAffectedDiameter(graph, affected): affection = [False for i in range(graph.node_cnt)] for x in affected: affection[x] = True dist0 = graph.getDistances(affected[0]) affect_1 = -1 for i in range(n): if affection[i] and (affect_1 == -1 or dist0[affect_1] < dist0[i]): affect_1 = i dist1 = graph.getDistances(affect_1) affect_2 = -1 for i in range(n): if affection[i] and (affect_2 == -1 or dist1[affect_2] < dist1[i]): affect_2 = i return affect_1, affect_2 n, m, d = map(int, input().split()) p = list(map(lambda s: int(s)-1, input().split())) g = Graph(n, dir=False) for i in range(1, n): a, b = map(lambda s: int(s)-1, input().split()) g.addEdge(a, b) p1, p2 = getAffectedDiameter(g, p) d1, d2 = g.getDistances(p1), g.getDistances(p2) cnt = 0 for i in range(n): if d1[i] <= d and d2[i] <= d: cnt += 1 print(cnt)
1376668800
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["4\n5\n8", "7\n10\n5"]
37e2bb1c7caeeae7f8a7c837a2b390c9
null
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
For each query, print on a single line the number of liters of water in the corresponding vessel.
The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1Β piΒ xi", the query of the second type is represented as "2Β ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n).
standard output
standard input
PyPy 3
Python
1,800
train_043.jsonl
737bd9d084eac06ecf5bed158a9be7c9
256 megabytes
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
PASSED
'''input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 ''' # its dsu from sys import stdin, setrecursionlimit import math from collections import defaultdict, deque setrecursionlimit(15000) def process_query(node, x, max_capacity, cur_capacity, link): i = node while link[i] != n + 1 and x > 0 : if cur_capacity[link[i]] + x < max_capacity[link[i]]: cur_capacity[link[i]] += x break diff = max_capacity[link[i]] - cur_capacity[link[i]] cur_capacity[link[i]] = max_capacity[link[i]] x -= diff link[i] = link[i + 1] i = link[i] link[node] = link[i] def convert_to_dict(max_capacity): mydict1, mydict2 = dict(), dict() link = dict() for i in range(len(max_capacity)): mydict1[i + 1] = max_capacity[i] mydict2[i + 1] = 0 link[i+ 1] = i + 1 mydict1[len(max_capacity) + 1] = float('inf') mydict2[len(max_capacity )+ 1] = float('inf') link[len(max_capacity) + 1] = len(max_capacity) + 1 return mydict1, mydict2, link # main starts n = int(stdin.readline().strip()) max_capacity = list(map(int, stdin.readline().split())) max_capacity, cur_capacity, link = convert_to_dict(max_capacity) m = int(stdin.readline().strip()) for _ in range(m): query = list(map(int, stdin.readline().split())) if len(query) == 3: process_query(query[1], query[2], max_capacity, cur_capacity, link) #print(link) else: print(cur_capacity[query[1]])
1386493200
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["8\n4\n6\n11"]
2e7d4deeeb700d7ad008875779d6f969
NoteIn the first test case, YouKn0wWho can select the sequence $$$[0, 2, 6]$$$. So $$$f(6, 2) = c(1, 2) + c(3, 6) = 3 + 5 = 8$$$ which is the minimum possible.
For two positive integers $$$l$$$ and $$$r$$$ ($$$l \le r$$$) let $$$c(l, r)$$$ denote the number of integer pairs $$$(i, j)$$$ such that $$$l \le i \le j \le r$$$ and $$$\operatorname{gcd}(i, j) \ge l$$$. Here, $$$\operatorname{gcd}(i, j)$$$ is the greatest common divisor (GCD) of integers $$$i$$$ and $$$j$$$.YouKn0wWho has two integers $$$n$$$ and $$$k$$$ where $$$1 \le k \le n$$$. Let $$$f(n, k)$$$ denote the minimum of $$$\sum\limits_{i=1}^{k}{c(x_i+1,x_{i+1})}$$$ over all integer sequences $$$0=x_1 \lt x_2 \lt \ldots \lt x_{k} \lt x_{k+1}=n$$$.Help YouKn0wWho find $$$f(n, k)$$$.
For each test case, print a single integerΒ β€” $$$f(n, k)$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$)Β β€” the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$).
standard output
standard input
PyPy 3-64
Python
3,000
train_110.jsonl
1dfa86aa93dd171ae6b5b8eea2b0b0bc
1024 megabytes
["4\n6 2\n4 4\n3 1\n10 3"]
PASSED
# 1603D from itertools import accumulate from collections import Counter from math import floor, sqrt import io, os, sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, n2, n3 = 100009, 320, 18 phi = list(range(n)) root = [0]*n for i in range(2, n): if phi[i] == i: for j in range(i, n, i): phi[j] -= phi[j]//i a = list(accumulate(phi)) s1 = [[0]*n2 for _ in range(n)] s2 = [[0]*n2 for _ in range(n)] dp = [[float("inf")]*n for _ in range(n3)] dp[0][0] = 0 def c(l, r): if l > r: return float("inf") if r // l <= root[r]: return s1[r][r//l] - a[r//l] * (l - 1 - r//((r//l) + 1)) else: return s2[r][l] for i in range(1, n): root[i] = floor(sqrt(i)) for j in range(1, root[i] + 1): s1[i][j] = s1[i][j-1] + a[j] * (i//j - i//(j+1)) s2[i][i//(root[i] + 1) + 1] = s1[i][root[i]] for j in range(i//(root[i] + 1), 0, -1): s2[i][j] = s2[i][j+1] + a[i//j] def solve(l, r, x, y): if l > r: return mid = (l + r)//2 val = c(x+1, mid) for i in range(x, min(y, mid) + 1): if dp[k-1][i] + val < dp[k][mid]: dp[k][mid] = dp[k-1][i] + val pos = i val -= a[mid//(i+1)] solve(l, mid-1, x, pos) solve(mid+1, r, pos, y) for k in range(1, n3): solve(1, n-1, 0, n-1) ans = [] T = int(input()) for _ in range(T): nn, k = map(int, input().split()) ans += [nn] if k >= n3 else [dp[k][nn]] sys.stdout.write(" ".join(map(str, ans)) + "\n")
1635604500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
3 seconds
["3\n1 4 1\n5 6 2\n3 4 3\n-1\n2\n1 2 1\n2 3 1\n-1\n3\n1 3 2\n5 6 3\n3 4 1"]
a4f4ad94387b16e8760e7c7fd45b93b3
NoteThe example from the statement.In the second case, it is impossible to represent by segments of known numbers of length 2 or more.In the third case, you can get the segments '12' and '21' from the first phone number.
Masha meets a new friend and learns his phone numberΒ β€” $$$s$$$. She wants to remember it as soon as possible. The phone numberΒ β€” is a string of length $$$m$$$ that consists of digits from $$$0$$$ to $$$9$$$. The phone number may start with 0.Masha already knows $$$n$$$ phone numbers (all numbers have the same length $$$m$$$). It will be easier for her to remember a new number if the $$$s$$$ is represented as segments of numbers she already knows. Each such segment must be of length at least $$$2$$$, otherwise there will be too many segments and Masha will get confused.For example, Masha needs to remember the number: $$$s = $$$ '12345678' and she already knows $$$n = 4$$$ numbers: '12340219', '20215601', '56782022', '12300678'. You can represent $$$s$$$ as a $$$3$$$ segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent $$$s$$$.Masha asks you for help, she asks you to break the string $$$s$$$ into segments of length $$$2$$$ or more of the numbers she already knows. If there are several possible answers, print any of them.
You need to print the answers to $$$t$$$ test cases. The first line of the answer should contain one number $$$k$$$, corresponding to the number of segments into which you split the phone number $$$s$$$. Print -1 if you cannot get such a split. If the answer is yes, then follow $$$k$$$ lines containing triples of numbers $$$l, r, i$$$. Such triplets mean that the next $$$r-l+1$$$ digits of number $$$s$$$ are equal to a segment (substring) with boundaries $$$[l, r]$$$ of the phone under number $$$i$$$. Both the phones and the digits in them are numbered from $$$1$$$. Note that $$$r-l+1 \ge 2$$$ for all $$$k$$$ lines.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€”the number of test cases. Before each test case there is a blank line. Then there is a line containing integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^3$$$)Β β€”the number of phone numbers that Masha knows and the number of digits in each phone number. Then follow $$$n$$$ line, $$$i$$$-th of which describes the $$$i$$$-th number that Masha knows. The next line contains the phone number of her new friend $$$s$$$. Among the given $$$n+1$$$ phones, there may be duplicates (identical phones). It is guaranteed that the sum of $$$n \cdot m$$$ ($$$n$$$ multiplied by $$$m$$$) values over all input test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3
Python
2,000
train_102.jsonl
bf0b6e31df55c0f6196000eec2f4fcf7
256 megabytes
["5\n\n4 8\n12340219\n20215601\n56782022\n12300678\n12345678\n\n2 3\n134\n126\n123\n\n1 4\n1210\n1221\n\n4 3\n251\n064\n859\n957\n054\n\n4 7\n7968636\n9486033\n4614224\n5454197\n9482268"]
PASSED
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353 for _ in range(I()): S();n,m=M();have={};pos={};dp=[0]*(m+1);pr=[0]*(m+1);dp[0]=1 for i in range(n): cur=S() for j in range(m): t=cur[j] for k in range(1,3): if k+j>=m:break t+=cur[j+k] if not have.get(t,0): have[t]=1 pos[t]=(j,j+k,i) s=S() for i in range(m): t=s[i] for k in range(1,3): if i-k<0:break t=s[i-k]+t if have.get(t,0) and dp[i-k]: dp[i+1]=1 pr[i+1]=i-k if dp[i+1]:break if not dp[m]:print(-1);continue k=m;ans=[] while k>0: p=pr[k] t=s[p:k] ans.append(pos[t]) k=p print(len(ans));ans.reverse() for i in ans:print(i[0]+1,i[1]+1,i[2]+1)
1641825300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["-3 5 1 2 2\n1 1 1"]
fa24700412a8532b5b92c1e72d8a2e2d
NoteIn the first case, when removing vertex $$$1$$$ all remaining connected components have sum $$$5$$$ and when removing vertex $$$3$$$ all remaining connected components have sum $$$2$$$. When removing other vertices, there is only one remaining connected component so all remaining connected components have the same sum.
You are given an undirected unrooted tree, i.e. a connected undirected graph without cycles.You must assign a nonzero integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vertices.
For each test case, you must output one line with $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$, where $$$a_i$$$ is the weight assigned to vertex $$$i$$$. The weights must satisfy $$$-10^5 \leq a_i \leq 10^5$$$ and $$$a_i \neq 0$$$. It can be shown that there always exists a solution satisfying these constraints. If there are multiple possible solutions, output any of them.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) β€” the number of vertices of the tree. The next $$$n-1$$$ lines of each case contain each two integers $$$u, v$$$ ($$$1 \leq u,v \leq n$$$) denoting that there is an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. The sum of $$$n$$$ for all test cases is at most $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,200
train_092.jsonl
6853dc337b70dbcddcfb51dfd4903043
256 megabytes
["2\n5\n1 2\n1 3\n3 4\n3 5\n3\n1 2\n1 3"]
PASSED
import os,sys from io import BytesIO, IOBase from collections import deque, Counter,defaultdict as dft from heapq import heappop ,heappush from math import log,sqrt,factorial,cos,tan,sin,radians,log2,ceil,floor,gcd from bisect import bisect,bisect_left,bisect_right from decimal import * import sys,threading from itertools import permutations, combinations from copy import deepcopy input = sys.stdin.readline def modI(a, m): m0=m y=0 x=1; if(m==1): return 0; while(a>1): q=a//m; t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; if(x<0):x+=m0; return x; ii = lambda: int(input()) si = lambda: input().rstrip() mp = lambda: map(int, input().split()) ms= lambda: map(str,input().strip().split(" ")) ml = lambda: list(mp()) mf = lambda: map(float, input().split()) alphs = "abcdefghijklmnopqrstuvwxyz" # stuff you should look for # int overflow, array bounds # special cases (n=1?) # do smth instead of nothing and stay organized # WRITE STUFF DOWN # DON'T GET STUCK ON ONE APPROACH # DON'T use pow() multiple times use modI if possible. # def solve(): n=int(input()) dct=[[] for i in range(n+1)] for i in range(n-1): a,b=map(int,input().split()) dct[a].append(b) dct[b].append(a) w=[0]*(n+1) vis=[0]*(n+1) #print(curr,pre) st=deque([[1,1]]) while(st): nd,c=st.popleft() vis[nd]=1 w[nd]=len(dct[nd])*c for lnk in dct[nd]: if vis[lnk]:continue st.append([lnk,-c]) print(*w[1:]) 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") class SegmentTree: def __init__(self, data, default=0, func=gcd): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) # endregion if __name__ == "__main__": tc=1 tc = ii() for i in range(tc): solve()
1648132500
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
1 second
["YES\na\nba\naba\naba\nabacaba", "NO", "YES\nqwerty\nqwerty\nqwerty"]
5c33d1f970bcc2ffaea61d5407b877b2
NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".
You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".
If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.
The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) β€” the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.
standard output
standard input
PyPy 2
Python
1,100
train_002.jsonl
91eff6545e8e939cd34817c18228732a
256 megabytes
["5\na\naba\nabacaba\nba\naba", "5\na\nabacaba\nba\naba\nabab", "3\nqwerty\nqwerty\nqwerty"]
PASSED
n = input() ll = [] for i in xrange(n): ll.append(raw_input()) ll.sort(key=lambda x: len(x)) check = False for i in xrange(n): for j in xrange(i+1, n): if ll[i] not in ll[j]: check = True break if not check: print "YES" print "\n".join(ll) else: print "NO"
1614692100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
4 seconds
["YES\nYES\nNO\nYES\nNO"]
c53e3b38a345dcf65bf984e819c289ef
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: $$$1$$$-st query: $$$1$$$ – $$$3$$$ – $$$2$$$ $$$2$$$-nd query: $$$1$$$ – $$$2$$$ – $$$3$$$ $$$4$$$-th query: $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$2$$$ – $$$3$$$
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with $$$n$$$ vertices, then he will ask you $$$q$$$ queries. Each query contains $$$5$$$ integers: $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$, and $$$k$$$. This means you're asked to determine if there exists a path from vertex $$$a$$$ to $$$b$$$ that contains exactly $$$k$$$ edges after adding a bidirectional edge between vertices $$$x$$$ and $$$y$$$. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
For each query, print "YES" if there exists a path that contains exactly $$$k$$$ edges from vertex $$$a$$$ to $$$b$$$ after adding an edge between vertices $$$x$$$ and $$$y$$$. Otherwise, print "NO". You can print each letter in any case (upper or lower).
The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$), the number of vertices of the tree. Next $$$n-1$$$ lines contain two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) each, which means there is an edge between vertex $$$u$$$ and $$$v$$$. All edges are bidirectional and distinct. Next line contains an integer $$$q$$$ ($$$1 \le q \le 10^5$$$), the number of queries Gildong wants to ask. Next $$$q$$$ lines contain five integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$, and $$$k$$$ each ($$$1 \le x,y,a,b \le n$$$, $$$x \ne y$$$, $$$1 \le k \le 10^9$$$) – the integers explained in the description. It is guaranteed that the edge between $$$x$$$ and $$$y$$$ does not exist in the original tree.
standard output
standard input
Python 3
Python
2,000
train_009.jsonl
598575b1787c458d287272021f730065
512 megabytes
["5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9"]
PASSED
import sys # LCA implementation found from: # https://github.com/cheran-senthil/PyRival/blob/1971590e96b351288cacb09852896f2383862ab6/pyrival/graphs/lca.py class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)]) i <<= 1 def query(self, begin, end): depth = (end - begin).bit_length() - 1 return self.func( self._data[depth][begin], self._data[depth][end - (1 << depth)] ) class LCA: def __init__(self, root, graph): self.time = [-1] * len(graph) self.path = [] self.depth = [0] * len(graph) # MODIFIED dfs = [root] while dfs: node = dfs.pop() self.path.append(node) if self.time[node] == -1: self.time[node] = len(self.path) - 1 for nei in graph[node]: if self.time[nei] == -1: self.depth[nei] = self.depth[node] + 1 # MODIFIED dfs.append(node) dfs.append(nei) self.rmq = RangeQuery(self.time[node] for node in self.path) def lca(self, a, b): a = self.time[a] b = self.time[b] if a > b: a, b = b, a return self.path[self.rmq.query(a, b + 1)] def solve(N, edges, queries): graph = [[] for i in range(N + 1)] for e in edges: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) L = LCA(1, graph) def lca(u, v): return L.lca(u, v) def getDist(u, v): return L.depth[u] + L.depth[v] - 2 * L.depth[lca(u, v)] ans = [] for x, y, a, b, k in queries: d_ab = getDist(a, b) d_axyb = getDist(a, x) + 1 + getDist(y, b) d_ayxb = getDist(a, y) + 1 + getDist(x, b) if any(d <= k and (k - d) % 2 == 0 for d in [d_ab, d_axyb, d_ayxb]): ans.append("YES") else: ans.append("NO") return "\n".join(ans) if __name__ == "__main__": N = int(input()) edges = [] for i in range(N - 1): edges.append(list(map(int, sys.stdin.readline().split()))) Q = int(input()) queries = [] for i in range(Q): queries.append(list(map(int, sys.stdin.readline().split()))) ans = solve(N, edges, queries) print(ans)
1581771900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["YES\nNO\nYES\nYES"]
53a3313f5d6ce19413d72473717054fc
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes $$$[2, 0, 2]$$$. Then place the figure in the second column and after the second step of the process, the field becomes $$$[0, 0, 0]$$$.And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes $$$[0, 2]$$$. Then place the figure in the first column and after the second step of the process, the field becomes $$$[0, 0]$$$.In the fourth test case of the example, place the figure in the first column, then the field becomes $$$[102]$$$ after the first step of the process, and then the field becomes $$$[0]$$$ after the second step of the process.
You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$: You place one figure $$$2 \times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$); then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer β€” "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) β€” the number of columns in the Tetris field. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the initial height of the $$$i$$$-th column of the Tetris field.
standard output
standard input
PyPy 3
Python
900
train_007.jsonl
06468094bbaa2db78f3cefb55047df7d
256 megabytes
["4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100"]
PASSED
import sys def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def main(): for k in range(inp()): n=inp() col=inlt() i=0 for b in col: if(n-1!=i): if(col[i+1]-b)%2==1: print("NO") i+=1 break i+=1 if(i==n): print("YES") break return main()
1584018300
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["1\n2\n2\n2"]
3b8678d118c90d34c99ffa9259cc611f
NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$.
A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings β€” there are no restrictions.Formally, in one move you: choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively), swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously?
Print $$$Q$$$ integers β€” one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case.
The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) β€” the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ β€” one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones.
standard output
standard input
PyPy 3
Python
1,400
train_001.jsonl
2b752b2bd363a0151af8db9e5d90d9af
256 megabytes
["4\n1\n0\n3\n1110\n100110\n010101\n2\n11111\n000001\n2\n001\n11100111"]
PASSED
#!/usr/bin/env python import os import operator from collections import defaultdict import sys from io import BytesIO, IOBase import bisect # def power(x, p): # res = 1 # while p: # if p & 1: # res = res * x % 1000000007 # x = x * x % 1000000007 # p >>= 1 # return res; def main(): # n,m,k=map(int,input().split()) # A=[int(k) for k in input().split()] # B=[int(k) for k in input().split()] # a=[0] # b=[0] # for i in range(n): # a.append(a[i]+A[i]) # for i in range(m): # b.append(b[i]+B[i]) # ans=0 # j=m # for i in range(n+1): # if a[i]>k: # break # while b[j]>k-a[i]: # j-=1 # ans=max(ans,i+j) # #print(i,j) # print(ans) for _ in range(int(input())): n=int(input()) even_odd=0 ans=0 odd=0 for i in range(n): st=input() if len(st)&1: odd+=1 ans+=1 continue o=0 z=0 for j in range(len(st)): if st[j]=="1": o+=1 else: z+=1 if z&1==0: ans+=1 else: even_odd+=1 if even_odd & 1==1: if odd==0: even_odd-=1 print(ans+even_odd) # n=int(input()) # arr=[int(k) for k in input().split()] # odd=[] # even=[] # for i in range(2*n): # if arr[i]%2==0: # even.append(i+1) # else: # odd.append(i+1) # if len(odd)%2!=0 and len(even)%2!=0: # odd.pop() # even.pop() # for i in range(0,len(odd),2): # print(odd[i],odd[i+1]) # for i in range(0,len(even),2): # print(even[i],even[i+1]) # else: # if len(odd)!=0 and len(even)!=0: # odd.pop() # odd.pop() # for i in range(0, len(odd), 2): # print(odd[i], odd[i + 1]) # for i in range(0, len(even), 2): # print(even[i], even[i + 1]) # else: # for i in range(0,2*n-2,2): # print(i+1,i+2) 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") if __name__ == "__main__": main()
1571929500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1 2", "4 2 2 4"]
d2d21871c068e04469047e959dcf0d09
null
During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. First element $$$a_1$$$ becomes the root of the tree. Elements $$$a_2, a_3, \ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node.
Output $$$n - 1$$$ integers. For all $$$i &gt; 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.
The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$)Β β€” the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$)Β β€” the sequence $$$a$$$ itself.
standard output
standard input
PyPy 3
Python
1,800
train_024.jsonl
0e42650e13b95048df3d04e46cf6c2c6
256 megabytes
["3\n1 2 3", "5\n4 2 3 1 6"]
PASSED
# pylint: disable=redefined-builtin, ungrouped-imports from __future__ import print_function from bisect import bisect_left, bisect_right, insort from collections import Sequence, MutableSequence from functools import wraps from itertools import chain, repeat, starmap from math import log as log_e import operator as op from operator import iadd, add from functools import reduce from _dummy_thread import get_ident def recursive_repr(func): repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper class SortedList(MutableSequence): def __init__(self, iterable=None, load=1000): self._len = 0 self._lists = [] self._maxes = [] self._index = [] self._load = load self._twice = load * 2 self._half = load >> 1 self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None, load=1000): if key is None: return object.__new__(cls) else: if cls is SortedList: return SortedListWithKey(iterable=iterable, key=key, load=load) else: raise TypeError('inherit SortedListWithKey for key argument') def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, val): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, val) if pos == len(_maxes): pos -= 1 _lists[pos].append(val) _maxes[pos] = val else: insort(_lists[pos], val) self._expand(pos) else: _lists.append([val]) _maxes.append(val) self._len += 1 def _expand(self, pos): _lists = self._lists _index = self._index if len(_lists[pos]) > self._twice: _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: values.extend(chain.from_iterable(_lists)) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, val): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, val) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], val) return _lists[pos][idx] == val def discard(self, val): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, val) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], val) if _lists[pos][idx] == val: self._delete(pos, idx) def remove(self, val): _maxes = self._maxes if not _maxes: raise ValueError('{0} not in list'.format(repr(val))) pos = bisect_left(_maxes, val) if pos == len(_maxes): raise ValueError('{0} not in list'.format(repr(val))) _lists = self._lists idx = bisect_left(_lists[pos], val) if _lists[pos][idx] == val: self._delete(pos, idx) else: raise ValueError('{0} not in list'.format(repr(val))) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > self._half: _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not len(_index): self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, idx): if isinstance(idx, slice): start, stop, step = idx.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(idx) self._delete(pos, idx) _delitem = __delitem__ def __getitem__(self, idx): _lists = self._lists if isinstance(idx, slice): start, stop, step = idx.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) if start_pos == stop_pos: return _lists[start_pos][start_idx:stop_idx] prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if idx == 0: return _lists[0][0] elif idx == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= idx < len(_lists[0]): return _lists[0][idx] len_last = len(_lists[-1]) if -len_last < idx < 0: return _lists[-1][len_last + idx] pos, idx = self._pos(idx) return _lists[pos][idx] _getitem = __getitem__ def _check_order(self, idx, val): _len = self._len _lists = self._lists pos, loc = self._pos(idx) if idx < 0: idx += _len # Check that the inserted value is not less than the # previous value. if idx > 0: idx_prev = loc - 1 pos_prev = pos if idx_prev < 0: pos_prev -= 1 idx_prev = len(_lists[pos_prev]) - 1 if _lists[pos_prev][idx_prev] > val: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) # Check that the inserted value is not greater than # the previous value. if idx < (_len - 1): idx_next = loc + 1 pos_next = pos if idx_next == len(_lists[pos_next]): pos_next += 1 idx_next = 0 if _lists[pos_next][idx_next] < val: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) def __setitem__(self, index, value): _lists = self._lists _maxes = self._maxes _check_order = self._check_order _pos = self._pos if isinstance(index, slice): start, stop, step = index.indices(self._len) indices = range(start, stop, step) if step != 1: if not hasattr(value, '__len__'): value = list(value) indices = list(indices) if len(value) != len(indices): raise ValueError( 'attempt to assign sequence of size {0}' ' to extended slice of size {1}' .format(len(value), len(indices))) # Keep a log of values that are set so that we can # roll back changes if ordering is violated. log = [] _append = log.append for idx, val in zip(indices, value): pos, loc = _pos(idx) _append((idx, _lists[pos][loc], val)) _lists[pos][loc] = val if len(_lists[pos]) == (loc + 1): _maxes[pos] = val try: # Validate ordering of new values. for idx, oldval, newval in log: _check_order(idx, newval) except ValueError: # Roll back changes from log. for idx, oldval, newval in log: pos, loc = _pos(idx) _lists[pos][loc] = oldval if len(_lists[pos]) == (loc + 1): _maxes[pos] = oldval raise else: if start == 0 and stop == self._len: self._clear() return self._update(value) # Test ordering using indexing. If the given value # isn't a Sequence, convert it to a tuple. if not isinstance(value, Sequence): value = tuple(value) # pylint: disable=redefined-variable-type # Check that the given values are ordered properly. iterator = range(1, len(value)) if not all(value[pos - 1] <= value[pos] for pos in iterator): raise ValueError('given sequence not in sort order') # Check ordering in context of sorted list. if not start or not len(value): # Nothing to check on the lhs. pass else: if self._getitem(start - 1) > value[0]: msg = '{0} not in sort order at index {1}'.format(repr(value[0]), start) raise ValueError(msg) if stop == len(self) or not len(value): # Nothing to check on the rhs. pass else: # "stop" is exclusive so we don't need # to add one for the index. if self._getitem(stop) < value[-1]: msg = '{0} not in sort order at index {1}'.format(repr(value[-1]), stop) raise ValueError(msg) # Delete the existing values. self._delitem(index) # Insert the new values. _insert = self.insert for idx, val in enumerate(value): _insert(start + idx, val) else: pos, loc = _pos(index) _check_order(index, value) _lists[pos][loc] = value if len(_lists[pos]) == (loc + 1): _maxes[pos] = value def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) elif min_pos == max_pos and not reverse: return iter(_lists[min_pos][min_idx:max_idx]) elif min_pos == max_pos and reverse: return reversed(_lists[min_pos][min_idx:max_idx]) elif min_pos + 1 == max_pos and not reverse: return chain(_lists[min_pos][min_idx:], _lists[max_pos][:max_idx]) elif min_pos + 1 == max_pos and reverse: return chain( reversed(_lists[max_pos][:max_idx]), reversed(_lists[min_pos][min_idx:]), ) elif not reverse: return chain( _lists[min_pos][min_idx:], chain.from_iterable(_lists[(min_pos + 1):max_pos]), _lists[max_pos][:max_idx], ) else: temp = map(reversed, reversed(_lists[(min_pos + 1):max_pos])) return chain( reversed(_lists[max_pos][:max_idx]), chain.from_iterable(temp), reversed(_lists[min_pos][min_idx:]), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): return self._len def bisect_left(self, val): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, val) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], val) return self._loc(pos, idx) def bisect_right(self, val): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, val) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], val) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, val): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, val) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], val) pos_right = bisect_right(_maxes, val) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], val) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self, load=self._load) __copy__ = copy def append(self, val): _lists = self._lists _maxes = self._maxes if not _maxes: _maxes.append(val) _lists.append([val]) self._len = 1 return pos = len(_lists) - 1 if val < _lists[pos][-1]: msg = '{0} not in sort order at index {1}'.format(repr(val), self._len) raise ValueError(msg) _maxes[pos] = val _lists[pos].append(val) self._len += 1 self._expand(pos) def extend(self, values): _lists = self._lists _maxes = self._maxes _load = self._load if not isinstance(values, list): values = list(values) if any(values[pos - 1] > values[pos] for pos in range(1, len(values))): raise ValueError('given sequence not in sort order') offset = 0 if _maxes: if values[0] < _lists[-1][-1]: msg = '{0} not in sort order at index {1}'.format(repr(values[0]), self._len) raise ValueError(msg) if len(_lists[-1]) < self._half: _lists[-1].extend(values[:_load]) _maxes[-1] = _lists[-1][-1] offset = _load len_lists = len(_lists) for idx in range(offset, len(values), _load): _lists.append(values[idx:(idx + _load)]) _maxes.append(_lists[-1][-1]) _index = self._index if len_lists == len(_lists): len_index = len(_index) if len_index > 0: len_values = len(values) child = len_index - 1 while child: _index[child] += len_values child = (child - 1) >> 1 _index[0] += len_values else: del _index[:] self._len += len(values) def insert(self, idx, val): _len = self._len _lists = self._lists _maxes = self._maxes if idx < 0: idx += _len if idx < 0: idx = 0 if idx > _len: idx = _len if not _maxes: # The idx must be zero by the inequalities above. _maxes.append(val) _lists.append([val]) self._len = 1 return if not idx: if val > _lists[0][0]: msg = '{0} not in sort order at index {1}'.format(repr(val), 0) raise ValueError(msg) else: _lists[0].insert(0, val) self._expand(0) self._len += 1 return if idx == _len: pos = len(_lists) - 1 if _lists[pos][-1] > val: msg = '{0} not in sort order at index {1}'.format(repr(val), _len) raise ValueError(msg) else: _lists[pos].append(val) _maxes[pos] = _lists[pos][-1] self._expand(pos) self._len += 1 return pos, idx = self._pos(idx) idx_before = idx - 1 if idx_before < 0: pos_before = pos - 1 idx_before = len(_lists[pos_before]) - 1 else: pos_before = pos before = _lists[pos_before][idx_before] if before <= val <= _lists[pos][idx]: _lists[pos].insert(idx, val) self._expand(pos) self._len += 1 else: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) def pop(self, idx=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if idx == 0: val = _lists[0][0] self._delete(0, 0) return val if idx == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= idx < len(_lists[0]): val = _lists[0][idx] self._delete(0, idx) return val len_last = len(_lists[-1]) if -len_last < idx < 0: pos = len(_lists) - 1 loc = len_last + idx val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(idx) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, val, start=None, stop=None): # pylint: disable=arguments-differ _len = self._len if not _len: raise ValueError('{0} is not in list'.format(repr(val))) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0} is not in list'.format(repr(val))) _maxes = self._maxes pos_left = bisect_left(_maxes, val) if pos_left == len(_maxes): raise ValueError('{0} is not in list'.format(repr(val))) _lists = self._lists idx_left = bisect_left(_lists[pos_left], val) if _lists[pos_left][idx_left] != val: raise ValueError('{0} is not in list'.format(repr(val))) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(val) - 1 if start <= right: return start raise ValueError('{0} is not in list'.format(repr(val))) def __add__(self, that): values = reduce(iadd, self._lists, []) values.extend(that) return self.__class__(values, load=self._load) def __iadd__(self, that): self._update(that) return self def __mul__(self, that): values = reduce(iadd, self._lists, []) * that return self.__class__(values, load=self._load) def __imul__(self, that): values = reduce(iadd, self._lists, []) * that self._clear() self._update(values) return self def _make_cmp(self, seq_op, doc): "Make comparator method." def comparer(self, that): "Compare method for sorted list and sequence." # pylint: disable=protected-access if not isinstance(that, Sequence): return NotImplemented self_len = self._len len_that = len(that) if self_len != len_that: if seq_op is op.eq: return False if seq_op is op.ne: return True for alpha, beta in zip(self, that): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_that) comparer.__name__ = '__{0}__'.format(seq_op.__name__) doc_str = 'Return `True` if and only if Sequence is {0} `that`.' comparer.__doc__ = doc_str.format(doc) return comparer __eq__ = _make_cmp(None, op.eq, 'equal to') __ne__ = _make_cmp(None, op.ne, 'not equal to') __lt__ = _make_cmp(None, op.lt, 'less than') __gt__ = _make_cmp(None, op.gt, 'greater than') __le__ = _make_cmp(None, op.le, 'less than or equal to') __ge__ = _make_cmp(None, op.ge, 'greater than or equal to') @recursive_repr def __repr__(self): temp = '{0}({1}, load={2})' return temp.format( self.__class__.__name__, repr(list(self)), repr(self._load) ) def _check(self): try: # Check load parameters. assert self._load >= 4 assert self._half == (self._load >> 1) assert self._twice == (self._load * 2) # Check empty sorted list case. if self._maxes == []: assert self._lists == [] return assert len(self._maxes) > 0 and len(self._lists) > 0 # Check all sublists are sorted. assert all(sublist[pos - 1] <= sublist[pos] for sublist in self._lists for pos in range(1, len(sublist))) # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check length of _maxes and _lists match. assert len(self._maxes) == len(self._lists) # Check _maxes is a map of _lists. assert all(self._maxes[pos] == self._lists[pos][-1] for pos in range(len(self._maxes))) # Check load level is less than _twice. assert all(len(sublist) <= self._twice for sublist in self._lists) # Check load level is greater than _half for all # but the last sublist. assert all(len(self._lists[pos]) >= self._half for pos in range(0, len(self._lists) - 1)) # Check length. assert self._len == sum(len(sublist) for sublist in self._lists) # Check index. if len(self._index): assert len(self._index) == self._offset + len(self._lists) assert self._len == self._index[0] def test_offset_pos(pos): "Test positional indexing offset." from_index = self._index[self._offset + pos] return from_index == len(self._lists[pos]) assert all(test_offset_pos(pos) for pos in range(len(self._lists))) for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert self._index[pos] == child_sum except: import sys import traceback traceback.print_exc(file=sys.stdout) print('len', self._len) print('load', self._load, self._half, self._twice) print('offset', self._offset) print('len_index', len(self._index)) print('index', self._index) print('len_maxes', len(self._maxes)) print('maxes', self._maxes) print('len_lists', len(self._lists)) print('lists', self._lists) raise def identity(value): "Identity function." return value class SortedListWithKey(SortedList): def __init__(self, iterable=None, key=identity, load=1000): # pylint: disable=super-init-not-called self._len = 0 self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._key = key self._load = load self._twice = load * 2 self._half = load >> 1 self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity, load=1000): return object.__new__(cls) def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, val): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(val) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(val) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, val) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([val]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > self._twice: _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: values.extend(chain.from_iterable(_lists)) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, val): _maxes = self._maxes if not _maxes: return False key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == val: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, val): _maxes = self._maxes if not _maxes: return key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == val: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, val): _maxes = self._maxes if not _maxes: raise ValueError('{0} not in list'.format(repr(val))) key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0} not in list'.format(repr(val))) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0} not in list'.format(repr(val))) if _lists[pos][idx] == val: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0} not in list'.format(repr(val))) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > self._half: _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def _check_order(self, idx, key, val): # pylint: disable=arguments-differ _len = self._len _keys = self._keys pos, loc = self._pos(idx) if idx < 0: idx += _len # Check that the inserted value is not less than the # previous value. if idx > 0: idx_prev = loc - 1 pos_prev = pos if idx_prev < 0: pos_prev -= 1 idx_prev = len(_keys[pos_prev]) - 1 if _keys[pos_prev][idx_prev] > key: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) # Check that the inserted value is not greater than # the previous value. if idx < (_len - 1): idx_next = loc + 1 pos_next = pos if idx_next == len(_keys[pos_next]): pos_next += 1 idx_next = 0 if _keys[pos_next][idx_next] < key: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) def __setitem__(self, index, value): _lists = self._lists _keys = self._keys _maxes = self._maxes _check_order = self._check_order _pos = self._pos if isinstance(index, slice): start, stop, step = index.indices(self._len) indices = range(start, stop, step) if step != 1: if not hasattr(value, '__len__'): value = list(value) indices = list(indices) if len(value) != len(indices): raise ValueError( 'attempt to assign sequence of size {0}' ' to extended slice of size {1}' .format(len(value), len(indices))) # Keep a log of values that are set so that we can # roll back changes if ordering is violated. log = [] _append = log.append for idx, val in zip(indices, value): pos, loc = _pos(idx) key = self._key(val) _append((idx, _keys[pos][loc], key, _lists[pos][loc], val)) _keys[pos][loc] = key _lists[pos][loc] = val if len(_keys[pos]) == (loc + 1): _maxes[pos] = key try: # Validate ordering of new values. for idx, oldkey, newkey, oldval, newval in log: _check_order(idx, newkey, newval) except ValueError: # Roll back changes from log. for idx, oldkey, newkey, oldval, newval in log: pos, loc = _pos(idx) _keys[pos][loc] = oldkey _lists[pos][loc] = oldval if len(_keys[pos]) == (loc + 1): _maxes[pos] = oldkey raise else: if start == 0 and stop == self._len: self._clear() return self._update(value) # Test ordering using indexing. If the given value # isn't a Sequence, convert it to a tuple. if not isinstance(value, Sequence): value = tuple(value) # pylint: disable=redefined-variable-type # Check that the given values are ordered properly. keys = tuple(map(self._key, value)) iterator = range(1, len(keys)) if not all(keys[pos - 1] <= keys[pos] for pos in iterator): raise ValueError('given sequence not in sort order') # Check ordering in context of sorted list. if not start or not len(value): # Nothing to check on the lhs. pass else: pos, loc = _pos(start - 1) if _keys[pos][loc] > keys[0]: msg = '{0} not in sort order at index {1}'.format(repr(value[0]), start) raise ValueError(msg) if stop == len(self) or not len(value): # Nothing to check on the rhs. pass else: # "stop" is exclusive so we don't need # to add one for the index. pos, loc = _pos(stop) if _keys[pos][loc] < keys[-1]: msg = '{0} not in sort order at index {1}'.format(repr(value[-1]), stop) raise ValueError(msg) # Delete the existing values. self._delitem(index) # Insert the new values. _insert = self.insert for idx, val in enumerate(value): _insert(start + idx, val) else: pos, loc = _pos(index) key = self._key(value) _check_order(index, key, value) _lists[pos][loc] = value _keys[pos][loc] = key if len(_lists[pos]) == (loc + 1): _maxes[pos] = key def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): minimum = self._key(minimum) if minimum is not None else None maximum = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=minimum, max_key=maximum, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, val): return self._bisect_key_left(self._key(val)) def bisect_right(self, val): return self._bisect_key_right(self._key(val)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, val): _maxes = self._maxes if not _maxes: return 0 key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == val: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key, load=self._load) __copy__ = copy def append(self, val): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(val) if not _maxes: _maxes.append(key) _keys.append([key]) _lists.append([val]) self._len = 1 return pos = len(_keys) - 1 if key < _keys[pos][-1]: msg = '{0} not in sort order at index {1}'.format(repr(val), self._len) raise ValueError(msg) _lists[pos].append(val) _keys[pos].append(key) _maxes[pos] = key self._len += 1 self._expand(pos) def extend(self, values): _lists = self._lists _keys = self._keys _maxes = self._maxes _load = self._load if not isinstance(values, list): values = list(values) keys = list(map(self._key, values)) if any(keys[pos - 1] > keys[pos] for pos in range(1, len(keys))): raise ValueError('given sequence not in sort order') offset = 0 if _maxes: if keys[0] < _keys[-1][-1]: msg = '{0} not in sort order at index {1}'.format(repr(values[0]), self._len) raise ValueError(msg) if len(_keys[-1]) < self._half: _lists[-1].extend(values[:_load]) _keys[-1].extend(keys[:_load]) _maxes[-1] = _keys[-1][-1] offset = _load len_keys = len(_keys) for idx in range(offset, len(keys), _load): _lists.append(values[idx:(idx + _load)]) _keys.append(keys[idx:(idx + _load)]) _maxes.append(_keys[-1][-1]) _index = self._index if len_keys == len(_keys): len_index = len(_index) if len_index > 0: len_values = len(values) child = len_index - 1 while child: _index[child] += len_values child = (child - 1) >> 1 _index[0] += len_values else: del _index[:] self._len += len(values) def insert(self, idx, val): _len = self._len _lists = self._lists _keys = self._keys _maxes = self._maxes if idx < 0: idx += _len if idx < 0: idx = 0 if idx > _len: idx = _len key = self._key(val) if not _maxes: self._len = 1 _lists.append([val]) _keys.append([key]) _maxes.append(key) return if not idx: if key > _keys[0][0]: msg = '{0} not in sort order at index {1}'.format(repr(val), 0) raise ValueError(msg) else: self._len += 1 _lists[0].insert(0, val) _keys[0].insert(0, key) self._expand(0) return if idx == _len: pos = len(_keys) - 1 if _keys[pos][-1] > key: msg = '{0} not in sort order at index {1}'.format(repr(val), _len) raise ValueError(msg) else: self._len += 1 _lists[pos].append(val) _keys[pos].append(key) _maxes[pos] = _keys[pos][-1] self._expand(pos) return pos, idx = self._pos(idx) idx_before = idx - 1 if idx_before < 0: pos_before = pos - 1 idx_before = len(_keys[pos_before]) - 1 else: pos_before = pos before = _keys[pos_before][idx_before] if before <= key <= _keys[pos][idx]: self._len += 1 _lists[pos].insert(idx, val) _keys[pos].insert(idx, key) self._expand(pos) else: msg = '{0} not in sort order at index {1}'.format(repr(val), idx) raise ValueError(msg) def index(self, val, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0} is not in list'.format(repr(val))) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0} is not in list'.format(repr(val))) _maxes = self._maxes key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0} is not in list'.format(repr(val))) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0} is not in list'.format(repr(val))) if _lists[pos][idx] == val: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0} is not in list'.format(repr(val))) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0} is not in list'.format(repr(val))) def __add__(self, that): values = reduce(iadd, self._lists, []) values.extend(that) return self.__class__(values, key=self._key, load=self._load) def __mul__(self, that): values = reduce(iadd, self._lists, []) * that return self.__class__(values, key=self._key, load=self._load) def __imul__(self, that): values = reduce(iadd, self._lists, []) * that self._clear() self._update(values) return self @recursive_repr def __repr__(self): temp = '{0}({1}, key={2}, load={3})' return temp.format( self.__class__.__name__, repr(list(self)), repr(self._key), repr(self._load) ) def _check(self): try: # Check load parameters. assert self._load >= 4 assert self._half == (self._load >> 1) assert self._twice == (self._load * 2) # Check empty sorted list case. if self._maxes == []: assert self._keys == [] assert self._lists == [] return assert len(self._maxes) > 0 and len(self._keys) > 0 and len(self._lists) > 0 # Check all sublists are sorted. assert all(sublist[pos - 1] <= sublist[pos] for sublist in self._keys for pos in range(1, len(sublist))) # Check beginning/end of sublists are sorted. for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] # Check length of _maxes and _lists match. assert len(self._maxes) == len(self._lists) == len(self._keys) # Check _keys matches _key mapped to _lists. assert all(len(val_list) == len(key_list) for val_list, key_list in zip(self._lists, self._keys)) assert all(self._key(val) == key for val, key in zip((_val for _val_list in self._lists for _val in _val_list), (_key for _key_list in self._keys for _key in _key_list))) # Check _maxes is a map of _keys. assert all(self._maxes[pos] == self._keys[pos][-1] for pos in range(len(self._maxes))) # Check load level is less than _twice. assert all(len(sublist) <= self._twice for sublist in self._lists) # Check load level is greater than _half for all # but the last sublist. assert all(len(self._lists[pos]) >= self._half for pos in range(0, len(self._lists) - 1)) # Check length. assert self._len == sum(len(sublist) for sublist in self._lists) # Check index. if len(self._index): assert len(self._index) == self._offset + len(self._lists) assert self._len == self._index[0] def test_offset_pos(pos): "Test positional indexing offset." from_index = self._index[self._offset + pos] return from_index == len(self._lists[pos]) assert all(test_offset_pos(pos) for pos in range(len(self._lists))) for pos in range(self._offset): child = (pos << 1) + 1 if self._index[pos] == 0: assert child >= len(self._index) elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert self._index[pos] == child_sum except: import sys import traceback traceback.print_exc(file=sys.stdout) print('len', self._len) print('load', self._load, self._half, self._twice) print('offset', self._offset) print('len_index', len(self._index)) print('index', self._index) print('len_maxes', len(self._maxes)) print('maxes', self._maxes) print('len_keys', len(self._keys)) print('keys', self._keys) print('len_lists', len(self._lists)) print('lists', self._lists) raise n = int(input()) r = SortedList([(-1, -1)]) for x in map(int, input().split()): i = r.bisect((x+1, -1))-1 y, p = r[i] if p != -1: print(p, end=' ') del r[i] r.add((y, x)) r.add((x, x)) print()
1463416500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["0\n2\n13\n3\n20"]
36aec7a06c02052f562ea3d44d4a62e4
null
You are given the strings $$$a$$$ and $$$b$$$, consisting of lowercase Latin letters. You can do any number of the following operations in any order: if $$$|a| &gt; 0$$$ (the length of the string $$$a$$$ is greater than zero), delete the first character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_2 a_3 \ldots a_n$$$; if $$$|a| &gt; 0$$$, delete the last character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_1 a_2 \ldots a_{n-1}$$$; if $$$|b| &gt; 0$$$ (the length of the string $$$b$$$ is greater than zero), delete the first character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_2 b_3 \ldots b_n$$$; if $$$|b| &gt; 0$$$, delete the last character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_1 b_2 \ldots b_{n-1}$$$. Note that after each of the operations, the string $$$a$$$ or $$$b$$$ may become empty.For example, if $$$a=$$$"hello" and $$$b=$$$"icpc", then you can apply the following sequence of operations: delete the first character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"icpc"; delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"cpc"; delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"pc"; delete the last character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"pc"; delete the last character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"p". For the given strings $$$a$$$ and $$$b$$$, find the minimum number of operations for which you can make the strings $$$a$$$ and $$$b$$$ equal. Note that empty strings are also equal.
For each test case, output the minimum number of operations that can make the strings $$$a$$$ and $$$b$$$ equal.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains the string $$$a$$$ ($$$1 \le |a| \le 20$$$), consisting of lowercase Latin letters. The second line of each test case contains the string $$$b$$$ ($$$1 \le |b| \le 20$$$), consisting of lowercase Latin letters.
standard output
standard input
Python 3
Python
1,000
train_101.jsonl
cbcd2027912233e68fe65867ce7731c8
256 megabytes
["5\na\na\nabcd\nbc\nhello\ncodeforces\nhello\nhelo\ndhjakjsnasjhfksafasd\nadjsnasjhfksvdafdser"]
PASSED
import sys def stringComparator(a, b): n = len(a) m = len(b) size = 0 for i in range(1, min(n,m) + 1): for j in range(0, n - i + 1): for k in range(0, m - i + 1): if (a[j: j + i] == b[k: k + i]): size = max(size, i) #print("final size:",size) return((len(a) + len(b)) - (size * 2)) if __name__ == '__main__': n = int(sys.stdin.readline()) arr = [] for i in range (0, n): a = input() b = input() arr.append(stringComparator(a, b)) for i in range(0, len(arr)): print(arr[i])
1616682900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2 1", "1 3 2"]
f35d7f9c12eea4364891e0449613f6b0
null
Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors β€” the positive integers i such that for at least one j (1 ≀ j ≀ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.Help Vasya β€” find the volume disposition with the minimum number of divisors.
Print n numbers β€” the sought disposition with the minimum divisor number. The j-th number (1 ≀ j ≀ n) should be equal to p(j) β€” the number of tome that stands on the j-th place. If there are several solutions, print any of them.
The first line contains number n (1 ≀ n ≀ 100000) which represents the number of volumes and free places.
standard output
standard input
PyPy 3
Python
1,700
train_007.jsonl
17218f3206b7060ec4739761660fdf0a
256 megabytes
["2", "3"]
PASSED
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict 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") #-------------------game starts now----------------------------------------------------- n=int(input()) l=[i for i in range(1,n)] l=[n]+l print(*l,sep=" ")
1292601600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["XXX\n..X\nXXX\nXXXX\n.X.X\n.X..\n.XXX\n.X...\n.XXXX\n.X...\n.X...\nXXXXX\nXXXXXXXXXX\n..\n.."]
669390a40a6ef9bf1547c71823da169b
NoteLet's use $$$(x,y)$$$ to describe the cell on $$$x$$$-th row and $$$y$$$-th column.In the following pictures white, yellow, and blue cells stand for the cells that grow a sunflower, the cells lightning stroke, and the cells sunflower on which are removed, respectively.In the first test case, one possible solution is to remove sunflowers on $$$(1,2)$$$, $$$(2,3)$$$ and $$$(3 ,2)$$$. Another acceptable solution is to remove sunflowers on $$$(1,2)$$$, $$$(2,2)$$$ and $$$(3,2)$$$. This output is considered wrong because there are 2 simple paths between any pair of cells (there is a cycle). For example, there are 2 simple paths between $$$(1,1)$$$ and $$$(3,3)$$$. $$$(1,1)\to (1,2)\to (1,3)\to (2,3)\to (3,3)$$$ $$$(1,1)\to (2,1)\to (3,1)\to (3,2)\to (3,3)$$$ This output is considered wrong because you can't walk from $$$(1,1)$$$ to $$$(3,3)$$$.
There are many sunflowers in the Garden of the Sun.Garden of the Sun is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, any two empty cells have no common points (neither edges nor corners).Now the owner wants to remove some (possibly zero) sunflowers to reach the following two goals: When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected. There is exactly one simple path between any two empty cells. In other words, there is no cycle among the empty cells. You can walk from an empty cell to another if they share a common edge.Could you please give the owner a solution that meets all her requirements?Note that you are not allowed to plant sunflowers. You don't need to minimize the number of sunflowers you remove. It can be shown that the answer always exists.
For each test case, print $$$n$$$ lines. Each should contain $$$m$$$ characters, representing one row of the table. Each character should be either 'X' or '.', representing an empty cell and a cell with a sunflower, respectively. If there are multiple answers, you can print any. It can be shown that the answer always exists.
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. The description of the test cases follows. The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 500$$$)Β β€” the number of rows and columns. Each of the next $$$n$$$ lines contains $$$m$$$ characters. Each character is either 'X' or '.', representing an empty cell and a cell that grows a sunflower, respectively. It is guaranteed that the sum of $$$n \cdot m$$$ for all test cases does not exceed $$$250\,000$$$.
standard output
standard input
PyPy 3
Python
2,300
train_085.jsonl
3b758af957b840cfe4bce60eff7a5d8b
256 megabytes
["5\n3 3\nX.X\n...\nX.X\n4 4\n....\n.X.X\n....\n.X.X\n5 5\n.X...\n....X\n.X...\n.....\nX.X.X\n1 10\n....X.X.X.\n2 2\n..\n.."]
PASSED
import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n,m=map(int,input().split()) MAP=[list(input().strip()) for i in range(n)] if m<=1: for i in range(n): MAP[i][0]="X" for j in range(1,m,3): for i in range(n): MAP[i][j]="X" for j in range(2,m,3): if j+1<m: for i in range(n): if MAP[i][j]=="X": MAP[i][j+1]="X" break else: for i in range(n): if MAP[i][j+1]=="X": MAP[i][j]="X" break else: MAP[0][j]=MAP[0][j+1]="X" if m%3==1: for i in range(n): if MAP[i][m-1]=="X": MAP[i][m-2]="X" for i in range(n): print("".join(MAP[i])) #print()
1615377900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["8\n141093479"]
5c3eb78a7e15d9afe6d745e1a77d7451
null
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?
Print the sought number of operations for each pair on a single line.
The first line contains the number of pairs n (1  ≀  n  ≀  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≀  ai,  bi  ≀  109).
standard output
standard input
Python 3
Python
900
train_002.jsonl
87bff2ba34b4208ed96986b662590d89
256 megabytes
["2\n4 17\n7 987654321"]
PASSED
def solve(a, b): holder = [a, b] times = 0 while holder[0] > 0 and holder[1] > 0: smaller = 0 if holder[0] < holder[1] else 1 other = 1 - smaller # how many times does smaller go into bigger? times += holder[other] // holder[smaller] # guaranteed to be smaller than `smaller` now holder[other] = holder[other] % holder[smaller] return times def main(): cases = int(input()) for _ in range(cases): a, b = map(int, input().split()) print(solve(a, b)) if __name__ == "__main__": main()
1358002800
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n12\n13\n28\n55\n85\n500099995000"]
7d774a003d2e3e8ae6fe1912b3998c96
NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.
You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path. For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.
For each test case output a single integer β€” a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β€” the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) β€” the number of rows and columns of the table $$$a$$$ respectively.
standard output
standard input
PyPy 3-64
Python
800
train_094.jsonl
6ae99e03dfee779a013589b2966d2b43
256 megabytes
["7\n\n1 1\n\n2 3\n\n3 2\n\n7 1\n\n1 10\n\n5 5\n\n10000 10000"]
PASSED
t = int(input()) list = [] for i in range(1,t+1): pair = input().split() list.append(pair) for i in range(1,t+1): n = int(list[i-1][0]) m = int(list[i-1][1]) sum = 0 for x in range(1,m): sum = sum + x for y in range(1,n+1): sum = sum + (y*m) print(sum)
1655629500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]