prob_desc_time_limit
stringclasses
21 values
prob_desc_sample_outputs
stringlengths
5
329
src_uid
stringlengths
32
32
prob_desc_notes
stringlengths
31
2.84k
prob_desc_description
stringlengths
121
3.8k
prob_desc_output_spec
stringlengths
17
1.16k
prob_desc_input_spec
stringlengths
38
2.42k
prob_desc_output_to
stringclasses
3 values
prob_desc_input_from
stringclasses
3 values
lang
stringclasses
5 values
lang_cluster
stringclasses
1 value
difficulty
int64
-1
3.5k
file_name
stringclasses
111 values
code_uid
stringlengths
32
32
prob_desc_memory_limit
stringclasses
11 values
prob_desc_sample_inputs
stringlengths
5
802
exec_outcome
stringclasses
1 value
source_code
stringlengths
29
58.4k
prob_desc_created_at
stringlengths
10
10
tags
listlengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
listlengths
8
8
2 seconds
["12"]
a18edcadb31f76e69968b0a3e1cb7e3e
NoteHere's a picture depicting the example. Each vertical column presents the stacked books.
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. He lifts all the books above book x. He pushes book x out of the stack. He puts down the lifted books without changing their order. After reading book x, he puts book x on the top of the stack. He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?
Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.
The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.
standard output
standard input
PyPy 2
Python
1,600
train_015.jsonl
676e9cd287bcaefb21cc10bb73d7965d
256 megabytes
["3 5\n1 2 3\n1 3 2 3 1"]
PASSED
import copy n,m=map(int,raw_input().split()) w=map(int,raw_input().split()) b=map(int,raw_input().split()) initial=[] for i in range(len(b)): b[i]-=1 for bb in b: if bb not in initial: initial.append(bb) ans=0 for bb in b: num=initial.index(bb) for i in range(num): ans+=w[initial[i]] tmp=copy.copy(initial[num]) del initial[num] initial.insert(0,tmp) print ans
1419951600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["18\n14\n-1\n-1\n0\n11\n25599\n184470016815529983"]
10ec2bd27cbb7aaf7b52c281591cc043
NoteIn the first test case, $$$x=18$$$ is one of the possible solutions, since $$$39|18=55$$$ and $$$12|18=30$$$, both of which are multiples of $$$d=5$$$.In the second test case, $$$x=14$$$ is one of the possible solutions, since $$$8|14=6|14=14$$$, which is a multiple of $$$d=14$$$.In the third and fourth test cases, we can show that there are no solutions.
You are given three integers $$$a$$$, $$$b$$$, and $$$d$$$. Your task is to find any integer $$$x$$$ which satisfies all of the following conditions, or determine that no such integers exist: $$$0 \le x \lt 2^{60}$$$; $$$a|x$$$ is divisible by $$$d$$$; $$$b|x$$$ is divisible by $$$d$$$. Here, $$$|$$$ denotes the bitwise OR operation.
For each test case print one integer. If there exists an integer $$$x$$$ which satisfies all of the conditions from the statement, print $$$x$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any of them.
Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line, containing three integers $$$a$$$, $$$b$$$, and $$$d$$$ ($$$1 \le a,b,d \lt 2^{30}$$$).
standard output
standard input
PyPy 3-64
Python
2,100
train_083.jsonl
08746a4516507a05dc1af0d5088faf90
256 megabytes
["8\n\n12 39 5\n\n6 8 14\n\n100 200 200\n\n3 4 6\n\n2 2 2\n\n18 27 3\n\n420 666 69\n\n987654321 123456789 999999999"]
PASSED
"""**************************************************************\ BISMILLAHIR RAHMANIR RAHIM **************************************************************** AUTHOR NAME: MD. TAHURUZZOHA TUHIN \**************************************************************""" #!/usr/bin/env python import os import sys from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush # from math import * from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # Start 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") 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() 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) # def input(): return sys.stdin.readline().rstrip("\r\n") def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def check_freq(x): freq = {} for c in set(x): freq[c] = x.count(c) return freq def numToDigit(x): box = [] while(x): tmp = x % 10 x = x//10 box.append(tmp) box.reverse() return box def ii(): return int(input()) def si(): return input() def mi(): return map(int, input().strip().split(" ")) def li(): return list(mi()) MAXX = 100000000 '''**************Solution is Here***********''' def main(): T=int(input()) for i in range(T): a,b,d=map(int,input().split()) num=1 while d%2==0: d//=2 num*=2 bitOr=a|b if bitOr%num!=0: print(-1) continue shift=(1<<30)%d count=(-bitOr*pow(shift,-1,d))%d res=(count<<30)+bitOr print(res) # End FASTIO if __name__ == "__main__": main()
1668263700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["2 1\n2 1 5 3 4"]
f4779e16e0857e6507fdde55e6d4f982
null
You are given one integer $$$n$$$ ($$$n &gt; 1$$$).Recall that a permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation of length $$$5$$$, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n = 3$$$ but there is $$$4$$$ in the array).Your task is to find a permutation $$$p$$$ of length $$$n$$$ that there is no index $$$i$$$ ($$$1 \le i \le n$$$) such that $$$p_i = i$$$ (so, for all $$$i$$$ from $$$1$$$ to $$$n$$$ the condition $$$p_i \ne i$$$ should be satisfied).You have to answer $$$t$$$ independent test cases.If there are several answers, you can print any. It can be proven that the answer exists for each $$$n &gt; 1$$$.
For each test case, print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ — a permutation that there is no index $$$i$$$ ($$$1 \le i \le n$$$) such that $$$p_i = i$$$ (so, for all $$$i$$$ from $$$1$$$ to $$$n$$$ the condition $$$p_i \ne i$$$ should be satisfied). If there are several answers, you can print any. It can be proven that the answer exists for each $$$n &gt; 1$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the permutation you have to find.
standard output
standard input
Python 3
Python
null
train_014.jsonl
50aa4e268859b2c39300847ce919ad31
256 megabytes
["2\n2\n5"]
PASSED
n = int(input()) list1 = [] a = 1 for i in range(0,n): list1.append(int(input())) for j in list1: if j%2==0: for num in range(j,0,-1): print(num,end=" ") else: print('2 3 1',end=" ") print(* [x for x in range(j,3,-1)]) if a in range(1,n): print("") a+=1
1606228500
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["100", "120"]
f0633a45bf4dffda694d0b8041a6d743
NoteThe second sample is depicted above. The red beam gets 10 + 50 + 5 + 35 + 8 + 2 = 110 points and the blue one gets 120.The red beam on the picture given in the statement shows how the laser beam can go approximately, this is just illustration how the laser beam can gain score. So for the second sample there is no such beam that gain score 110.
Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like. In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also — to make things even funnier — the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law "the angle of incidence equals the angle of reflection".
The only line of output should contain a single integer — the maximum possible score a player could gain.
The first line of the input contains three space-separated integers hl, hr, n (0 &lt; hl, hr &lt; 100, 0 ≤ n ≤ 100) — the heights of the holes and the number of the mirrors. Next n lines contain the descriptions of the mirrors. The i-th line contains space-separated vi, ci, ai, bi; the integer vi (1 ≤ vi ≤ 1000) is the score for the i-th mirror; the character ci denotes i-th mirror's position — the mirror is on the ceiling if ci equals "T" and on the floor if ci equals "F"; integers ai and bi (0 ≤ ai &lt; bi ≤ 105) represent the x-coordinates of the beginning and the end of the mirror. No two mirrors will share a common point. Consider that the x coordinate increases in the direction from left to right, so the border with the hole at height hl has the x coordinate equal to 0 and the border with the hole at height hr has the x coordinate equal to 105.
standard output
standard input
Python 2
Python
2,000
train_016.jsonl
4601f931f46377d38bfb0207cc262f5a
256 megabytes
["50 50 7\n10 F 1 80000\n20 T 1 80000\n30 T 81000 82000\n40 T 83000 84000\n50 T 85000 86000\n60 T 87000 88000\n70 F 81000 89000", "80 72 9\n15 T 8210 15679\n10 F 11940 22399\n50 T 30600 44789\n50 F 32090 36579\n5 F 45520 48519\n120 F 49250 55229\n8 F 59700 80609\n35 T 61940 64939\n2 T 92540 97769"]
PASSED
#!/usr/bin/python import sys L = 100000 a = 50.0 def getScore(uSide, lSide, uScore, lScore, d1, d2): mok = 1 finalScore = 0 for k in range(1, 2*min(len(uScore), len(lScore))+1): thisScore = 0 uValid = [1 for x in range(len(uScore))] lValid = [1 for x in range(len(lScore))] mok = - mok for j in range(1, k+1): x = ((-2*j+1)*a - d1) * L / (-2*k*a + mok * d2 - d1) if j % 2 == 1: side = lSide score = lScore valid = lValid else: side = uSide score = uScore valid = uValid pos = int(x) if side[pos] == -1 or valid[side[pos]] == 0: break else: valid[side[pos]] = 0 thisScore += score[side[pos]] else: finalScore = max(finalScore, thisScore) return finalScore h1, h2, n = [int(x) for x in raw_input().split()] upperSide = [-1 for x in range(L)] lowerSide = [-1 for x in range(L)] upperScore = [] lowerScore = [] for i in range(n): x = sys.stdin.readline().split() if x[1] == 'F': score = lowerScore side = lowerSide else: score = upperScore side = upperSide score.append(int(x[0])) for i in range(int(x[2]), int(x[3])): side[i] = len(score)-1 d1 = h1 - a d2 = h2 - a score1 = getScore(upperSide, lowerSide, upperScore, lowerScore, d1, d2) score2 = getScore(lowerSide, upperSide, lowerScore, upperScore, -d1, -d2) print max(score1, score2)
1351783800
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
3 seconds
["0\n8\n3"]
9cd7f058d4671b12b67babd38293a3fc
null
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as three integers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects and $$$w_i$$$ is the weight of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\sum n \le 10^5$$$).
standard output
standard input
PyPy 3
Python
2,000
train_041.jsonl
91eac377db5324482b95f806da962035
256 megabytes
["3\n3 20\n2 1 8\n3 1 7\n5 50\n1 3 100\n1 5 10\n2 3 123\n5 4 55\n2 100\n1 2 409"]
PASSED
import sys from heapq import heappop, heapify from collections import defaultdict input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, S = map(int, input().split()) adj = [dict() for _ in range(n+1)] for _ in range(n-1): u, v, w = map(int, input().split()) adj[u][v] = w adj[v][u] = w stack = [1] dp = [0] * (n + 1) dfs_order = [] parent = [0] * (n+1) parent[1] = 1 while stack: node = stack.pop() dfs_order.append(node) leaf = True for next_node in adj[node].keys(): if parent[next_node] == 0: parent[next_node] = node stack.append(next_node) leaf = False if leaf: dp[node] = 1 for node in reversed(dfs_order): for next_node in adj[node].keys(): if next_node != parent[node]: dp[node] += dp[next_node] moves = [] s = 0 for v, c in enumerate(dp): if v == 0 or v == 1: continue u = parent[v] w = adj[u][v] s += w * c while w > 0: moves.append((w//2 - w) * c) w //= 2 heapify(moves) ans = 0 while s - S > 0: s += heappop(moves) ans += 1 print(ans)
1596638100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["1\n3\n2\n0\n0"]
04e2e1ce3f0b4efd2d4dda69748a0a25
NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&amp;$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs.
"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i&lt;j$$$ and $$$a_i$$$ $$$\&amp;$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&amp;$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?
For every test case print one non-negative integer — the answer to the problem.
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,200
train_012.jsonl
367b7532d3a271919a07eed2bc8fdc1b
256 megabytes
["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"]
PASSED
# from bisect import bisect_left TC = int(input()) for tc in range(TC): N = int(input()) A = list(map(int, input().split())) B = [0 for _ in range(32)] for i, a in enumerate(A): B[a.bit_length()] += 1 result = 0 for b in B: if b > 1: result += b * (b - 1) // 2 print(result)
1600958100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 3\n1 2\n1 1\n2 3\n2 2\n2 1\n3 3\n3 2\n3 1"]
14a56443e48c52c118788bd5c0031b0c
NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER REWQ ASDF -&gt; FDSAZXCV VCXZ
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
For each of the p candies, print on a single line its space-separated new coordinates.
The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105). Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.
standard output
standard input
Python 2
Python
1,500
train_023.jsonl
47306be00d2d3c3742831a409b52e605
256 megabytes
["3 3 3 1 1 9\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3"]
PASSED
a=raw_input().split() n=int(a[0]) m=int(a[1]) x=int(a[2]) y=int(a[3]) z=int(a[4]) p=int(a[5]) lis=[] for i in range(p): b=raw_input().split() c=int(b[0]) d=int(b[1]) lis.append((c,d)) def flip(lis,y,p,m): for i in range(y%2): for k in range(p): lis[k]=(lis[k][0],m+1-lis[k][1]) def ro(lis,rot,p,n,m): if rot==1: for k in range(p): lis[k]=(lis[k][1],n+1-lis[k][0]) if rot==2: for k in range(p): lis[k]=(n+1-lis[k][0],m+1-lis[k][1]) if rot==3: for k in range(p): lis[k]=(m+1-lis[k][1],lis[k][0]) ro(lis,x%4,p,n,m) if x%2==1: n,m=m,n flip(lis,y,p,m) ro(lis,(0-z)%4,p,n,m) for i in lis: print i[0], i[1]
1394033400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["-1", "2"]
1b83529ea4057c76ae8483f8aa506c56
null
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).
standard output
standard input
Python 3
Python
1,500
train_046.jsonl
665f65b7d658042e5783f4b435345ed2
256 megabytes
["abc\nxyz", "abcd\ndabc"]
PASSED
from bisect import bisect_right as bl s1, s2 = input(), input() try: inv_map = {} for k, v in enumerate(s1): inv_map[v] = inv_map.get(v, []) inv_map[v].append(k) pointer = inv_map[s2[0]][0] count = 1 for i in s2[1:]: pos = bl(inv_map[i],pointer) if len(inv_map[i])==pos: count+=1 pointer = inv_map[i][0] continue pointer = inv_map[i][pos] print(count) except: print(-1)
1308582000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["4\n-1\n5\n2\n0\n1"]
2005224ffffb90411db3678ac4996f84
NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.
Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$; if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b&lt;a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$; if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b &lt; a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.
standard output
standard input
Python 3
Python
1,400
train_012.jsonl
b5faae6e6654400d6329e59b0953c7be
256 megabytes
["6\n15 5 3 2\n15 5 4 3\n15 5 2 1\n15 5 5 1\n16 7 5 2\n20 5 7 3"]
PASSED
def f(k,n,a,b): m=(k-n*b)/(a-b) if m<=0: return -1 elif m==int(m): if m-1>=n: return n else: return m-1 else: if int(m)>=n: return n else: return int(m) n=int(input()) c=[] for i in range(n): b=input().split() c.append(b) for i in c: print(int(f(int(i[0]),int(i[1]),int(i[2]),int(i[3]))))
1561559700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n0\n7\n5"]
8bbec86e427e26158393bbfbf1a067fe
NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything.
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?
For each test case print one integer — the maximum number of emeralds Polycarp can earn.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — the number of sticks and the number of diamonds, respectively.
standard output
standard input
PyPy 3
Python
1,100
train_002.jsonl
7938ffd7e31965e5f74eed446125bec1
256 megabytes
["4\n4 4\n1000000000 0\n7 15\n8 7"]
PASSED
#------------------------------what is this I don't know....just makes my mess faster-------------------------------------- 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") #----------------------------------Real game starts here-------------------------------------- #_______________________________________________________________# def fact(x): if x == 0: return 1 else: return x * fact(x-1) def lower_bound(li, num): #return 0 if all are greater or equal to answer = -1 start = 0 end = len(li)-1 while(start <= end): middle = (end+start)//2 if li[middle] >= num: answer = middle end = middle - 1 else: start = middle + 1 return answer #index where x is not less than num def upper_bound(li, num): #return n-1 if all are small or equal answer = -1 start = 0 end = len(li)-1 while(start <= end): middle = (end+start)//2 if li[middle] <= num: answer = middle start = middle + 1 else: end = middle - 1 return answer #index where x is not greater than num def abs(x): return x if x >=0 else -x def binary_search(li, val, lb, ub): ans = 0 while(lb <= ub): mid = (lb+ub)//2 #print(mid, li[mid]) if li[mid] > val: ub = mid-1 elif val > li[mid]: lb = mid + 1 else: ans = 1 break return ans def sieve_of_eratosthenes(n): ans = [] arr = [1]*(n+1) arr[0],arr[1], i = 0, 0, 2 while(i*i <= n): if arr[i] == 1: j = i+i while(j <= n): arr[j] = 0 j += i i += 1 for k in range(n): if arr[k] == 1: ans.append(k) return ans def nc2(x): if x == 1: return 0 else: return x*(x-1)//2 #_______________________________________________________________# ''' ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄███████▀▀▀▀▀▀███████▄ ░▐████▀▒▒Aestroix▒▒▀██████ ░███▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▀████ ░▐██▒▒▒▒▒KARMANYA▒▒▒▒▒▒████▌ ________________ ░▐█▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▌ ? ? |▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒| ░░█▒▒▄▀▀▀▀▀▄▒▒▄▀▀▀▀▀▄▒▒▐███▌ ? |___CM ONE DAY___| ░░░▐░░░▄▄░░▌▐░░░▄▄░░▌▒▐███▌ ? ? |▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒| ░▄▀▌░░░▀▀░░▌▐░░░▀▀░░▌▒▀▒█▌ ? ? ░▌▒▀▄░░░░▄▀▒▒▀▄░░░▄▀▒▒▄▀▒▌ ? ░▀▄▐▒▀▀▀▀▒▒▒▒▒▒▀▀▀▒▒▒▒▒▒█ ? ? ░░░▀▌▒▄██▄▄▄▄████▄▒▒▒▒█▀ ? ░░░░▄█████████ ████=========█▒▒▐▌ ░░░▀███▀▀████▀█████▀▒▌ ░░░░░▌▒▒▒▄▒▒▒▄▒▒▒▒▒▒▐ ░░░░░▌▒▒▒▒▀▀▀▒▒▒▒▒▒▒▐ ░░░░░████████████████ ''' for _ in range(int(input()) if True else 1): o, z = map(int, input().split()) print(min(o, z, (o+z)//3))
1591886100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5.0000000000", "39.2846263444"]
afcd217811ca5853179e5a936b4633fe
NoteThe optimal strategy in the first sample is to guess friends alternately.
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff.The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the i-th friend does not change between rounds and is equal to pi percent (as we know, it is directly proportional to the amount of alcohol consumed by the i-th friend) and p1 + p2 + ... + pn = 100 holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins.The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds k1, k2, ..., kn, that during round number ki Misha caught the i-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally.
Print a single real value — the expectation of the number of rounds provided that Misha plays optimally. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of Misha's friends. The second line contains n integers pi (), giving the probability to catch the i-th friend in one particular round in percent.
standard output
standard input
PyPy 3
Python
2,700
train_076.jsonl
ea801460d2e2ee74e4d930a8d2faf652
256 megabytes
["2\n50 50", "4\n50 20 20 10"]
PASSED
import random N = int(input()) prob = [float(x)/100 for x in input().strip().split()] prob_sum = [] cur = 0 for i in range(N): cur += prob[i] prob_sum.append(cur) def experiment(): cur_prob = [1.] * N cur_exp = 0 for i in range(200000): bp = [prob[i] * cur_prob[i] / (1-cur_prob[i]+1E-100) for i in range(N)] mn = max(bp) for j in range(N): if bp[j] == mn: choice = j cur_prob[choice] *= 1-prob[choice] tp = 1 for j in range(N): tp *= (1-cur_prob[j]) tp = 1 - tp cur_exp += tp return cur_exp + 1 ans = experiment() print(ans)
1454605500
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["4", "0"]
eaa768dc1024df6449e89773234cc0c3
NoteIn the first sample, one of the best permutations is $$$[1, 5, 5, 3, 10, 1, 1]$$$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array $$$[10, 20, 30, 40]$$$, we can permute it so that it becomes $$$[20, 40, 10, 30]$$$. Then on the first and the second positions the integers became larger ($$$20&gt;10$$$, $$$40&gt;20$$$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $$$2$$$. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.
standard output
standard input
Python 3
Python
1,300
train_017.jsonl
957e1a825015b4c3be9a8781b24bbba6
256 megabytes
["7\n10 1 1 1 5 5 3", "5\n1 1 1 1 1"]
PASSED
from collections import * print( int(input()) - max(Counter(map(int, input().split())).values()) )
1531492500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["22 3"]
ad50e2946470fa8e02eb70d8cef161c5
NoteConsider 6 possible routes: [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is = = .
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
The first line contains integer n (2 ≤ n ≤ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 107).
standard output
standard input
Python 2
Python
1,600
train_055.jsonl
60e6912a6b1e4ff90a09b9ba3868af8d
256 megabytes
["3\n2 3 5"]
PASSED
import sys #sys.stdin = open('in.txt', 'r') def gcd(a, b): if b == 0: return a return gcd(b, a % b) n = input() a = map(int, raw_input().split()) a.sort() s = [0 for i in xrange(n+1)] for i in xrange(n): s[i+1] += s[i] + a[i] t = s[n] for i in xrange(2, n): t += a[i-1] * (i - 1) - s[i-1] t += s[n] - s[i] - a[i-1] * (n - i) t += s[n] - s[1] - a[0] * (n - 1) t += a[n-1] * (n - 1) - s[n-1] g = gcd(t, n) print t/g, n/g
1377876600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3"]
8d911f79dde31f2c6f62e73b925e6996
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
Print a single integer denoting the minimum number of groups that will be formed in the party.
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
standard output
standard input
Python 3
Python
900
train_007.jsonl
c21c612c3a68848a8a82fb7f7c6cde97
256 megabytes
["5\n-1\n1\n2\n1\n-1"]
PASSED
""" Solution to Challenge 115A. A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B. What is the minimum number of groups that must be formed? """ import sys def solver(): """ Print the minimum number of groups that must be formed. (output). INPUT: The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers p i (1 ≤ p i ≤ n or p i = -1). Every p i denotes the immediate manager for the i-th employee. If p i is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself ( p i ≠ i). Also, there will be no managerial cycles. OUTPUT: Print a single integer denoting the minimum number of groups that will be formed in the party. """ # read input multiline inp = sys.stdin.read() # split multiline input and save in a list mylist = inp.splitlines() n = int(mylist[0]) # number of employees emp = [int(elem) for elem in mylist[1:]] # employees list (int) ans = 0 # answer counter for i in range(n): # restart counter for each employee count = 0 j = i # While when j is greater or equal 0. # This condition ensures that the loop will run at least once. while j >= 0: # We will run the loop until find the highest superior for the ith employee. j = emp[j] - 1 # update j with new manager value count += 1 # Update after each ith iteration ans = max(count, ans) print(ans) def main(): """Run solver function.""" solver() if __name__ == "__main__": main()
1316098800
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["Y 67.985071301 1.014928699\nY 0.000000000 0.000000000\nN\nY 2.000000000 2.000000000\nY 3.618033989 1.381966011\nY 997.998996990 1.001003010\nY 998.998997995 1.001002005"]
6f5d41346419901c830233b3bf5c9e65
null
Try guessing the statement from this picture: You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \cdot b = d$$$.
For each test print one line. If there is an answer for the $$$i$$$-th test, print "Y", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print "N". Your answer will be considered correct if $$$|(a + b) - a \cdot b| \le 10^{-6}$$$ and $$$|(a + b) - d| \le 10^{-6}$$$.
The first line contains $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \le d \le 10^3)$$$.
standard output
standard input
PyPy 3
Python
1,300
train_008.jsonl
542d8acdadc4b007b88f038024e3c45d
256 megabytes
["7\n69\n0\n1\n4\n5\n999\n1000"]
PASSED
for i in range(int(input())): d=int(input()) a=(d+(((d**2)-4*d)**.5))/2 b=(d-(((d**2)-4*d)**.5))/2 try: if a>=0 and b>=0: print('Y',a,b) else: print('N') except: print('N')
1542033300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["252", "0", "210"]
94559f08866b6136ba4791c440025a68
NoteIn the first example, all sequences ($$$4^4$$$) of length $$$4$$$ except the following are good: $$$[1, 1, 1, 1]$$$ $$$[2, 2, 2, 2]$$$ $$$[3, 3, 3, 3]$$$ $$$[4, 4, 4, 4]$$$ In the second example, all edges are red, hence there aren't any good sequences.
You are given a tree (a connected undirected graph without cycles) of $$$n$$$ vertices. Each of the $$$n - 1$$$ edges of the tree is colored in either black or red.You are also given an integer $$$k$$$. Consider sequences of $$$k$$$ vertices. Let's call a sequence $$$[a_1, a_2, \ldots, a_k]$$$ good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $$$a_1$$$ and ending at $$$a_k$$$. Start at $$$a_1$$$, then go to $$$a_2$$$ using the shortest path between $$$a_1$$$ and $$$a_2$$$, then go to $$$a_3$$$ in a similar way, and so on, until you travel the shortest path between $$$a_{k-1}$$$ and $$$a_k$$$. If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If $$$k=3$$$ then the following sequences are good: $$$[1, 4, 7]$$$, $$$[5, 5, 3]$$$ and $$$[2, 3, 7]$$$. The following sequences are not good: $$$[1, 4, 6]$$$, $$$[5, 5, 5]$$$, $$$[3, 7, 3]$$$.There are $$$n^k$$$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $$$10^9+7$$$.
Print the number of good sequences modulo $$$10^9 + 7$$$.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$2 \le k \le 100$$$), the size of the tree and the length of the vertex sequence. Each of the next $$$n - 1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$ and $$$x_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$x_i \in \{0, 1\}$$$), where $$$u_i$$$ and $$$v_i$$$ denote the endpoints of the corresponding edge and $$$x_i$$$ is the color of this edge ($$$0$$$ denotes red edge and $$$1$$$ denotes black edge).
standard output
standard input
PyPy 3
Python
1,500
train_004.jsonl
de26e336b7059bba58e66584a3fed71e
256 megabytes
["4 4\n1 2 1\n2 3 1\n3 4 1", "4 6\n1 2 0\n1 3 0\n1 4 0", "3 5\n1 2 1\n2 3 0"]
PASSED
""" if num edges red <= k - 1: return (n choose k) # num edges red >= k """ def n_perm_k(n, k): return n ** k def ways(xs, k): total = n_perm_k(sum(xs), k) for x in xs: total -= n_perm_k(x, k) return total def dfs(i, graph, visited): stack = [i] count = 0 while stack: current = stack.pop() count += 1 visited.add(current) for neighbor, black in graph[current].items(): if not black and neighbor not in visited: stack.append(neighbor) return count def get_forest_sizes(n, graph): visited = set() components = [] for i in range(1, n + 1): if i not in visited: ans = dfs(i, graph, visited) components.append(ans) return components def solve(n, k, graph, black_count): if black_count == 0: # no black return 0 else: return ways(get_forest_sizes(n, graph), k) n, k = map(int, input().split()) graph = { x: {} for x in range(1, n + 1) } black_count = 0 for _ in range(1, n): a, b, black = map(int, input().split()) black_count += black graph[a][b] = (black == 1) graph[b][a] = (black == 1) print(solve(n, k, graph, black_count) % (10 ** 9 + 7))
1553182500
[ "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 1 ]
1 second
["abc\ndiane\nbbcaabbba\nyouarethecutestuwuu"]
21e361d7f907f2543a616c901e60c6f2
NoteIn the first test case, each substring of "abc" occurs exactly once.In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs $$$5$$$ times, "a" and "bb" occur $$$3$$$ times each, and each of the remaining substrings occurs exactly once.
You are given an integer $$$n$$$. Find any string $$$s$$$ of length $$$n$$$ consisting only of English lowercase letters such that each non-empty substring of $$$s$$$ occurs in $$$s$$$ an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
For each test case, print a single line containing the string $$$s$$$. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_087.jsonl
4015c11356857e55f65cb7cea3e598ad
256 megabytes
["4\n3\n5\n9\n19"]
PASSED
import itertools import queue import math import sys from collections import * from random import * #sys.setrecursionlimit(99999) eps = sys.float_info.epsilon P = 2 INF = 1e9 + 1 MOD = 1000000007 def is_prime(n): if n == 0 or n == 1: return False d = 2 while d * d <= n: if n % d == 0: return False d += 1 return True def div_up(n, k): if n % k == 0: return n // k else: return n // k + 1 def num_len(n, base): if n == 0: return 1 res = 0 while n: res += 1 n //= 10 return res def dfs_sample(graph, cl, p, v): cl[v] = 1 for to in graph[v]: if cl[to] == 1 and p[v] != to: # yay, cycle pass elif cl[to] == 0: p[to] = v dfs_sample(graph, cl, p, to) cl[v] = 2 def down(a): for i in range(1, len(a)): if a[i] > a[i - 1]: return False return True def up(a): for i in range(1, len(a)): if a[i] < a[i - 1]: return False return True def code(c): return ord(c) - 32 def _hash_(s): res, p = 0, 1 for i in range(len(s)): res += (code(s[i]) * p) res %= MOD p *= P p %= MOD return res % MOD def remove_edge(v, u, graph): graph[v].remove(u) graph[u].remove(v) def all_eq(a): for i in range(1, len(a)): if a[i] != a[i - 1]: return False return True def ok(s): for i in range(len(s)): for j in range(i, len(s)): if s.count(s[i:j+1]) % 2 == 0: return False return True def solve(): n = int(input()) if n == 1: print('a') return if n % 2 == 0: print('a' * (n // 2) + 'b' + 'a' * (n // 2 - 1)) else: n -= 1 print('a' * (n // 2) + 'b' + 'a' * (n // 2 - 1) + 'c') for _ in range(int(input())): solve() def debug(): pass # debug()
1627569300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["0\n0\n4\n4\n12\n990998587\n804665184"]
43ace9254c5d879d11e3484eacb0bcc4
NoteIt's easy to see that the answer for RDB of level $$$1$$$ or $$$2$$$ is $$$0$$$.The answer for RDB of level $$$3$$$ is $$$4$$$ since there is only one claw we can choose: $$$\{1, 2, 3, 4\}$$$.The answer for RDB of level $$$4$$$ is $$$4$$$ since we can choose either single claw $$$\{1, 3, 2, 4\}$$$ or single claw $$$\{2, 7, 5, 6\}$$$. There are no other claws in the RDB of level $$$4$$$ (for example, we can't choose $$$\{2, 1, 7, 6\}$$$, since $$$1$$$ is not a child of center vertex $$$2$$$). Rooted Dead Bush of level 4.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level $$$n$$$ as a rooted tree constructed as described below.A rooted dead bush of level $$$1$$$ is a single vertex. To construct an RDB of level $$$i$$$ we, at first, construct an RDB of level $$$i-1$$$, then for each vertex $$$u$$$: if $$$u$$$ has no children then we will add a single child to it; if $$$u$$$ has one child then we will add two children to it; if $$$u$$$ has more than one child, then we will skip it. Rooted Dead Bushes of level $$$1$$$, $$$2$$$ and $$$3$$$. Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw: The center of the claw is the vertex with label $$$1$$$. Lee has a Rooted Dead Bush of level $$$n$$$. Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $$$10^9+7$$$.
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo $$$10^9 + 7$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^6$$$) — the level of Lee's RDB.
standard output
standard input
PyPy 3
Python
1,900
train_006.jsonl
3e28bedf4a6ff9813d8f457a0ba529da
256 megabytes
["7\n1\n2\n3\n4\n5\n100\n2000000"]
PASSED
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase import threading from math import floor from bisect import bisect_right from collections import Counter from math import gcd mod=10**9+7 def main(): size=2*10**6+1 ans=[0]*(size) a=0 b=0 for i in range(1,2*10**6+1): # if i<10: # print(i,a,b) a,b=b,b+2*a if i%3==0: b+=1 a%=mod b%=mod ans[i]=b for _ in range(int(input())): # print(ans[:10]) n=int(input()) print(ans[n]*4%mod) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
1592921100
[ "math", "trees", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 1 ]
2 seconds
["2\n4\n12"]
f79a926e18a3f81b24f2fc3ae5c8f928
null
You have a list of numbers from $$$1$$$ to $$$n$$$ written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are $$$1$$$-indexed). On the $$$i$$$-th step you wipe the $$$i$$$-th number (considering only remaining numbers). You wipe the whole number (not one digit). When there are less than $$$i$$$ numbers remaining, you stop your algorithm. Now you wonder: what is the value of the $$$x$$$-th remaining number after the algorithm is stopped?
Print $$$T$$$ integers (one per query) — the values of the $$$x$$$-th number after performing the algorithm for the corresponding queries.
The first line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The next $$$T$$$ lines contain queries — one per line. All queries are independent. Each line contains two space-separated integers $$$n$$$ and $$$x$$$ ($$$1 \le x &lt; n \le 10^{9}$$$) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $$$x$$$ numbers.
standard output
standard input
PyPy 3
Python
800
train_013.jsonl
81159d31a78b33f9ecdc3075459229c9
256 megabytes
["3\n3 1\n4 2\n69 6"]
PASSED
import sys import math from collections import defaultdict,deque input = sys.stdin.readline def inar(): return [int(el) for el in input().split()] def main(): t=int(input()) for _ in range(t): n,x=inar() print(x*2) if __name__ == '__main__': main()
1563115500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5\n1 2 3 4 5", "2\n4 5", "1\n1"]
a704760d5ccd09d08558ea98d6007835
null
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions: Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel. For any integer i (1 ≤ i &lt; k), there is exactly one ski track leading from object vi. This track goes to object vi + 1. The path contains as many objects as possible (k is maximal). Help Valera. Find such path that meets all the criteria of our hero!
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects. The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel. The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
standard output
standard input
Python 2
Python
1,500
train_008.jsonl
9fb81725092eebfb874539680a7c25c8
256 megabytes
["5\n0 0 0 0 1\n0 1 2 3 4", "5\n0 0 1 0 1\n0 1 2 2 4", "4\n1 0 0 0\n2 3 4 2"]
PASSED
from collections import Counter n = input() v = [int(i) for i in raw_input().split()] a = [int(i) for i in raw_input().split()] cnt = Counter(a) pf = {} hotels = [] for i in range(len(a)): if v[i] == 1: hotels.append(i+1) if a[i] == 0: continue pf[i+1] = a[i] mp = [] for h in hotels: now = h path = [h] while pf.has_key(now): now = pf[now] if cnt[now] > 1: break path.append(now) if len(path) > len(mp): mp = path mp.reverse() print len(mp) print ' '.join(str(i) for i in mp)
1380641400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2 2 2\n7 5 3\n-1\n0 0 2"]
b43dee2f223c869a35b1b11ceb9d2b6b
null
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples: if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$$$; if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$$$; if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows.
For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.
Th first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of windows in the building.
standard output
standard input
Python 3
Python
900
train_023.jsonl
c432da3d979221707206cef5a29b7d7d
256 megabytes
["4\n30\n67\n4\n14"]
PASSED
for i in range(int(input())): n=int(input()) if n==1: print(-1) if n==2: print(-1) if n==4: print(-1) if n//3==(n-2)/3 and n>4: print(int(n//3-1),1,0) if n//3==n/3: print(int(n/3),0,0) elif n//3==(n-1)/3 and n>4: print(int(n//3-2),0,1)
1602407100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0.6250000000\n0.5312500000"]
92feda270834af751ca37bd80083aafa
null
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: Determine the probability with which an aim can be successfully hit by an anvil.You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 &lt; a &lt; 10, 0 ≤ b &lt; 10.
standard output
standard input
Python 3
Python
1,800
train_000.jsonl
ced6afd8e24e4094feee1568c8dd79d7
256 megabytes
["2\n4 2\n1 2"]
PASSED
for i in range(int(input())): a, b = map(int, input().split()) print(0.5 + a / (b << 4) if 4 * b > a else 1 - b / a if a else 1)
1303226100
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["3 2", "3 3"]
4a55e76aa512b8ce0f3f84bc6da3f86f
NoteConsider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.
Print two space-separated integers — the maximum possible and the minimum possible result of the game.
The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.
standard output
standard input
Python 2
Python
2,200
train_034.jsonl
d53024926b076561090d577dcfecb21a
256 megabytes
["5\n1 2\n1 3\n2 4\n2 5", "6\n1 2\n1 3\n3 4\n1 5\n5 6"]
PASSED
def readlist(f): return map(f, raw_input().split()) def readint(): return int(raw_input()) def printlist(l): print ' '.join(map(str, l)) N = readint() E = [[] for i in range(N)] for i in range(N-1): u, v = readlist(int) u -= 1 v -= 1 E[u].append(v) E[v].append(u) F = [None]*N C = [[] for i in range(N)] S = [0] while len(S) > 0: u = S.pop() for v in E[u]: if v != F[u]: F[v] = u C[u].append(v) S.append(v) pol = [0]*N pol[0] = 1 S.append(0) while len(S) > 0: u = S.pop() for v in C[u]: pol[v] = -pol[u] S.append(v) NB = [0]*N M = 0 for i in range(N): if len(C[i]) == 0: M += 1 S.append(i) NB[i] = 1 done = [0]*N res1 = [0]*N res2 = [0]*N while len(S) > 0: u = S.pop() if len(C[u]) > 0: if pol[u] > 0: res2[u] = 0 for v in C[u]: res2[u] += res2[v] + 1 res2[u] -= 1 res1[u] = 0 for v in C[u]: res1[u] = max(res1[u], NB[u] - (NB[v] - res1[v])) else: res1[u] = NB[u] - 1 for v in C[u]: res1[u] -= (NB[v] - res1[v]) res1[u] += 1 res2[u] = N-1 for v in C[u]: res2[u] = min(res2[u], res2[v]) if F[u] != None: done[F[u]] += 1 NB[F[u]] += NB[u] if done[F[u]] == len(C[F[u]]): S.append(F[u]) print res1[0]+1, res2[0]+1
1430064000
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
2 seconds
["0 0\n\n\n\n3 1\n\n\n\n2 3\n\n\n\n4 4\n\n\n\n0 2\n\n\n\n1 3 4 1"]
574347ab83379e5b08618d2b275b0d96
NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.The following picture illustrates the first test.
This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities: Exactly n dwarves entered completely dark cave. Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information. The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.
null
null
standard output
standard input
Python 3
Python
1,900
train_008.jsonl
70d242f3d4bad87349b71ff235ef01b9
256 megabytes
["5\n\n\n\nblack\n\n\n\nblack\n\n\n\nwhite\n\n\n\nwhite\n\n\n\nblack"]
PASSED
n=int(input()) print(1,0) c=input() n-=1 L=1 R=999999999 while n>0: M=int((L+R)/2) print(1,M) if input()==c: L=M+1 else: R=M n-=1 print(0,R,2,R-1)
1539511500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1", "3"]
71cead8cf45126902c518c9ce6e5e186
null
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: he chooses two elements of the array ai, aj (i ≠ j); he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
standard output
standard input
Python 2
Python
1,300
train_004.jsonl
0fbcc88897ff6dfeefbf7a553dd6c5c6
256 megabytes
["2\n2 1", "3\n1 4 1"]
PASSED
def solve(n, a): s = sum(a) if s % n == 0: return n return n-1 n = int(raw_input()) a = map(int, raw_input().split()) print solve(n, a)
1353511800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["5\n18\n10\n6\n75015"]
43b8e9fb2bd0ec5e0250a33594417f63
NoteIn the first test case, Santa can give $$$3$$$ and $$$2$$$ candies to kids. There $$$a=2, b=3,a+1=3$$$.In the second test case, Santa can give $$$5, 5, 4$$$ and $$$4$$$ candies. There $$$a=4,b=5,a+1=5$$$. The answer cannot be greater because then the number of kids with $$$5$$$ candies will be $$$3$$$.In the third test case, Santa can distribute candies in the following way: $$$[1, 2, 2, 1, 1, 2, 1]$$$. There $$$a=1,b=2,a+1=2$$$. He cannot distribute two remaining candies in a way to be satisfied.In the fourth test case, Santa can distribute candies in the following way: $$$[3, 3]$$$. There $$$a=3, b=3, a+1=4$$$. Santa distributed all $$$6$$$ candies.
Santa has $$$n$$$ candies and he wants to gift them to $$$k$$$ kids. He wants to divide as many candies as possible between all $$$k$$$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has $$$a$$$ candies and the kid who recieves the maximum number of candies has $$$b$$$ candies. Then Santa will be satisfied, if the both conditions are met at the same time: $$$b - a \le 1$$$ (it means $$$b = a$$$ or $$$b = a + 1$$$); the number of kids who has $$$a+1$$$ candies (note that $$$a+1$$$ not necessarily equals $$$b$$$) does not exceed $$$\lfloor\frac{k}{2}\rfloor$$$ (less than or equal to $$$\lfloor\frac{k}{2}\rfloor$$$). $$$\lfloor\frac{k}{2}\rfloor$$$ is $$$k$$$ divided by $$$2$$$ and rounded down to the nearest integer. For example, if $$$k=5$$$ then $$$\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$$$.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer $$$t$$$ independent test cases.
For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^9$$$) — the number of candies and the number of kids.
standard output
standard input
PyPy 3
Python
900
train_002.jsonl
e3986c08bf98a582883c36ce23440295
256 megabytes
["5\n5 2\n19 4\n12 7\n6 2\n100000 50010"]
PASSED
for _ in range(int(input())): x, y = map(int, input().split()) print(x - max(0, x % y - y // 2))
1577552700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n3\n3\n4"]
3581b3a6bf7b122b49c481535491399d
NoteThe picture corresponding to the first test case of the example:There you can remove vertices $$$2$$$, $$$5$$$ and $$$3$$$ during the first move and vertices $$$1$$$, $$$7$$$ and $$$4$$$ during the second move.The picture corresponding to the second test case of the example:There you can remove vertices $$$7$$$, $$$8$$$ and $$$9$$$ during the first move, then vertices $$$5$$$, $$$6$$$ and $$$10$$$ during the second move and vertices $$$1$$$, $$$3$$$ and $$$4$$$ during the third move.The picture corresponding to the third test case of the example:There you can remove vertices $$$5$$$ and $$$7$$$ during the first move, then vertices $$$2$$$ and $$$4$$$ during the second move and vertices $$$1$$$ and $$$6$$$ during the third move.
You are given a tree (connected graph without cycles) consisting of $$$n$$$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles.In one move, you can choose exactly $$$k$$$ leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves $$$u_1, u_2, \dots, u_k$$$ that there are edges $$$(u_1, v)$$$, $$$(u_2, v)$$$, $$$\dots$$$, $$$(u_k, v)$$$ and remove these leaves and these edges.Your task is to find the maximum number of moves you can perform if you remove leaves optimally.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer — the maximum number of moves you can perform if you remove leaves optimally.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le k &lt; n$$$) — the number of vertices in the tree and the number of leaves you remove in one move, respectively. The next $$$n-1$$$ lines describe edges. The $$$i$$$-th edge is represented as two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$ and $$$y_i$$$ are vertices the $$$i$$$-th edge connects. It is guaranteed that the given set of edges forms a tree. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
standard output
standard input
PyPy 3
Python
2,300
train_011.jsonl
4b689ae5017bfa30bc5e1afef8a2fa4e
256 megabytes
["4\n8 3\n1 2\n1 5\n7 6\n6 8\n3 1\n6 4\n6 1\n10 3\n1 2\n1 10\n2 3\n1 5\n1 6\n2 4\n7 10\n10 9\n8 10\n7 2\n3 1\n4 5\n3 6\n7 4\n1 2\n1 4\n5 1\n1 2\n2 3\n4 3\n5 3"]
PASSED
from collections import defaultdict,deque import sys input=sys.stdin.readline t=int(input()) for ii in range(t): graph=defaultdict(list) n,k=map(int,input().split()) st=[] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) if k==1: print(n-1) else: leaves=deque() for i in graph: if len(graph[i])==1: leaves.append(i) #print(leaves) treecount=[0]*(n+1) for i in leaves: treecount[i]=-1 ans=0 #print(graph) while leaves: size=len(leaves) for j in range(size): vertex=leaves.popleft() treecount[vertex]=10000000 for i in graph[vertex]: if treecount[i]!=-1 and treecount[i]<10000000: treecount[i]+=1 #print(i,treecount,'aa',treecount[i]%k,treecount[i],k) if treecount[i]%k==0 : ans+=1 #print(ans,i,'aaa') if treecount[i]==len(graph[i])-1: pos=0 for kj in graph[i]: if treecount[kj]==10000000: pos+=1 #print(pos,i) if pos==len(graph[i])-1: treecount[i]=-1 leaves.append(i) else: sys.stdout.write(str(min(ans,n-1))+'\n') #-1 ->leaves, 0 -> inner nodes, 10000000 -> visited nodes
1594996500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
a99f5e08f3f560488ff979a3e9746e7f
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.
standard output
standard input
Python 3
Python
1,200
train_006.jsonl
ed01f95b2750d1680e1e7293d3af8764
256 megabytes
["3", "4"]
PASSED
def f(n): if n==2: return True for i in range(2,int(n**0.5)+1): if n%i==0: return False return True s=int(input()) if s>2: print(2) q=[1]*(s) for i in range(2,s+2): if f(i): q[i-2]=2 print(' '.join([str(w)for w in q])) elif s==1: print(1) print(1) else: print(1) print('1 1')
1487861100
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2\n1\n2\n1"]
dd2cd365d7afad9c2b5bdbbd45d87c8a
NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students.
You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that: No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$); the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.
For each query, print the answer on it — the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.
standard output
standard input
Python 3
Python
800
train_003.jsonl
2e6885cd9e46112ca90c1b1c0ea47575
256 megabytes
["4\n4\n2 10 1 20\n2\n3 6\n5\n2 3 4 99 100\n1\n42"]
PASSED
q=int(input()) while q>0: q-=1 n=int(input()) a=list(map(int,input().split())) a.sort() s=1 z=1 i=0 while i<(n-1): if (a[i]-a[i+1])==-1: z=2 s=max(z,s) i+=1 z=1 print(s)
1571754900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\n1000000007\n0 1 \n1 2 3", "YES\n3\n0 1 \n1 2", "NO"]
ddd246cbbd038ae3fc54af1dcb9065c3
NoteBy we denote the remainder of integer division of b by c.It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≤ k ≤ 1018, 1 ≤ ai ≤ 1018, 1 ≤ bi ≤ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula:Vasya wrote down matrix v on a piece of paper and put it in the table.A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible.
If the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer k (1 ≤ k ≤ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively. In the third line print n integers a1, a2, ..., an (0 ≤ ai ≤ 1018), separated by spaces. In the fourth line print m integers b1, b2, ..., bm (0 ≤ bi ≤ 1018), separated by spaces.
The first line contains integers n and m (1 ≤ n, m ≤ 100), separated by a space — the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≤ wi, j ≤ 109), separated by spaces — the elements of the i-th row of matrix w.
standard output
standard input
Python 3
Python
2,200
train_048.jsonl
ed496b6bd0cf54e4f3ac2a82ffcef1b7
256 megabytes
["2 3\n1 2 3\n2 3 4", "2 2\n1 2\n2 0", "2 2\n1 2\n2 1"]
PASSED
def main(): n, m = map(int, input().split()) l = list(tuple(map(int, input().split())) for _ in range(n)) ma = max(x for _ in l for x in _) bb = l[0] x = bb[0] aa = [_[0] - x for _ in l] err = set(map(abs, filter(None, (a + b - x for a, row in zip(aa, l) for b, x in zip(bb, row))))) if err: k = err.pop() if err or k <= ma: print('NO') return else: k = ma + 1 for i in range(n): aa[i] %= k print('YES') print(k) print(*aa) print(*bb) if __name__ == '__main__': main()
1422705600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0", "13"]
2b6645cde74cc9fc6c927a6b1e709852
NoteFrom the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence. The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left.
standard output
standard input
Python 2
Python
2,300
train_049.jsonl
5119f26afc0c035c7e28724db037a174
256 megabytes
["2\n1 1", "3\n3 4 2"]
PASSED
from sys import stdin from itertools import repeat def main(): n = int(stdin.readline()) a = map(int, stdin.readline().split()) mod = 10 ** 9 + 7 for i in xrange(n): a[i] -= 1 lo, v = a[0], 0 px = a[0] ans = a[0] for x in a[1:]: if px > x: lo, v = x, (min(lo, x) * v + x) % mod else: lo, v = px, (min(lo, px) * v + px) % mod ans = (ans + lo * v + x) % mod px = x print ans main()
1459353900
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"]
ca835eeb8f24de8860d6f5ac6c0af55d
NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column.
Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$.
For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall.
The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_097.jsonl
348bbd4d1769cd2578ec53497701444c
256 megabytes
["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"]
PASSED
t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) s = list(input()) if s[0] == '1': rw = [1] cn = [True] cnt = 1 ans = [2] else: rw = [0] cn = [False] cnt = 0 ans = [0] k = 0 for i in range(1, m): if s[i] == '1': cnt += 1 cn += [True] rw += [1] k = m else: cn += [False] rw += [rw[-1]] k -= 1 ans += [cnt + rw[-1]] for i in range(m, m * n): if s[i] == '1': if not cn[i % m]: cnt += 1 cn[i % m] = True k = m rw[i % m] += 1 elif k > 0: rw[i % m] += 1 k -= 1 ans += [cnt + rw[i % m]] print(' '.join(map(str, ans)))
1652020500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["10", "1", "4", "4", "2", "7"]
f4a7c573ca0c129f241b415577a76ac2
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
standard output
standard input
PyPy 3-64
Python
2,000
train_107.jsonl
e698e4010a0efc3ee49288a155a11e18
256 megabytes
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
PASSED
n = int(input()) arr = list(map(int, input().split())) min_two = [100000000, 100000000] result = 100000000 for i in range(n): if i < n - 1: x, y = arr[i], arr[i + 1] big, small = max(x, y), min(x, y) if big < small * 2: cnt = big - small big -= cnt * 2 small -= cnt cnt += (big + small) // 3 + (1 if (big + small) % 3 else 0) result = min(result, cnt) else: result = min(result, big // 2 + big % 2) min_two.append(arr[i] // 2 + arr[i] % 2) min_two = sorted(min_two)[0:2] if 0 < i < n - 1 and arr[i - 1] and arr[i + 1]: total = arr[i - 1] + arr[i + 1] cnt = total // 2 + total % 2 result = min(result, cnt) result = min(sum(min_two), result) print(result)
1651502100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4 8\n10 5\n8 8\n10 6\n10 2\n1 8\n7 8\n10 6", "1 3\n2 1\n1 3"]
8f64c179a883047bf66ee14994364580
NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. In the second example, no dancers collide.
Wherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (xi, 0), moves in positive y direction (upwards); Horizontal: stands at (0, yi), moves in positive x direction (rightwards). According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.
Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.
The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
standard output
standard input
Python 3
Python
1,900
train_001.jsonl
79e64c8079a75fa5e70a0c8718e7b366
256 megabytes
["8 10 8\n1 1 10\n1 4 13\n1 7 1\n1 8 2\n2 2 0\n2 5 14\n2 6 0\n2 6 1", "3 2 3\n1 1 2\n2 1 1\n1 1 5"]
PASSED
from collections import namedtuple Dancer = namedtuple('Dancer', ['category', 'x', 'y', 'idx', 'group']) def read_dancer(idx): group, pos, time = [int(x) for x in input().split(' ')] x, y = None, None if group == 1: x, y = pos, 0 else: x, y = 0, pos return Dancer(time-pos, x, y, idx, group) n, w, h = [int(x) for x in input().split(' ')] dancers = [read_dancer(idx) for idx in range(n)] dancers_in = sorted(dancers, key = lambda d: (d.category, -d.group, d.x, -d.y)) dancers_out = sorted(dancers, key = lambda d: (d.category, d.group, d.x, -d.y)) end_pos = [None for _ in range(n)] def get_end_pos(dancer): x, y = None, None if dancer.x == 0: x, y = w, dancer.y else: x, y = dancer.x, h return (x, y) for i in range(n): end_pos[dancers_in[i].idx] = get_end_pos(dancers_out[i]) for i in range(n): print(*end_pos[i])
1504272900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["-2\n-2\n-5\n4\n-1"]
7eae40835f6e9580b985d636d5730e2d
NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$.
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows: $$$a_1 = -1$$$ $$$a_2 = 2$$$ $$$a_3 = -3$$$ $$$a_4 = 4$$$ $$$a_5 = -5$$$ And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!
Print $$$q$$$ lines, each containing one number — the answer to the query.
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the descriptions of the queries.
standard output
standard input
PyPy 2
Python
900
train_024.jsonl
6a22b44bf3a95bf6e6e58e0ddae3dca1
256 megabytes
["5\n1 3\n2 5\n5 5\n4 4\n2 3"]
PASSED
from __future__ import division from sys import stdin, stdout def write(x): stdout.write(str(x) + "\n") q = int(stdin.readline()) for _ in xrange(q): l, r = map(int, stdin.readline().split()) elements = r - l + 1 if elements % 2 == 0: res = elements // 2 if l % 2 == 0: write(-res) else: write(res) else: res = elements // 2 if l % 2 == 0: write(-res + r) else: write(res - r)
1543044900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3", "-1", "2"]
a746bd2a212167ea85d00ffebd73fd9c
NoteIn the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices.Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.
If it is impossible to obtain a chain from the given graph, print  - 1. Otherwise, print the maximum possible number of edges in the resulting chain.
The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes.
standard output
standard input
PyPy 3
Python
2,600
train_019.jsonl
5e1ad00cb4c58cb6528f94491b22e465
256 megabytes
["5 4\n1 2\n2 3\n3 4\n3 5", "4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4", "4 2\n1 3\n2 4"]
PASSED
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [] distance = [maxValue]*n cc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i innerCc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i en distinto orden for i in range(0, n): if distance[i] == maxValue: ccLen = bfs_2k(graph, i, distance,cc) if(ccLen==None): print(-1) return diameters.append(distance[cc[ccLen-1]] if ccLen > 0 else 0) for v in range(0,ccLen): innerDist = [maxValue]*n bfs_2k(graph, cc[v], innerDist,innerCc) diameters[-1] = max(diameters[-1], innerDist[innerCc[ccLen-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist,cc): queue = deque() queue.append(initVertex) dist[initVertex] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen]=v ccLen+=1 if (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve()
1430668800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["3\n4\n2\n7"]
0aa7c678bc06b0a305155b4a31176366
null
You are given $$$n$$$ segments on a coordinate axis $$$OX$$$. The $$$i$$$-th segment has borders $$$[l_i; r_i]$$$. All points $$$x$$$, for which $$$l_i \le x \le r_i$$$ holds, belong to the $$$i$$$-th segment.Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.Two segments $$$[l_i; r_i]$$$ and $$$[l_j; r_j]$$$ are non-intersecting if they have no common points. For example, segments $$$[1; 2]$$$ and $$$[3; 4]$$$, $$$[1; 3]$$$ and $$$[5; 5]$$$ are non-intersecting, while segments $$$[1; 2]$$$ and $$$[2; 3]$$$, $$$[1; 2]$$$ and $$$[2; 2]$$$ are intersecting.The segment $$$[l_i; r_i]$$$ lies inside the segment $$$[l_j; r_j]$$$ if $$$l_j \le l_i$$$ and $$$r_i \le r_j$$$. For example, segments $$$[2; 2]$$$, $$$[2, 3]$$$, $$$[3; 4]$$$ and $$$[2; 4]$$$ lie inside the segment $$$[2; 4]$$$, while $$$[2; 5]$$$ and $$$[1; 4]$$$ are not.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3000$$$) — the number of segments. The next $$$n$$$ lines describe segments. The $$$i$$$-th segment is given as two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$), where $$$l_i$$$ is the left border of the $$$i$$$-th segment and $$$r_i$$$ is the right border of the $$$i$$$-th segment. Additional constraint on the input: there are no duplicates in the list of segments. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3000$$$ ($$$\sum n \le 3000$$$).
standard output
standard input
PyPy 2
Python
2,300
train_007.jsonl
bd0af4785d19e9b3c44b0e59240fb814
256 megabytes
["4\n4\n1 5\n2 4\n2 3\n3 4\n5\n1 5\n2 3\n2 5\n3 5\n2 2\n3\n1 3\n2 4\n2 3\n7\n1 10\n2 8\n2 5\n3 4\n4 4\n6 8\n7 7"]
PASSED
import sys #sys.stdin=open("data.txt") input=sys.stdin.readline def solve(seg): # compress coordinates co=[] for a,b,_ in seg: co.append(a) co.append(b) co=sorted(set(co)) d={j:i for i,j in enumerate(co)} # get the best non-overlap answer dp=[0]*(len(co)+1) lo=0 for a,b,v in sorted(seg): a=d[a] b=d[b]+1 while lo<a: if dp[lo+1]<dp[lo]: dp[lo+1]=dp[lo] lo+=1 if dp[b]<dp[a]+v: dp[b]=dp[a]+v #print(seg,max(dp)) return max(dp) for _ in range(int(input())): n=int(input()) seg=[] for _ in range(n): a,b=map(int,input().split()) seg.append([b-a,a,b]) seg.append([10**6,0,10**6]) seg.sort() dp=[0]*(n+1) allow=[] for i in range(n+1): # find the answer for the range [s1,s2] _,s1,s2 = seg[i] dp[i]=solve([(s3,s4,v) for s3,s4,v in allow if s1<=s3<=s4<=s2])+1 allow.append((s1,s2,dp[i])) print(max(dp)-1)
1596638100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n2\n0\n1"]
b4183febe5ae61770368d2e16f273675
NoteConsider the queries of the example test. in the first query, the substring is baa, which can be changed to bac in one operation; in the second query, the substring is baacb, which can be changed to cbacb in two operations; in the third query, the substring is cb, which can be left unchanged; in the fourth query, the substring is aa, which can be changed to ba in one operation.
Let's call the string beautiful if it does not contain a substring of length at least $$$2$$$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You are given a string $$$s$$$ of length $$$n$$$, each character of the string is one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You have to answer $$$m$$$ queries — calculate the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.
For each query, print a single integer — the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the number of queries. The second line contains the string $$$s$$$, it consists of $$$n$$$ characters, each character one of the first $$$3$$$ Latin letters. The following $$$m$$$ lines contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — parameters of the $$$i$$$-th query.
standard output
standard input
PyPy 3-64
Python
1,600
train_088.jsonl
18fb96a11cab9dcacc259de1cfe2bb45
256 megabytes
["5 4\nbaacb\n1 3\n1 5\n4 5\n2 3"]
PASSED
a = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] stt = [3, 5, 1, 4, 0, 2] stt2 = [[3, 4, 0], [5, 2, 1], [1, 5, 2], [4, 0, 3], [0, 3, 4], [2, 1, 5]] # def query(l, r): # minimum = 9999999 # for ii in range(6): # if r >= n-1: # minimum = min(minimum, dp[l][ii]) # else: # pos = ii # time = (r-l+1)%3 # for k in range(time): # pos = stt[pos] # print(ii, pos) # minimum = min(minimum, dp[l][ii] - dp[r+1][pos]) # return minimum n, m = [int(x) for x in input().split(' ')] s = input() # s = 'c'*200000 ss =[ ord(x)-96 for x in s] dp = [[0 for i in range(6)] for j in range(n)] # DP here for ii in range(6): if a[ii][0] != ss[n-1]: dp[n-1][ii] = 1 for ii in range(n-2, -1, -1): for jj in range(6): dp[ii][jj] = dp[ii+1][stt[jj]] if a[jj][0] != ss[ii]: dp[ii][jj] += 1 res = [] for t in range(m): l, r = [int(x)-1 for x in input().split(' ')] # print(query(l, r)) minimum = 9999999 if r >= n-1: for ii in range(6): minimum = min(dp[l]) res.append(minimum) else: pos = (r-l) % 3 minimum = min([dp[l][ii] - dp[r+1][stt2[ii][pos]] for ii in range(6)]) res.append(minimum) # print(minimum) print(*res, sep = "\n")
1627655700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["0.666666666667"]
7b932b2d3ab65a353b18d81cf533a54e
null
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
A single line contains four integers .
standard output
standard input
Python 3
Python
1,300
train_000.jsonl
bfe1a027fe00a570cda1e07ea006e7bd
256 megabytes
["1 2 1 2"]
PASSED
a,b,c,d=list(map(int,input().split())) print((a/b)/(1-(1-(a/b))*(1-(c/d))))
1369582200
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["YES\nYES\nNO"]
6ae754639d96790c890f9d1ab259332a
NoteFor $$$n=2$$$, Phoenix can create a square like this: For $$$n=4$$$, Phoenix can create a square like this: For $$$n=6$$$, it is impossible for Phoenix to create a square.
Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below. A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?
For each test case, if Phoenix can create a square with the $$$n$$$ puzzle pieces, print YES. Otherwise, print NO.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of puzzle pieces.
standard output
standard input
Python 3
Python
1,000
train_097.jsonl
b13f6f8f2f9a0076a40b7d36ef0d61db
256 megabytes
["3\n2\n4\n6"]
PASSED
t = int(input()) import math for j in range(1, t + 1): n = int(input()) if n % 2 != 0: print("NO") elif n % 2 == 0: n = n // 2 if math.sqrt(n)%1==0: print("YES") elif n % 2 == 0: n = n // 2 if math.sqrt(n)%1==0: print("YES") else: print("NO") else: print("NO") else: print("NO")
1619966100
[ "number theory", "geometry", "math" ]
[ 0, 1, 0, 1, 1, 0, 0, 0 ]
3 seconds
["333333338\n141946947\n329622137"]
206a9a83a1d143a1a8d8d3a7512f59e2
NoteExplanation of the first sample test case:Let's write out all possible sequences of light toggles, which will make the device complete its operation: $$$(1, 2)$$$  — $$$2$$$ lights are turned on $$$(1, 3, 2)$$$  — $$$3$$$ lights are turned on $$$(2, 1)$$$  — $$$2$$$ lights are turned on $$$(2, 3)$$$  — $$$2$$$ lights are turned on $$$(3, 2)$$$  — $$$2$$$ lights are turned on $$$(3, 1, 2)$$$  — $$$3$$$ lights are turned on Then the final expected value will be equal to $$$\frac{2}{6}$$$ + $$$\frac{3}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{2}{6}$$$ + $$$\frac{3}{6}$$$ = $$$\frac{14}{6}$$$ = $$$\frac{7}{3}$$$. Then the required output will be $$$333333338$$$, since $$$333333338 \cdot 3 \equiv 7 \pmod{10^9+7}$$$.
To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of $$$n$$$ lights arranged in a row. The device functions in the following way:Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any $$$k$$$ consecutive lights contain more than one turned on light, then the device finishes working.William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.
For each test case print the answer, 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}$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The only line for each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 10^5$$$), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.
standard output
standard input
PyPy 3-64
Python
2,600
train_082.jsonl
67f46963a9391958f0258af511247aa8
256 megabytes
["3\n3 2\n15 2\n40 15"]
PASSED
import os, sys from io import BytesIO, IOBase from collections import defaultdict, deque, Counter from bisect import bisect_left, bisect_right from heapq import heappush, heappop from functools import lru_cache from itertools import accumulate import math import sys # sys.setrecursionlimit(10 ** 6) # Fast IO Region BUFSIZE = 8192 # class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # # sys.setrecursionlimit(800) ii = lambda: int(input()) mii = lambda: map(int, input().split()) fii = lambda: map(float, input().split()) lmii = lambda: list(map(int, input().split())) i2c = lambda n: chr(ord('a') + n) c2i = lambda c: ord(c) - ord('a') mod = 10 ** 9 + 7 def rev(n, mod=10 ** 9 + 7): r = 1 while n > 1: b = mod // n n = n * (b + 1) - mod r *= b + 1 r %= mod return r def solve(): n, k = mii() T, F = 1, 1 res = 0 for p in range(1, n): if k * (p - 1) + 1 > n: break T = T * (n - p + 1) % mod if p == 1: F = n else: for i in range(n - (k - 1) * (p - 2), n - (k - 1) * (p - 1), -1): F = (F * rev(i)) % mod for i in range(n - (k - 1) * (p - 2) - p + 1, n - (k - 1) * (p - 1) - p, -1): F = (F * i) % mod # for i in range(n - (k - 1) * (p - 1), n - (k - 1) * (p - 1) - p, -1): # F = (F * i) % mod res += F * rev(T) % mod res %= mod print(res + 1) for _ in range(ii()): solve()
1622385300
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
1 second
["1\n2\n5\n3 3 3 1 2"]
ac248c83c99d8a2262772816b5f4ac6e
NoteIn the first case, adding $$$1$$$ candy to all bags except of the second one leads to the arrangement with $$$[2, 2]$$$ candies.In the second case, firstly you use first three operations to add $$$1+2+3=6$$$ candies in total to each bag except of the third one, which gives you $$$[7, 8, 3]$$$. Later, you add $$$4$$$ candies to second and third bag, so you have $$$[7, 12, 7]$$$, and $$$5$$$ candies to first and third bag  — and the result is $$$[12, 12, 12]$$$.
There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \le m \le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.
For each testcase, print two lines with your answer. In the first line print $$$m$$$ ($$$1\le m \le 1000$$$) — the number of operations you want to take. In the second line print $$$m$$$ positive integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), where $$$a_j$$$ is the number of bag you chose on the $$$j$$$-th operation.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \le n\le 100$$$).
standard output
standard input
Python 3
Python
800
train_009.jsonl
4758625c1fd03dbac28aafdcc7ce1e09
256 megabytes
["2\n2\n3"]
PASSED
t = int(input()) def solve(): n = int(input()) print(n) arr = list(range(1, n + 1)) arr = [str(i) for i in arr] print(" ".join(arr)) for i in range(t): solve()
1605450900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1\n3"]
adf024899fb2a684427463733358566a
NoteIn the first test case Alice has to swap $$$1$$$ and $$$2$$$. After that Bob removes the last digit, $$$1$$$, so the answer is $$$2$$$.In the second test case Alice can swap $$$3$$$ and $$$1$$$: $$$312$$$. After that Bob deletes the last digit: $$$31$$$. Then Alice swaps $$$3$$$ and $$$1$$$: $$$13$$$ and Bob deletes $$$3$$$, so the answer is $$$1$$$.
There is an integer $$$n$$$ without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.You have to find the smallest integer Alice can get in the end, if she plays optimally.
For each test case output a single integer — the smallest integer Alice can get in the end of the game.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$10 \le n \le 10^9$$$) — the integer for the game. $$$n$$$ does not have zeros in its decimal representation.
standard output
standard input
PyPy 3-64
Python
800
train_103.jsonl
ebd44a27bba39d1853585e060b7bf395
256 megabytes
["3\n\n12\n\n132\n\n487456398"]
PASSED
for _ in range(int(input())): n = list(map(int, ' '.join(input()).split())) if len(n) > 2: print(min(n)) else: print(n[-1])
1652970900
[ "math", "games", "strings" ]
[ 1, 0, 0, 1, 0, 0, 1, 0 ]
1 second
["1\n3 \n2\n2 1", "2\n3 6\n4\n1 2 4 5"]
fab438cef9eb5e9e4a4a2e3f9e4f9cec
NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total.
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?
In the first line print a single integer $$$n$$$ ($$$0 \leq n \leq a$$$) — the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \leq m \leq b$$$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \ldots, q_m$$$ ($$$1 \leq q_i \leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.
The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \leq a, b \leq 10^{9}$$$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.
standard output
standard input
Python 3
Python
1,600
train_015.jsonl
d052e7cc2614c8ade1dc11ca1b67014d
256 megabytes
["3 3", "9 12"]
PASSED
def check(): a, b = [int(s) for s in input().split()] a1 = min(a, b) b1 = max(a, b) sum0=0 i=0 while(sum0<=a1): i += 1 sum0+=i ax=i-1 sum1=sum0-i r=a1-sum1 if(r==0): sum0 = 0 i = i - 1 while (sum0 <= b1): i += 1 sum0 += i sum2 = sum0 - i ay = i - 1 if(a<=b): print(ax) for i in range(1,ax+1): print(i,end=" ") if(i==ax): print() if (ax == 0): print( ) print(ay-ax) for j in range(ax+1,ay+1): print(j,end=" ") if(j==ay): print() if (ay - ax == 0): print( ) else: print(ay - ax) for j in range(ax + 1, ay + 1): print(j, end=" ") if(j==ay): print() if (ay - ax == 0): print( ) print(ax) for i in range(1,ax+1): print(i, end=" ") if(i==ax):print() if (ax == 0): print( ) else: c=ax+1-r sum0=0 i=ax+1 b1=b1-c while(sum0<=b1): i += 1 sum0+=i ay = i - 1 if a<=b : print(ax) for i in range(1,ax+2): if i==c: continue print(i,end=" ") if(i==ax+1):print() if(ax==0): print( ) print(ay-ax) print(c,end=" ") for j in range(ax+2,ay+1): print(j,end=" ") if(j==ay): print() if(ay-ax==0): print( ) else: print(ay - ax) print(c, end=" ") for j in range(ax + 2, ay + 1): print(j, end=" ") if(j==ay):print() if(ay-ax==0): print( ) print(ax) for i in range(1, ax + 2): if i == c: continue print(i, end=" ") if(i==ax+1): print() if(ax==0): print( ) check()
1540109400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["b\naabbbabaa\nbbbb\nabbaaa"]
351ffff1dfe1bc1762f062f612463759
NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.
You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.
For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.
standard output
standard input
PyPy 3-64
Python
900
train_108.jsonl
80f3dbd9137db63a32ebd0e5be8f924f
256 megabytes
["4\nb\naabbbabaa\nabbb\nabbaab"]
PASSED
import sys inpu = sys.stdin.readline prin = sys.stdout.write for _ in range(int(inpu())) : s = inpu().rstrip('\n') ab = s.count('ab') ba = s.count('ba') s = list(s) if ab > ba: s[-1] = 'a' elif ba > ab : s[-1] = 'b' prin(''.join(map(str, s)) + '\n')
1635518100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
5953b898995a82edfbd42b6c0f7138af
null
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
standard output
standard input
PyPy 3
Python
1,500
train_000.jsonl
699af83fb5e7dcd991f7e65beaa54eea
256 megabytes
["7\n1\n2\n6\n13\n14\n3620\n10000"]
PASSED
def main(): q = int(input()) for _ in [0]*q: n = int(input()) nn = n res = [0]*50 p = pow(3,49) idx = 49 ma = -1 while n != 0: if n >= p: pr = n//p res[idx] = pr n -= pr*p if pr == 2 and ma == -1: ma = idx p = p//3 idx -= 1 for i in range(ma,50): if res[i] == 2: res[i] = 0 res[i+1] += 1 if ma == -1: print(nn) else: ans = 0 p = pow(3,49) idx = 49 while idx >= ma: if res[idx] == 1: ans += p p = p//3 idx -= 1 print(ans) if __name__ == '__main__': main()
1571754900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["16\n16\n4\n9\n64\n9\n64\n40000"]
3bb093fb17d6b76ae340fab44b08fcb8
NoteBelow are the answers for the first two test cases:
Find the minimum area of a square land on which you can place two identical rectangular $$$a \times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally, You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 100$$$) — positive integers (you are given just the sizes, but not their positions). Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding. The picture shows a square that contains red and green rectangles.
Print $$$t$$$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $$$a \times b$$$.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) —the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — side lengths of the rectangles.
standard output
standard input
PyPy 2
Python
800
train_002.jsonl
f2364062305578c1119af021d4563f6d
256 megabytes
["8\n3 2\n4 2\n1 1\n3 1\n4 7\n1 3\n7 4\n100 100"]
PASSED
import atexit import io import sys import math from collections import defaultdict _INPUT_LINES = sys.stdin.read().splitlines() raw_input = iter(_INPUT_LINES).next _OUTPUT_BUFFER = io.BytesIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) t=int(raw_input()) for i in range(t): a,b=map(int,raw_input().split()) if a>b: a,b=b,a print pow(max(2*a,b),2)
1590327300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2 3", "2 6", "-1"]
eba76d0491f88ac8d8450e457610b067
null
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal.Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.If there is no possible sequence then output -1.
If the answer exists then output k numbers — resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
The first line consists of two numbers n and k (1 ≤ n, k ≤ 1010).
standard output
standard input
Python 3
Python
1,900
train_004.jsonl
c34323ca47130ab761d999430febecd3
256 megabytes
["6 3", "8 2", "5 3"]
PASSED
import math n, k = map(int, input().split()) Ans = [] if n < (k+1)*k//2: print(-1) else: d = n nd = 1 for i in range(int(math.sqrt(n)), 1, -1): if n%i == 0: if i > nd and n//i >=(k+1)*k//2: nd = i if n//i > nd and i >=(k+1)*k//2: nd = n//i d = n//nd for x in range(1, k): Ans.append(nd*x) d -= x Ans.append(d*nd) if len(Ans) != 0: print(*Ans) else: print(-1)
1493391900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n1\n1", "2\n2\n2\n2\n2"]
3a767b3040f44e3e2148cdafcb14a241
NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3. If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses. If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p &lt; x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.
Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.
standard output
standard input
Python 3
Python
1,100
train_042.jsonl
500194f3c55c3bb001e3a1e50a3203d8
256 megabytes
["3\n1 2 3", "5\n1 1 5 1 1"]
PASSED
def main(): n, l, v = int(input()), input().split(), 0 for i, a in enumerate(l): v ^= ord(a[-1]) - 1 l[i] = (('2', '1')[v & 1]) print('\n'.join(l)) if __name__ == '__main__': main()
1470578700
[ "math", "games" ]
[ 1, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3", "5"]
3992602be20a386f0ec57c51e14b39c5
NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case: In the first day Anastasia collects 8 pebbles of the third type. In the second day she collects 8 pebbles of the fourth type. In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. In the fourth day she collects 7 pebbles of the fifth type. In the fifth day she collects 1 pebble of the second type.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.
standard output
standard input
Python 3
Python
1,100
train_009.jsonl
a5423dac3e76300c3a7c7831a307e0e4
256 megabytes
["3 2\n2 3 4", "5 4\n3 1 8 9 7"]
PASSED
n, k = map(int, input().split()) w = list(map(int, input().split())) q=0 t=0 for i in range(n): a=w[i]//k w[i]%=k q+=(a//2) t+=(a%2) # print(a, w[i], t, q) if t==2: t=0 q+=1 if w[i]>0: if t==1: t=0 w[i]=0 q+=1 else: w[i]=0 t+=1 if t>0: q+=1 print(q)
1490803500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
6 seconds
["4", "2", "14", "1", "120"]
96fe0cd25dc0f6a76ebeb43834bae8de
null
You are given a tree, consisting of $$$n$$$ vertices. Each edge has an integer value written on it.Let $$$f(v, u)$$$ be the number of values that appear exactly once on the edges of a simple path between vertices $$$v$$$ and $$$u$$$.Calculate the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$1 \le v &lt; u \le n$$$.
Print a single integer — the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$v &lt; u$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^5$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains three integers $$$v, u$$$ and $$$x$$$ ($$$1 \le v, u, x \le n$$$) — the description of an edge: the vertices it connects and the value written on it. The given edges form a tree.
standard output
standard input
PyPy 3-64
Python
2,300
train_087.jsonl
7c70d412cc7c61bc0c1692ea9b7c66d8
1024 megabytes
["3\n1 2 1\n1 3 2", "3\n1 2 2\n1 3 2", "5\n1 4 4\n1 2 3\n3 4 4\n4 5 5", "2\n2 1 1", "10\n10 2 3\n3 8 8\n4 8 9\n5 8 5\n3 10 7\n7 8 2\n5 6 6\n9 3 4\n1 6 3"]
PASSED
input = __import__('sys').stdin.readline n = int(input()) adj = [[] for _ in range(n)] for _ in range(n-1): u, v, x = map(lambda x: int(x)-1, input().split()) adj[u].append((v, x)) adj[v].append((u, x)) TRAVERSE = 0 UPDATE_DP = 1 prev_node_stack = [[0] for _ in range(n)] prev_node = [0]*n sz = [1]*n dp_root = [0]*n dp_remove = [0]*n stack = [(TRAVERSE, (0, -1, 0))] while len(stack) > 0: state, param = stack.pop() if state == TRAVERSE: u, par, i = param if i < len(adj[u]) and adj[u][i][0] == par: i += 1 if i < len(adj[u]): v, x = adj[u][i] stack.append((TRAVERSE, (u, par, i+1))) stack.append((UPDATE_DP, (v, u, x))) stack.append((TRAVERSE, (v, u, 0))) prev_node_stack[x].append(v) if state == UPDATE_DP: v, u, x = param prev_node_stack[x].pop() sz[u] += sz[v] prev_node[v] = prev_node_stack[x][-1] if prev_node[v] == 0: dp_root[x] += sz[v] else: dp_remove[prev_node[v]] += sz[v] # print('prev_node', prev_node) # print('dp_root', dp_root) # print('dp_remove', dp_remove) ans = sum((sz[v] - dp_remove[v]) * (sz[prev_node[v]] - (dp_root[x] if prev_node[v] == 0 else dp_remove[prev_node[v]])) for u in range(n) for v, x in adj[u] if sz[u] > sz[v]) print(ans)
1653316500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["11", "1001"]
bcf75978c9ef6202293773cf533afadf
NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?
Print the n-th even-length palindrome number.
The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).
standard output
standard input
PyPy 3
Python
1,000
train_023.jsonl
dcfbf68f75aeed09adecdda29a8f97d8
256 megabytes
["1", "10"]
PASSED
s = input() print(s + ''.join(reversed(s)))
1467219900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES", "NO", "NO"]
113ae625e67c8ea5ab07be44c3b58a8f
null
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.
Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.
The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.
standard output
standard input
Python 3
Python
1,500
train_006.jsonl
9fdc67b1d35071ca736835762e199bc1
256 megabytes
["11\n10", "1\n01", "000\n101"]
PASSED
s1 = input() s2 = input() if len(s1) != len(s2): print("NO") exit() elif len(s1) == 1: if s1 != s2: print("NO") else: print("YES") exit() elif s1 == s2: print("YES") exit() if (s1.count("1") != 0) and (s2.count("1") != 0): print("YES") else: print("NO")
1363188600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2"]
a1631f068c8da218243a9ab0aced4f16
null
Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing n nodes and n - 1 edges. We will consider the tree nodes numbered by integers from 1 to n.Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers a, b, c and d such that: 1 ≤ a &lt; b ≤ n; 1 ≤ c &lt; d ≤ n; there's no such node that lies on both the shortest path from node a to node b and from node c to node d. The shortest path betweem two nodes is the path that is shortest in the number of edges.Help Polo solve this problem.
In a single line print a single integer — the answer to the problem. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator.
The first line contains integer n (1 ≤ n ≤ 80000) — the number of tree nodes. Each of the following n - 1 lines contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) — the i-th edge of the tree. It is guaranteed that the given graph is a tree.
standard output
standard input
Python 2
Python
2,400
train_035.jsonl
a3f396ce90df85dc8747e777579d7ee9
256 megabytes
["4\n1 2\n2 3\n3 4"]
PASSED
n=input() e=[[] for i in range(0,n+10)] sz,f=[0]*(n+10),[0]*(n+10) s=[] ans=n*n*(n-1)*(n-1)/4 for i in xrange(1,n): u,v=map(int,raw_input().split()) e[u].append(v) e[v].append(u) q=[1] for i in xrange(0,n): u=q[i] for v in e[u]: if (v==f[u]): continue q.append(v) f[v]=u for i in reversed(xrange(0,n)): u=q[i] sz[u]+=1 sz[f[u]]+=sz[u] su=sz[u]*(sz[u]-1)/2-sum(sz[v]*(sz[v]-1)/2 for v in e[u] if (v!=f[u])) ans-=su*(su+2*(n-sz[u])*sz[u]) print ans
1364916600
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["6\n1\n9999999966"]
adcd813d4c45337bbd8bb0abfa2f0e00
NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.
You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x &lt; m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.
Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a &lt; m \le 10^{10}$$$).
standard output
standard input
PyPy 3
Python
1,800
train_002.jsonl
ece9037a7d3ed495182e3f0819d92139
256 megabytes
["3\n4 9\n5 10\n42 9999999967"]
PASSED
import math def cal(x, y, z): return z // x - y // x T = int(input()) while T: T -= 1 a, m = map(int, input().split()) k = math.gcd(a, m) x = (m - 1) // k n = m // k i = 2 p = [] while i * i <= m // k: if n % i == 0: while n % i == 0: n //= i p.append(i) i += 1 if n > 1: p.append(n) res = 0 for mask in range(1, 1<<len(p)): tmp = 1 cnt = 0 for i in range(len(p)): if mask & (1<<i): tmp *= p[i] cnt += 1 if cnt % 2 == 1: res += cal(tmp, a//k, a//k + x) else: res -= cal(tmp, a//k, a//k + x) print(x + 1 - res) #Участник 165 место, s34vv1nd
1580308500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["2 3\n1 2\n1 1"]
7af4eee2e9f60283c4d99200769c77ec
NoteIn the first case, for $$$i = 2$$$ and $$$j = 3$$$ the equality holds true for all $$$k$$$: $$$k = 1$$$: $$$|a_2 - a_1| + |a_1 - a_3| = |2 - 5| + |5 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 2$$$: $$$|a_2 - a_2| + |a_2 - a_3| = |2 - 2| + |2 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 3$$$: $$$|a_2 - a_3| + |a_3 - a_3| = |2 - 7| + |7 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$.
You are given an array $$$a_1, a_2, \ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \leq i, j \leq n$$$ such that, for all $$$1 \leq k \leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.
For each test case, print a single line with two space-separated indices $$$i$$$ and $$$j$$$ which form a good pair of the array. The case $$$i=j$$$ is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
800
train_091.jsonl
42f9289222c3a343ac244d76a9b3a84f
256 megabytes
["3\n\n3\n\n5 2 7\n\n5\n\n1 4 2 2 3\n\n1\n\n2"]
PASSED
t = int(input()) for _ in range(t): n = int(input()) li = list(map(int,input().split())) i = li.index(min(li)) + 1 j = li.index(max(li)) + 1 print(i,j)
1648132500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6\n9\n5\n0\n116461800"]
875851f43c7a6e09cd3d20f2a6980d40
NoteHere are the pairs for the first test case:
Berland year consists of $$$m$$$ months with $$$d$$$ days each. Months are numbered from $$$1$$$ to $$$m$$$. Berland week consists of $$$w$$$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $$$w$$$ days.A pair $$$(x, y)$$$ such that $$$x &lt; y$$$ is ambiguous if day $$$x$$$ of month $$$y$$$ is the same day of the week as day $$$y$$$ of month $$$x$$$.Count the number of ambiguous pairs.
Print $$$t$$$ integers — for each testcase output the number of pairs $$$(x, y)$$$ such that $$$x &lt; y$$$ and day $$$x$$$ of month $$$y$$$ is the same day of the week as day $$$y$$$ of month $$$x$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$m$$$, $$$d$$$ and $$$w$$$ ($$$1 \le m, d, w \le 10^9$$$) — the number of months in a year, the number of days in a month and the number of days in a week.
standard output
standard input
PyPy 3
Python
2,200
train_053.jsonl
2cf8e7e0fc5f92884a9357ac811ab4b5
256 megabytes
["5\n6 7 4\n10 7 12\n12 30 7\n1 1 1\n3247834 10298779 625324"]
PASSED
def GCD(x, y): while(y):x,y=y,x%y return x for i in ' '*int(input()): m,d,w=map(int,input().split()) m=min(m,d) g=GCD(d-1,w) ww=w//g k=m//ww print(k*m-k*(k+1)//2*ww)
1596033300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["5\n2 1\n3 2\n5 3\n5 4\n6 5", "12\n2 1\n4 1\n5 4\n6 5\n7 1\n7 4\n8 3\n8 5\n9 3\n9 6\n10 4\n10 7"]
5a0f578ef7e9e9f28ee0b5b19be2ca76
null
Vus the Cossack has a simple graph with $$$n$$$ vertices and $$$m$$$ edges. Let $$$d_i$$$ be a degree of the $$$i$$$-th vertex. Recall that a degree of the $$$i$$$-th vertex is the number of conected edges to the $$$i$$$-th vertex.He needs to remain not more than $$$\lceil \frac{n+m}{2} \rceil$$$ edges. Let $$$f_i$$$ be the degree of the $$$i$$$-th vertex after removing. He needs to delete them in such way so that $$$\lceil \frac{d_i}{2} \rceil \leq f_i$$$ for each $$$i$$$. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges!
In the first line, print one integer $$$k$$$ ($$$0 \leq k \leq \lceil \frac{n+m}{2} \rceil$$$) — the number of edges which you need to remain. In each of the next $$$k$$$ lines, print two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^6$$$, $$$0 \leq m \leq 10^6$$$) — the number of vertices and edges respectively. Each of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$) — vertices between which there is an edge. It is guaranteed that the graph does not have loops and multiple edges. It is possible to show that the answer always exists.
standard output
standard input
PyPy 2
Python
2,400
train_036.jsonl
2988cd95461f2897a821d65472a2da25
256 megabytes
["6 6\n1 2\n2 3\n3 4\n4 5\n5 3\n6 5", "10 20\n4 3\n6 5\n4 5\n10 8\n4 8\n5 8\n10 4\n9 5\n5 1\n3 8\n1 2\n4 7\n1 4\n10 7\n1 7\n6 1\n9 6\n3 9\n7 9\n6 2"]
PASSED
from __future__ import print_function from sys import stdin inp = [int(x) for x in stdin.read().split()] n, m = inp[0], inp[1] in_idx = 2 n += 1 adj = [[] for _ in range(n)] edge_index = [[] for _ in range(n)] for i in range(m): a = inp[in_idx] in_idx += 1 b = inp[in_idx] in_idx += 1 adj[a].append(b) edge_index[a].append(i) adj[b].append(a) edge_index[b].append(i) deg = [len(adj[node]) for node in range(n)] for x in range(n): if deg[x] & 1: adj[0].append(x) edge_index[0].append(m) deg[0] += 1 adj[x].append(0) edge_index[x].append(m) deg[x] += 1 m += 1 used_edge = [False] * m out = [] for node in range(n): if deg[node]: path = [] while deg[node]: path.append(node) while deg[node]: deg[node] -= 1 nxt_node = adj[node].pop() idx = edge_index[node].pop() if used_edge[idx] == False: used_edge[idx] = True node = nxt_node break pre = False for i in range(1, len(path)): b = path[i] a = path[i - 1] removed = False if not a or not b: removed = True elif i + 1 < len(path) and not path[i + 1]: removed = False elif not pre and i & 1 == 0: removed = True if removed == False: out.append('%d %d' % (a, b)) pre = removed print(len(out)) print('\n'.join(out))
1561710000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4\n10\n143922563\n698570404"]
d8066e517678dfd6a11f2bfa9e0faed0
NoteIn the first test case, it can be proven that the maximum $$$F(a)$$$ among all good arrays $$$a$$$ is equal to $$$2$$$. The excellent arrays are: $$$[2, 1, 2]$$$; $$$[0, 3, 2]$$$; $$$[2, 3, 2]$$$; $$$[3, 0, 1]$$$.
Let's call an integer array $$$a_1, a_2, \dots, a_n$$$ good if $$$a_i \neq i$$$ for each $$$i$$$.Let $$$F(a)$$$ be the number of pairs $$$(i, j)$$$ ($$$1 \le i &lt; j \le n$$$) such that $$$a_i + a_j = i + j$$$.Let's say that an array $$$a_1, a_2, \dots, a_n$$$ is excellent if: $$$a$$$ is good; $$$l \le a_i \le r$$$ for each $$$i$$$; $$$F(a)$$$ is the maximum possible among all good arrays of size $$$n$$$. Given $$$n$$$, $$$l$$$ and $$$r$$$, calculate the number of excellent arrays modulo $$$10^9 + 7$$$.
For each test case, print the number of excellent arrays modulo $$$10^9 + 7$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$, and $$$r$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$-10^9 \le l \le 1$$$; $$$n \le r \le 10^9$$$). It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,300
train_094.jsonl
a5bb98103cda5b3e586b09c2486192b8
256 megabytes
["4\n3 0 3\n4 -3 5\n42 -33 55\n69 -42 146"]
PASSED
from sys import stdin, stdout import sys # 1 2 3 4 # # 1+k, 2+k | 3-k, 4-k # 1-k >= l => k <= 1-l # n+k <= r => k <= r-n # if k <= min(1-l, r-n) # then C(n,n/2) even, C(n,n/2) + C(n, n/2+1) # MOD = 1000000007 def bpow(a, b): global MOD if b == 0: return 1 c = bpow(a, b//2) c *= c c %= MOD if b % 2 == 1: c *= a c %= MOD return c def factorial(): global MOD fa = [1] for i in range(1, 200001): fa.append(fa[-1]*i) fa[-1] %= MOD return fa def inv(fa): global MOD iv = [1] for i in range(1, 200001): iv.append(bpow(fa[i], MOD-2)) return iv def C(fa, iv, a, b): if a < b or a < 0 or b < 0: return 0 global MOD r = fa[a] * iv[a-b] r %= MOD r *= iv[b] r %= MOD return r def solve(n, l, r): global MOD, fa, iv res = 0 k = min(1-l, r-n) if k >= 1: res = k * C(fa, iv, n, n//2) res %= MOD if n % 2 == 1: res += k * C(fa, iv, n, n//2 + 1) res %= MOD # 1 2 3 4 lf = 1 rt = n while True: k += 1 #lf = max(1, l + k) #rt = min(n, r - k) while lf - k < l: lf += 1 while rt + k > r: rt -= 1 if rt - lf + 1 < 0: break res += C(fa, iv, rt - lf + 1, n//2 - lf + 1) res %= MOD if n % 2 == 1: res += C(fa, iv, rt - lf + 1, n//2 + 1 - lf + 1) res %= MOD return res try: fa = factorial() iv = inv(fa) t = int(stdin.readline()) for _ in range(t): n, l, r = map(int, stdin.readline().split()) res = solve(n, l, r) stdout.write(str(res) + '\n') except: print(sys.exc_info())
1626273300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1.5 seconds
["4\n8\n2\n2"]
79ecf771f4a54c2c9f988e069f7bfceb
NoteIn the first example, one valid way to select the elements is $$$[\underline{1}, 2, \underline{3}, \underline{4}, \underline{5}]$$$. All subsegments satisfy at least one of the criteria. For example, for the subsegment $$$l = 1$$$, $$$r = 2$$$ we have that the element $$$2$$$ is not selected, satisfying the first criterion. For the subsegment $$$l = 3$$$, $$$r = 5$$$ we have $$$3 + 4 + 5 = 12 \ge 2 \cdot 3$$$, satisfying the second criterion.We can't select all elements, because in this case for $$$l = 1$$$, $$$r = 2$$$ all elements are selected and we have $$$a_1 + a_2 = 3 &lt; 2 \cdot 2$$$. Thus, the maximum number of selected elements is $$$4$$$.In the second example, one valid solution is $$$[\underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}]$$$.In the third example, one valid solution is $$$[\underline{-10}, -5, \underline{-10}]$$$.In the fourth example, one valid solution is $$$[\underline{9}, \underline{9}, -3]$$$.
You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ and an integer $$$x$$$.You need to select the maximum number of elements in the array, such that for every subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ containing strictly more than one element $$$(l &lt; r)$$$, either: At least one element on this subsegment is not selected, or $$$a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1)$$$.
For each test case, print one integer: the maximum number of elements that you can select.
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10$$$): the number of test cases. The descriptions of $$$t$$$ test cases follow, three lines per test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 50\,000$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100\,000 \leq a_i \leq 100\,000$$$). The third line contains one integer $$$x$$$ ($$$-100\,000 \leq x \leq 100\,000$$$).
standard output
standard input
PyPy 3
Python
2,000
train_101.jsonl
417e5354077a49943fc76ea8463e6911
256 megabytes
["4\n5\n1 2 3 4 5\n2\n10\n2 4 2 4 2 4 2 4 2 4\n3\n3\n-10 -5 -10\n-8\n3\n9 9 -3\n5"]
PASSED
inf=float("inf") for _ in range(int(input())): n=int(input()) xx=[int(x) for x in input().split()] x=int(input()) m=inf a=0 for i in range(n): a+=1 if xx[i]+m<x*a: xx[i]=inf m=inf a=0 else: if m+xx[i] - x*a < xx[i] - x : m=m+xx[i] else: m=xx[i] a=1 print(n-xx.count(inf))
1640792100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["FTT\n\nTTF", "FTFF\n\nTTTT\n\nTFTT"]
f4a5815ecbdf744b80791cf728abf8c6
NoteThe empty lines in the example are just for you to better understand the interaction process. You're not required to print them.In the first example, there are $$$3$$$ questions, and the answer to each question is 'true', 'true', and 'false', respectively. The first query, guessing the answers to be 'false', 'true', and 'true', respectively, guesses only one question — the $$$2$$$-nd question — correctly. Then, in the second query, the program correctly guesses the answer key. The interaction ends here. In the second example, there are $$$4$$$ questions, and the answer to each question is 'true', 'false', 'true', and 'true', respectively. The first query guessed none of the questions correctly, resulting in the answer $$$0$$$. The second query guessed the $$$1$$$-st, $$$3$$$-rd, and $$$4$$$-th question correctly, resulting in the answer $$$3$$$. In the third query, the program correctly guesses the answer key. Then, the interaction ends.
Mark is administering an online exam consisting of $$$n$$$ true-false questions. However, he has lost all answer keys. He needs a way to retrieve the answers before his client gets infuriated.Fortunately, he has access to the grading system. Thus, for each query, you can input the answers to all $$$n$$$ questions, and the grading system will output how many of them are correct.He doesn't have much time, so he can use the grading system at most $$$675$$$ times. Help Mark determine the answer keys.Note that answer keys are fixed in advance and will not change depending on your queries.
null
The first line of the input consists of an integer $$$n$$$ ($$$1\leq n\leq 1000$$$) — the number of questions.
standard output
standard input
PyPy 3-64
Python
2,900
train_100.jsonl
ca36f072329928a1e913611d4699aa74
256 megabytes
["3\n\n1\n\n3", "4\n\n0\n\n3\n\n4"]
PASSED
#from math import ceil, floor #, gcd, log, factorial, comb, perm, #log10, log2, log, sin, asin, tan, atan, #from heapq import heappop,heappush,heapify #heappop(hq), heapify(list) #from collections import defaultdict as dd #mydd=dd(list) for .append #from collections import deque as dq #deque e.g. myqueue=dq(list) #append/appendleft/appendright/pop/popleft import sys input = sys.stdin.readline #sys.setrecursionlimit(100000) #default is 1000 ############ ---- Input Functions ---- ############ def inp(): return(int(input())) #def inlt(): # return(list(map(int,input().split()))) #.split(','), default is space def insr(): s = input().strip("\n") return(list(s)) #def invr(): # return(map(int,input().split())) #################################################### #1) inp — For taking integer inputs. #2) inlt — For taking List inputs. #3) insr — For taking string inputs. Returns a List of Characters. #4) invr — For taking space seperated integer variable inputs. #################################################### def solve(): n=inp() s1=['T']*n;s2=['T','F']*(n//2)+['T']*(n%2) print("".join(s1));sys.stdout.flush() a1=inp() if a1==n:return print("".join(s2));sys.stdout.flush() a2=inp() if a2==n:return ans=[] for i in range(n//3): s1[3*i]='F';s1[3*i+1]='F' print("".join(s1));sys.stdout.flush() ax=inp() if ax==n:return if ax-a1==2: ans.append('FF') s1[3*i+2]='F' print("".join(s1));sys.stdout.flush() ay=inp() if ay==n:return if ay>ax: ans.append('F') else: ans.append('T') elif a1-ax==2: ans.append('TT') s1[3*i+2]='F' print("".join(s1));sys.stdout.flush() ay=inp() if ay==n:return if ay>ax: ans.append('F') else: ans.append('T') else: if i%2==0: s2[3*i],s2[3*i+1],s2[3*i+2]='F','T','F' else: s2[3*i],s2[3*i+1],s2[3*i+2]='T','F','T' print("".join(s2));sys.stdout.flush() az=inp() if az==n:return if az-a2==3: ans.append(s2[3*i]+s2[3*i+1]+s2[3*i]) elif a2-az==3: ans.append(s2[3*i+1]+s2[3*i]+s2[3*i+1]) elif az-a2==1: ans.append(s2[3*i]+s2[3*i+1]+s2[3*i+1]) else: ans.append(s2[3*i+1]+s2[3*i]+s2[3*i]) s1[3*i],s1[3*i+1],s1[3*i+2]='T','T','T' if i%2==0: s2[3*i],s2[3*i+1],s2[3*i+2]='T','F','T' else: s2[3*i],s2[3*i+1],s2[3*i+2]='F','T','F' for i in range(3*(n//3),n): s1[i]='F' print("".join(s1));sys.stdout.flush() ax=inp() if ax==n:return if ax>a1: ans.append('F') else: ans.append('T') s1[i]='T' print("".join(ans));sys.stdout.flush() solve() #print(*ans,sep=' ')##print("{:.3f}".format(ans)+"%") #:b binary :% eg print("{:6.2%}".format(ans)) #print(" ".join(str(i) for i in ans)) #print(" ".join(map(str,ans))) #seems faster #prefixsum a=[a1...an] #psa=[0]*(n+1) #for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x+1] e.g. sum 1st 5 items in psa[5] #ASCII<->number ord('f')=102 chr(102)='f' #def binary_search(li, val, lb, ub): # while ((ub-lb)>1): # mid = (lb + ub) // 2 # if li[mid] >= val: # ub = mid # else: # lb = mid # return lb+1 #return index of elements <val in li #def binary_search(li, val, lb, ub): # ans = -1 # while (lb <= ub): # mid = (lb + ub) // 2 # if li[mid] > val: # ub = mid - 1 # elif val > li[mid]: # lb = mid + 1 # else: # ans = mid # return index # break # return ans ########## #def pref(li): # pref_sum = [0] # for i in li: # pref_sum.append(pref_sum[-1] + i) # return pref_sum ########## #def suff(li): # suff_sum = [0] # for i in range(len(li)-1,-1,-1): # suff_sum.insert(0,suff_sum[0] + li[i]) # return suff_sum ############# #def maxSubArraySumI(arr): #Kadane's algorithm with index # max_till_now=arr[0];max_ending=0;size=len(arr) # start=0;end=0;s=0 # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending: # max_till_now=max_ending # start=s;end=i # if max_ending<0: # max_ending=0 # s=i+1 # return max_till_now,start,end ############# avoid max for 2 elements - slower than direct if #def maxSubArraySum(arr): #Kadane's algorithm # max_till_now=arr[0];max_ending=0;size=len(arr) # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending:max_till_now=max_ending # if max_ending<0:max_ending=0 # return max_till_now ############# #def findbits(x): # tmp=[] # while x>0:tmp.append(x%2);x//=2 # tmp.reverse() # return tmp ##############Dijkstra algorithm example #dg=[999999]*(n+1);dg[n]=0;todo=[(0,n)];chkd=[0]*(n+1) #while todo:#### find x with min dg in todo # _,x=hq.heappop(todo) # if chkd[x]:continue # for i in coming[x]:going[i]-=1 # for i in coming[x]: # tmp=1+dg[x]+going[i] # if tmp<dg[i]:dg[i]=tmp;hq.heappush(todo,(dg[i],i)) # chkd[x]=1 ################ ## moves to match 2 binary strings: sum_{i=1}^n(abs(diff in i-th prefix sums)) ############### ##s=[2, 3, 1, 4, 5, 3] ##sorted(range(len(s)), key=lambda k: s[k]) ##gives sorted indices [2, 0, 1, 5, 3, 4] ##m= [[3, 4, 6], [2, 4, 8], [2, 3, 4], [1, 2, 3], [7, 6, 7], [1, 8, 2]] ##m.sort(reverse=True,key=lambda k:k[2]) #sorts m according to 3rd elements
1657892100
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["cfmailru", "NO"]
02fe37c2e31ca4e278d493fc2e3e35e0
NoteOne can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.
Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.
The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.
standard output
standard input
Python 3
Python
2,000
train_017.jsonl
bdef7a376f448f5856521e8115c34918
256 megabytes
["4\nmail\nai\nlru\ncf", "3\nkek\npreceq\ncheburek"]
PASSED
def cm(s1,s2): for i in range(1, len(s1)): if s1[:i] == s2[-i:] : s = s2 + s1[i:] if len(s) == len(set(list(s))): return s if s2[:i] == s1[-i:]: s = s1 + s2[i:] if len(s) == len(set(list(s))): return s return None n = int(input()) a = [] for i in range(n): na = [] s = input() if len(s) != len(set(list(s))): print('NO') exit() for sa in a: if len(set(list(s)).intersection(set(list(sa)))) == 0: na.append(sa) else: if s in sa: s = sa elif sa in s: pass else: ms = cm(s, sa) if ms is None: print('NO') exit() else: s = ms a = na + [s] #print(a) print(''.join(sorted(a)))
1510502700
[ "strings", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 1, 0 ]
1 second
["Poor Dima!", "Poor Inna!", "4"]
80fdfeba87b7075c70671b3fd3a1199c
NoteNotes to the samples:In the first test sample, Inna cannot go through name DIMA a single time.In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: initially, Inna chooses some cell of the table where letter "D" is written; then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name DIMA.
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 103). Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A". Note that it is not guaranteed that the table contains at least one letter "D".
standard output
standard input
PyPy 3
Python
1,900
train_015.jsonl
d31f9145e86db5f0b2879a9c6717f390
256 megabytes
["1 2\nDI", "2 2\nMA\nID", "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID"]
PASSED
import sys n, m = map(int, input().split()) m += 1 d = {'I': 0, 'M': 1, 'A': 2, 'D': 3, '\n': -7} t = list(map(d.get, sys.stdin.read())) + [-7] * m p = [[] for q in t] c = [0] * len(t) for a in range(n * m): for b in (a - m, a + m, a - 1, a + 1): if abs(t[b] - t[a] + 1) == 2: p[a].append(b) c[b] += 1 s = [i for i, q in enumerate(c) if not q] while s: a = s.pop() for b in p[a]: t[b] = max(t[b], t[a] + 1) c[b] -= 1 if c[b] == 0: s.append(b) k = max(t) - 2 >> 2 print('Poor Inna!' if any(c) else k if k > 0 else 'Poor Dima!')
1387380600
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["32", "4", "1920", "10"]
4ca7837d1ddf80f0bde4aac2fb37d60b
NoteIn the first case, $$$a = 19305$$$. Its divisors are $$$1, 3, 5, 9, 11, 13, 15, 27, 33, 39, 45, 55, 65, 99, 117, 135, 143, 165, 195, 297, 351, 429, 495, 585, 715, 1287, 1485, 1755, 2145, 3861, 6435, 19305$$$ — a total of $$$32$$$.In the second case, $$$a$$$ has four divisors: $$$1$$$, $$$86028121$$$, $$$86028157$$$, and $$$7400840699802997 $$$.In the third case $$$a = 202600445671925364698739061629083877981962069703140268516570564888699 375209477214045102253766023072401557491054453690213483547$$$.In the fourth case, $$$a=512=2^9$$$, so answer equals to $$$10$$$.
You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Each of $$$a_i$$$ has between $$$3$$$ and $$$5$$$ divisors. Consider $$$a = \prod a_i$$$ — the product of all input integers. Find the number of divisors of $$$a$$$. As this number may be very large, print it modulo prime number $$$998244353$$$.
Print a single integer $$$d$$$ — the number of divisors of the product $$$a_1 \cdot a_2 \cdot \dots \cdot a_n$$$ modulo $$$998244353$$$. Hacks input For hacks, the input needs to be provided in a special format. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of numbers. Each of the next $$$n$$$ lines contains a prime factorization of $$$a_i$$$. The line contains an integer $$$k_i$$$ ($$$2 \leq k_i \leq 4$$$) — the number of prime factors of $$$a_i$$$ and $$$k_i$$$ integers $$$p_{i,j}$$$ ($$$2 \leq p_{i,j} \leq 2 \cdot 10^{18}$$$) where $$$p_{i,j}$$$ is the $$$j$$$-th prime factor of $$$a_i$$$. Before supplying the input to the contestant, $$$a_i = \prod p_{i,j}$$$ are calculated. Note that each $$$p_{i,j}$$$ must be prime, each computed $$$a_i$$$ must satisfy $$$a_i \leq 2\cdot10^{18}$$$ and must have between $$$3$$$ and $$$5$$$ divisors. The contestant will be given only $$$a_i$$$, and not its prime factorization. For example, you need to use this test to get the first sample: 32 3 32 3 52 11 13
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of numbers. Each of the next $$$n$$$ lines contains an integer $$$a_i$$$ ($$$1 \leq a_i \leq 2\cdot 10^{18}$$$). It is guaranteed that the number of divisors of each $$$a_i$$$ is between $$$3$$$ and $$$5$$$.
standard output
standard input
PyPy 3
Python
2,000
train_028.jsonl
2247664b54bb0a1424d3f8df865c68c6
256 megabytes
["3\n9\n15\n143", "1\n7400840699802997", "8 \n4606061759128693\n4606066102679989\n4606069767552943\n4606063116488033\n4606063930903637\n4606064745319241\n4606063930904021\n4606065559735517", "3\n4\n8\n16"]
PASSED
import math import sys from decimal import Decimal n=int(input()) d={} f={} s=set() for j in range(n): i=int(input()) f.setdefault(i,0) f[i]+=1 x=i**.25 x=int(x) y=i**.5 y=int(y) if x**4==i: d.setdefault(x,0) d[x]+=4 elif y*y==i: x=int(i**.5) d.setdefault(x, 0) d[x] += 2 elif int(i**(1./3)) ** 3 == i: x=int(math.pow(i,1/3)) d.setdefault(x,0) d[x]+=3 elif (1+int(i**(1./3))) ** 3 == i: x=int(math.pow(i,1/3))+1 d.setdefault(x,0) d[x]+=3 elif (int(i**(1./3))-1) ** 3 == i: x=int(math.pow(i,1/3))-1 d.setdefault(x,0) d[x]+=3 else: s.add(i) rem=set() # print(d) # print(s) for i in s: if i in rem: continue for j in s: if i==j: continue if math.gcd(i,j)!=1: a,b,c=math.gcd(i,j),i//math.gcd(i,j),j//math.gcd(i,j) d.setdefault(a,0) d.setdefault(b,0) d.setdefault(c,0) d[a]+=f[i] d[b]+=f[i] if j not in rem: d[c]+=f[j] d[a]+=f[j] rem.add(i) rem.add(j) break for i in s: if i in rem: continue for j in d: if i%j==0: d[j]+=f[i] d.setdefault(i//j,0) d[i//j]+=f[i] rem.add(i) break k=-1 for i in s: if i not in rem: d[k]=f[i] k-=1 d[k]=f[i] k-=1 ans=1 #print(rem,d) for k in d: ans*=d[k]+1 ans=ans%998244353 print(ans) sys.stdout.flush()
1538931900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["11", "66"]
f350de23c9750b6e95b8cad80dde77c9
NoteIn the first test, you can make such operations: Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 5$$$ coins for that. Delete element $$$1$$$ from set $$$2$$$. You should pay $$$a_2 + b_1 = 6$$$ coins for that. You pay $$$11$$$ coins in total. After these operations, the first and the second sets will be equal to $$$\{2\}$$$ and the third set will be equal to $$$\{1, 2\}$$$.So, the graph will consist of one edge $$$(1, 2)$$$ of color $$$3$$$.In the second test, you can make such operations: Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 11$$$ coins for that. Delete element $$$4$$$ from set $$$2$$$. You should pay $$$a_2 + b_4 = 13$$$ coins for that. Delete element $$$7$$$ from set $$$3$$$. You should pay $$$a_3 + b_7 = 13$$$ coins for that. Delete element $$$4$$$ from set $$$4$$$. You should pay $$$a_4 + b_4 = 16$$$ coins for that. Delete element $$$7$$$ from set $$$6$$$. You should pay $$$a_6 + b_7 = 13$$$ coins for that. You pay $$$66$$$ coins in total.After these operations, the sets will be: $$$\{2, 3\}$$$; $$$\{1\}$$$; $$$\{1, 3\}$$$; $$$\{3\}$$$; $$$\{3, 4, 5, 6, 7\}$$$; $$$\{5\}$$$; $$$\{8\}$$$. We will get the graph:There are no rainbow cycles in it.
You are given $$$m$$$ sets of integers $$$A_1, A_2, \ldots, A_m$$$; elements of these sets are integers between $$$1$$$ and $$$n$$$, inclusive.There are two arrays of positive integers $$$a_1, a_2, \ldots, a_m$$$ and $$$b_1, b_2, \ldots, b_n$$$. In one operation you can delete an element $$$j$$$ from the set $$$A_i$$$ and pay $$$a_i + b_j$$$ coins for that.You can make several (maybe none) operations (some sets can become empty).After that, you will make an edge-colored undirected graph consisting of $$$n$$$ vertices. For each set $$$A_i$$$ you will add an edge $$$(x, y)$$$ with color $$$i$$$ for all $$$x, y \in A_i$$$ and $$$x &lt; y$$$. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.You call a cycle $$$i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1$$$ ($$$e_j$$$ is some edge connecting vertices $$$i_j$$$ and $$$i_{j+1}$$$ in this graph) rainbow if all edges on it have different colors.Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \leq m, n \leq 10^5$$$), the number of sets and the number of vertices in the graph. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \leq a_i \leq 10^9$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$). In the each of the next of $$$m$$$ lines there are descriptions of sets. In the $$$i$$$-th line the first integer $$$s_i$$$ ($$$1 \leq s_i \leq n$$$) is equal to the size of $$$A_i$$$. Then $$$s_i$$$ integers follow: the elements of the set $$$A_i$$$. These integers are from $$$1$$$ to $$$n$$$ and distinct. It is guaranteed that the sum of $$$s_i$$$ for all $$$1 \leq i \leq m$$$ does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
2,400
train_044.jsonl
6bc454ac3728b5c16e8e43544bc0f16c
256 megabytes
["3 2\n1 2 3\n4 5\n2 1 2\n2 1 2\n2 1 2", "7 8\n3 6 7 9 10 7 239\n8 1 9 7 10 2 6 239\n3 2 1 3\n2 4 1\n3 1 3 7\n2 4 3\n5 3 4 5 6 7\n2 5 7\n1 8"]
PASSED
import sys int1 = lambda x: int(x)-1 def MI(): return map(int, sys.stdin.buffer.readline().split()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LI1(): return list(map(int1, sys.stdin.buffer.readline().split())) def root(u): stack=[] while 1: if uf[u]<0: for v in stack:uf[v]=u break else: stack.append(u) u=uf[u] return u def merge(u,v): u=root(u) v=root(v) if u==v:return if uf[u]>uf[v]:u,v=v,u if uf[u]==uf[v]:uf[u]-=1 uf[v]=u def solve(): cuv = [] ans = 0 for u in range(m): vv = LI1() for v in vv[1:]: cost = aa[u]+bb[v] cuv.append((-cost, u, v+m)) ans += cost cuv.sort() for c, u, v in cuv: if root(u) == root(v): continue ans += c merge(u, v) print(ans) m,n=MI() aa=LI() bb=LI() uf=[-1]*(m+n) solve()
1601476500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["3\nabout proud\nhooray round\nwow first\nthis is\ni that\nmcdics am", "0", "1\nsame differ\nsame same"]
f06f7d0dcef10f064f5ce1e9eccf3928
NoteIn the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word "same" up to three times.
You are given $$$n$$$ words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric, "hey man""iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.
In the first line, print $$$m$$$ — the number of maximum possible beautiful lyrics. In next $$$2m$$$ lines, print $$$m$$$ beautiful lyrics (two lines per lyric). If there are multiple answers, print any.
The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of words. The $$$i$$$-th of the next $$$n$$$ lines contains string $$$s_{i}$$$ consisting lowercase alphabet letters — the $$$i$$$-th word. It is guaranteed that the sum of the total word length is equal or less than $$$10^{6}$$$. Each word contains at least one vowel.
standard output
standard input
PyPy 2
Python
1,700
train_034.jsonl
fd891599d2896e0e2c5c0dda0f8aa7a5
256 megabytes
["14\nwow\nthis\nis\nthe\nfirst\nmcdics\ncodeforces\nround\nhooray\ni\nam\nproud\nabout\nthat", "7\narsijo\nsuggested\nthe\nidea\nfor\nthis\nproblem", "4\nsame\nsame\nsame\ndiffer"]
PASSED
from sys import stdin, stdout import sys, atexit, io buffer = io.BytesIO() sys.stdout = buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) @atexit.register def main(): dici = {} n = int(stdin.readline()) for k in xrange(n): word = stdin.readline() vog = "" cont = 0 for l in word: if l in ["a", "e", "i", "o", "u"]: vog = l cont += 1 if not (vog, cont) in dici: dici[(vog, cont)] = [word] else: dici[(vog, cont)].append(word) reject = {} other = [] god = [] for l in dici: if len(dici[l]) > 1: for k in xrange(len(dici[l])-1, 0, -2): other.append((dici[l][k], dici[l][k-1])) dici[l].pop() dici[l].pop() for l in dici: if len(dici[l]) == 1: if not l[1] in reject: reject[l[1]] = [dici[l][0]] else: reject[l[1]].append(dici[l][0]) for l in reject: if len(reject[l]) > 1: for k in xrange(len(reject[l])-1, 0, -2): god.append((reject[l][k], reject[l][k-1])) reject[l].pop() reject[l].pop() result = [] for k in xrange(min(len(other), len(god) )): result.append(other[k]) result.append(god[k]) final = [] for k in xrange( 0,len(result), 2): final.append( (result[k+1][1], result[k][1])) final.append( (result[k+1][0], result[k][0])) if (len(god) - len(other)) % 2 == 0: for k in xrange(len(god), len(other), 2): final.append( (other[k+1][1], other[k][1])) final.append( (other[k+1][0], other[k][0])) else: for k in xrange(len(god) + 1, len(other), 2): final.append( (other[k+1][1], other[k][1])) final.append( (other[k+1][0], other[k][0])) stdout.write("%d\n" % (len(final)/2)) for k in xrange(0, len(final), 2): stdout.write(final[k][0] + final[k][1]) stdout.write(final[k+1][0] + final[k+1][1]) if __name__ == "__main__": main
1560258300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["25200.0000", "1365.0000"]
937acacc6d5d12d45c08047dde36dcf0
NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles.
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102).
standard output
standard input
PyPy 2
Python
1,100
train_007.jsonl
21e90debf5cf80907d1af47860f845fa
256 megabytes
["19 00\n255 1 100 1", "17 41\n1000 6 15 11"]
PASSED
import math hh, mm = map(int, raw_input().split(" ")) H, D, C, N = map(int, raw_input().split(" ")) result = 0 if hh >= 20: result = int(math.ceil(H/float(N))) * ((4*C)/5.0) else: rem = (20-hh-1)*60 + (60 - mm) now = int(math.ceil(H/float(N))) * C result = int(math.ceil((H+rem*D)/float(N))) * ((4*C)/5.0) result = min(result, now) print result
1521822900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3", "1"]
7030441bd7f8f34b007f959698f4739d
NoteFor example $$$1$$$, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than $$$3$$$ operations, and as such the answer is $$$3$$$. Here is the puzzle from the first example. For example $$$2$$$, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is $$$1$$$. Here is the puzzle from the second example.
This is the easy version of the problem. The difference between the versions is the constraints on $$$a_i$$$. You can make hacks only if all versions of the problem are solved.Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with $$$n$$$ rows and $$$m$$$ columns of cells, some empty and some filled with blocks of sand, and $$$m$$$ non-negative integers $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). In this version of the problem, $$$a_i$$$ will be equal to the number of blocks of sand in column $$$i$$$.When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell $$$(i,j)$$$ will pass through all cells below and including the cell $$$(i,j)$$$ within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell $$$(i,j)$$$ are defined as $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$, and $$$(i,j+1)$$$ (if they are within the grid). Note that the newly falling blocks can disturb other blocks.In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least $$$a_i$$$ blocks of sand counted in the $$$i$$$-th sand counter for each column from $$$1$$$ to $$$m$$$.You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.
Print one non-negative integer, the minimum amount of operations needed to solve the puzzle.
The first line consists of two space-separated positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$). Each of the next $$$n$$$ lines contains $$$m$$$ characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand. The final line contains $$$m$$$ non-negative integers $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, $$$a_i$$$ will be equal to the number of blocks of sand in column $$$i$$$.
standard output
standard input
PyPy 3
Python
2,500
train_091.jsonl
3e6964a55e920a90c55b94111a40cc66
512 megabytes
["5 7\n#....#.\n.#.#...\n#....#.\n#....##\n#.#....\n4 1 1 1 0 3 1", "3 3\n#.#\n#..\n##.\n3 1 1"]
PASSED
import io,os from collections import deque input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def find_scc(graph): # print(graph) SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] def main(t): m,n = map(int,input().split()) grid = [] for i in range(m): grid.append(list(input())) arr = list(map(int,input().split())) neigh = [[] for i in range(m*n)] direc = [[0,-1],[0,1],[-1,0],[1,0]] totedge = 0 for j in range(n): last = -2 i = 0 while i<m and grid[i][j]!=ord('#'): i += 1 while i<m: if last!=-2: neigh[last*n+j].append(i*n+j) if last+1==i: neigh[i*n+j].append(last*n+j) last,under = i,i while under<m: if j>0 and grid[under][j-1]==ord('#'): neigh[i*n+j].append(under*n+j-1) if under==i: neigh[under*n+j-1].append(i*n+j) if j+1<n and grid[under][j+1]==ord('#'): neigh[i*n+j].append(under*n+j+1) if under==i: neigh[under*n+j+1].append(i*n+j) under += 1 if under==m or grid[under][j]==ord('#'): break i = under # if m==632 and totedge>1000000: # print(totedge) # return scc = find_scc(neigh) group = [0]*(m*n) for index in range(len(scc)): for c in scc[index]: group[c] = index innum = [0]*len(scc) for i in range(m*n): for e in neigh[i]: if group[i]!=group[e]: innum[group[e]] += 1 ans = 0 for i in range(m): for j in range(n): if grid[i][j]==ord('#') and innum[group[i*n+j]] == 0: innum[group[i*n+j]] = -1 ans += 1 print(ans) T = 1 #int(input()) t = 1 while t<=T: main(t) t += 1
1623598500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1/6\n7/30"]
f4c743af8e8a1f90b74a27ca9bbc8b7b
null
Let's assume that v(n) is the largest prime number, that does not exceed n; u(n) is the smallest prime number strictly greater than n. Find .
Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q &gt; 0.
The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases. Each of the following t lines of the input contains integer n (2 ≤ n ≤ 109).
standard output
standard input
Python 3
Python
null
train_001.jsonl
86fdc66c4e439679e2f17b127c381fc3
256 megabytes
["2\n2\n3"]
PASSED
T = int( input() ) #for every prime x #(b-a)/ab #1/a-1/b MAX = 33000 bePrime = [0] * MAX; primNum = [] for j in range(2, MAX): if bePrime[j] == 0: primNum.append( j ) i = j while i < MAX: bePrime[i] = 1 i = i + j def isPrime( a ): for j in primNum: if j >= a: return True if a % j == 0: return False return True def gcd( a, b ): if b == 0: return a return gcd( b, a % b ); while T > 0: num = 0; n = int( input() ) m = n while isPrime(m) == False: m -= 1 while isPrime(n + 1) == False: n += 1 num += 1 a = n - 1 b = 2 * ( n+1 ) a = a * (n+1) * m - num * b b = b * (n+1) * m g = gcd( a, b) a //= g b //= g print( '{0}/{1}'.format( a, b ) ) T -= 1;
1393428600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n2\n0\n1\n1\n1"]
fd85ebe1dc975a71c72fac7eeb944a4a
NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant.
Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then: strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant; strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.
For each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,300
train_000.jsonl
6d760167b3b033669bf2d67d5ed37ae9
256 megabytes
["6\n6 1\n100010\n6 2\n000000\n5 1\n10101\n3 1\n001\n2 2\n00\n1 1\n0"]
PASSED
import math for _ in range(int(input())): n,k = map(int, input().split()) s = input() #print(s[::-1]) if s.count('0') == len(s): print(math.ceil(len(s)/(k+1))) else: anz = 0 st = s.index('1') en = n - s[::-1].index('1') #print(st,en) if (st) > 0: anz += math.ceil((st - k) / (k+1)) if (n-en) > 0: anz += math.ceil((n-en-k) / (k+1)) i = st + 1 while i < en: j = i while j < en and s[j] != '1': j += 1 if (j-i-(2*k)) > 0: anz += math.ceil((j-i-(2*k)) / (k+1)) i = j+1 print(anz)
1592318100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["4 7\nDDDDDDD\nDABACAD\nDBABACD\nDDDDDDD", "4 50\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\nABABABABABABABABABABABABABABABABABABABABABABABABAB\nBABABABABABABABABABABABABABABABABABABABABABABABABA\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", "7 7\nDDDDDDD\nDDDBDBD\nDDCDCDD\nDBDADBD\nDDCDCDD\nDBDBDDD\nDDDDDDD"]
637b0a757223521c44674bf1663a1114
NoteIn the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one.
As the boat drifts down the river, a wood full of blossoms shows up on the riverfront."I've been here once," Mino exclaims with delight, "it's breathtakingly amazing.""What is it like?""Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.The wood can be represented by a rectangular grid of $$$n$$$ rows and $$$m$$$ columns. In each cell of the grid, there is exactly one type of flowers.According to Mino, the numbers of connected components formed by each kind of flowers are $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.You are to help Kanno depict such a grid of flowers, with $$$n$$$ and $$$m$$$ arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.Note that you can choose arbitrary $$$n$$$ and $$$m$$$ under the constraints below, they are not given in the input.
In the first line, output two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid respectively. Then output $$$n$$$ lines each consisting of $$$m$$$ consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower).
The first and only line of input contains four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a, b, c, d \leq 100$$$) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively.
standard output
standard input
Python 3
Python
1,800
train_044.jsonl
1fa5609157b8023029804d9bc946d6d3
256 megabytes
["5 3 2 1", "50 50 1 1", "1 6 4 5"]
PASSED
a, b, c, d = map(int, input().split()) res = [['A'] * 50 for i in range(25)] + [['B'] * 50 for i in range(25)] a, b = a - 1, b - 1 for i in range(0, 24, 2): for j in range(0, 50, 2): if b > 0: b -= 1 res[i][j] = 'B' elif c > 0: c -= 1 res[i][j] = 'C' elif d > 0: d -= 1 res[i][j] = 'D' if a > 0: a -= 1 res[i + 26][j] = 'A' print(50, 50) for i in res: print(*i, sep='')
1528724100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1", "3", "0"]
d549f70d028a884f0313743c09c685f1
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
standard output
standard input
PyPy 2
Python
1,300
train_015.jsonl
10407d83aa537c4dc72ef9684f52626e
256 megabytes
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
PASSED
n, m = [int(s) for s in raw_input().split()] A = [None] * n for i in range(n): row = [int(s) for s in raw_input().split()] A[i] = row Amax = max([i for a in A for i in a]) def generate_primes(Amax): Amax = max(Amax, 10) numbers = [i for i in range(100004)] mapping = {n: True for n in numbers} mapping[0] = False mapping[1] = False primes = [] for i in range(len(numbers)): n = numbers[i] if mapping[n]: primes.append(n) r = 2 while n * r <= len(numbers) - 1: mapping[n*r] = False r += 1 return primes ''' primes = [2] i = 3 cont = True while cont: if all([i % p != 0 for p in primes]): primes.append(i) if i > Amax: cont = False i += 1 else: i += 1 return primes ''' def get_next_largest_prime(x, primes): if x == primes[-1] or x == 2: return x if x == 1: return 2 mini = 0 maxi = len(primes) - 1 mid = mini + ((maxi - mini)//2) while maxi - mini > 1 : if x < primes[mid]: maxi = mid mid = mini + ((maxi - mini)//2) elif x > primes[mid]: mini = mid mid = mini + ((maxi - mini)//2) else: return primes[mid] if x == primes[mini]: return primes[mini] elif x > primes[mini]: return primes[maxi] else: raise ValueError() primes = generate_primes(Amax) row_sums = [0 for _ in range(m)] col_sums = [0 for _ in range(n)] for i in range(n): for j in range(m): A[i][j] = get_next_largest_prime(A[i][j], primes) - A[i][j] row_sums[j] += A[i][j] col_sums[i] += A[i][j] moves = min(min(col_sums), min(row_sums)) print(moves) ''' 2 3 5 7 11 0 1 2 3 4 x = 6 mini = 2 maxi = 5 mid = 7//2 = 3 mini + ((maxi - mini)//2) '''
1360596600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["1\n1", "2\n2 2", "3\n9 9 9"]
7c483498f497f4291e3d33375c0ebd53
NoteIn the first test, the number $$$1$$$ can be divided into $$$1$$$ digit equal to $$$1$$$.In the second test, there are $$$3$$$ partitions of the number $$$4$$$ into digits in which the number of different digits is $$$1$$$. This partitions are $$$[1, 1, 1, 1]$$$, $$$[2, 2]$$$ and $$$[4]$$$. Any of these partitions can be found. And, for example, dividing the number $$$4$$$ to the digits $$$[1, 1, 2]$$$ isn't an answer, because it has $$$2$$$ different digits, that isn't the minimum possible number.
Vasya has his favourite number $$$n$$$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $$$d_1, d_2, \ldots, d_k$$$, such that $$$1 \leq d_i \leq 9$$$ for all $$$i$$$ and $$$d_1 + d_2 + \ldots + d_k = n$$$.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $$$d_1, d_2, \ldots, d_k$$$. Help him!
In the first line print one integer $$$k$$$ — the number of digits in the partition. Note that $$$k$$$ must satisfy the inequality $$$1 \leq k \leq n$$$. In the next line print $$$k$$$ digits $$$d_1, d_2, \ldots, d_k$$$ separated by spaces. All digits must satisfy the inequalities $$$1 \leq d_i \leq 9$$$. You should find a partition of $$$n$$$ in which the number of different digits among $$$d_1, d_2, \ldots, d_k$$$ will be minimal possible among all partitions of $$$n$$$ into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number $$$n$$$ into digits.
The first line contains a single integer $$$n$$$ — the number that Vasya wants to split ($$$1 \leq n \leq 1000$$$).
standard output
standard input
Python 3
Python
800
train_001.jsonl
6f66d62b6d28a5bccbfe768b70ecc33f
256 megabytes
["1", "4", "27"]
PASSED
n = int(input()) print(n) for i in range(n): print('1',end = ' ')
1548167700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nYES\nNO\nYES\nNO\nYES\nYES"]
b3978805756262e17df738e049830427
null
Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$; If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.
For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.
standard output
standard input
PyPy 3
Python
1,000
train_001.jsonl
3b162a0bdd1311e1760328ce3caa8709
256 megabytes
["7\n2 3\n1 1\n3 6\n6 8\n1 2\n4 1\n31235 6578234"]
PASSED
for _ in range(int(input())): x, y = map(int, input().split()) if x >= y: print("YES") elif x <= 3 and y > 3: print("NO") elif x <= 3 and x > 0 and x % 2: print("NO") else: print("YES")
1573655700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n0\n0"]
5de66fbb594bb317654366fd2290c4d3
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
You are given a string $$$s$$$. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?
Print $$$t$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th testcase (the minimum number of 0's that you have to erase from $$$s$$$).
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each representing a test case. Each line contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$); each character of $$$s$$$ is either 0 or 1.
standard output
standard input
Python 3
Python
800
train_001.jsonl
d555ef4c641c7aef75cb0f6a09ab8b17
256 megabytes
["3\n010011\n0\n1111000"]
PASSED
for _ in range(int(input())): s = str(input()) n = len(s) print(s.strip('0').count('0'))
1581518100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["0\n2", "2\n1 2 3"]
fb5c6182b9cad133d8b256f8e72e7e3b
null
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
standard output
standard input
Python 3
Python
1,700
train_033.jsonl
ca3fcd27ca7dcc7ec54b29175d736498
256 megabytes
["3\n2 1\n2 3", "4\n1 4\n2 4\n3 4"]
PASSED
n=int(input()) t=[0]*(n+1) u,v=[[]for i in range(n+1)],[[]for i in range(n+1)] for i in range(n-1): x,y=map(int,input().split()) t[y]=1 u[x].append(y) v[y].append(x) d, s = u[1] + v[1], len(v[1]) for i in u[1]: t[i]=1 v[i].remove(1) for i in v[1]: t[i]=-1 u[i].remove(1) while d: b=d.pop() for i in u[b]: t[i]=t[b]+1 v[i].remove(b) for i in v[b]: t[i]=t[b]-1 u[i].remove(b) d+=u[b]+v[b] s+=len(v[b]) m=min(t) print(s+m) print(' '.join(map(str,[i for i in range(1,n+1) if t[i]==m])))
1346081400
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3.5 seconds
["3\n1\n78975\n969\n109229059713337"]
2cc753baa293ee832054de494dee0f15
NoteIn the first test case, there are $$$3$$$ suitable triplets: $$$(1,2,3)$$$, $$$(1,3,4)$$$, $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet: $$$(3,4,5)$$$.
We are sum for we are manySome NumberThis version of the problem differs from the next one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \le i &lt; j &lt; k \le r$$$ and $$$\operatorname{lcm}(i,j,k) \ge i + j + k$$$.Here $$$\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.
For each test case print one integer — the number of suitable triplets.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\bf{1 \le t \le 5}$$$). Description of the test cases follows. The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 2 \cdot 10^5$$$, $$$l + 2 \le r$$$).
standard output
standard input
PyPy 3-64
Python
2,300
train_102.jsonl
6f7932999e4e73ee4a63a3d557dc46e6
512 megabytes
["5\n\n1 4\n\n3 5\n\n8 86\n\n68 86\n\n6 86868"]
PASSED
import sys input = sys.stdin.buffer.readline # from collections import defaultdict, deque, Counter from math import gcd, lcm from functools import reduce # from itertools import accumulate, chain, islice, starmap # from operator import add, sub, mul, floordiv, truediv # def f(L,R,tup): def lcm3(tup): a,b,c = tup if c%b or c%a: return 2*c else: return c def tup_gen(hi=2*10**5,a=1,b=1): # if a * b <= hi: yield (a,b) # k = 1 # while a*k+b <= hi//a: for k in range(1, (hi//a-b)//a+1): for i in tup_gen(hi, a*k+b, a): yield i # k+=1 # s = set(tuple(sorted((b,a,a*b))) for (a,b) in tup_gen()) # s.add((3,4,6)) # s.add((6,10,15)) ma = 0 for _ in range(int(input())): L, R = map(int,input().split()) tot = (R-L+1)*(R-L)*(R-L-1) // 6 # ans = tot tmp = 0 # s = set() if R > ma: ma = R # s = set(tuple(sorted((b,a,a*b))) for (a,b) in tup_gen(R)) # l = list(tuple(sorted((b,a,a*b))) for (a,b) in tup_gen(R)) l = list(tup_gen(R)) # s.add((3,4,6)) # s.add((6,10,15)) # for a, b in tup_gen(R, L, 1,1): # # cands = [(b,a,a*b),(2*b,a,a*b),(b,2*a,a*b),(2*b,2*a,a*b),(b,a,a*b*2),(2*b,a,a*b*2),(b,2*a,a*b*2),(2*b,2*a,a*b*2)] # cands = [(b,a,a*b),(2*b,a,a*b),(b,2*a,a*b),(2*b,2*a,a*b)] # for cand in cands: # if not all(x%2==0 for x in cand): # # assert reduce(gcd,cand) < 2 # s.add(tuple(sorted(cand))) # s2 = set() l2 = list() # for tup in s: # a,b,c=tup # c2 = 0 # for n in range(1,R//c+1): # c2 += c # if a<b<c2: # tup2=(a,b,c2) # if lcm3(tup2) < sum(tup2) and not all(x%2==0 for x in tup2):# and tup2 not in s: # # if tup2 in s: # # print("?????",tup2,n) # # assert reduce(gcd,tup2) < 2 # s2.add(tup2) # # l2.append(tup2) # elif n > 1: # break # # s2.add(tup) # for tup in l: # for b,a in tup_gen(R): for b,a in l: # a,b,c=tup # a,b=min(a,b),max(a,b) c = a*b tup = (a,b,c) su=a+b+c if a<b<c: if lcm3(tup) < su: # assert reduce(gcd,tup) < 2 # s2.add(tup) # l2.append(tup) lo,hi=(L+a-1)//a, R//c if lo <= hi: tmp += hi-lo+1 # else: # break if a<b<=c: for n in range(2,R//c+1): su+=c tup2=(a,b,c*n) if lcm3(tup2) < su:# and not all(x%2==0 for x in tup2):# and tup2 not in s: # if tup2 in s: # print("?????",tup2,n) # assert reduce(gcd,tup2) < 2 # s2.add(tup2) # l2.append(tup2) lo,hi=(L+a-1)//a, R//(c*n) if lo <= hi: tmp += hi-lo+1 else: break # s2.add(tup) # s2.add((3,4,6)) # s2.add((6,10,15)) l2.append((3,4,6)) l2.append((6,10,15)) for tup in l2: a,b,c=tup # if a<b<c: # s4 = set() lo,hi=(L+a-1)//a, R//c if lo <= hi: tmp += hi-lo+1 # for d in range((L+a-1)//a, R//c+1): # tup2 = (d*a,d*b,d*c) # if tup2 in s3: # print(tup2,"?????") # s3.add(tup2) # s4.add(tup2) # assert tmp == len(s3), (L,R,lo,hi,tup, s3,s4) # s32= set(list(s3)) # for tup in s3: # a,b,c=tup # if L<=a<b<c<=R:# and lcm3(tup) < sum(tup): # # s4.add(tup) # ans -= 1 # print(tot - len(s3)) print(tot-tmp)
1660401300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
4 seconds
["26", "-1"]
ed0765719bfc3903701c0c14b7ad15c7
NoteThe best option in the first example is to take the first course $$$2$$$, the second course $$$1$$$, the drink $$$2$$$ and the dessert $$$1$$$.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are $$$n_1$$$ different types of first courses Ivan can buy (the $$$i$$$-th of them costs $$$a_i$$$ coins), $$$n_2$$$ different types of second courses (the $$$i$$$-th of them costs $$$b_i$$$ coins), $$$n_3$$$ different types of drinks (the $$$i$$$-th of them costs $$$c_i$$$ coins) and $$$n_4$$$ different types of desserts (the $$$i$$$-th of them costs $$$d_i$$$ coins).Some dishes don't go well with each other. There are $$$m_1$$$ pairs of first courses and second courses that don't go well with each other, $$$m_2$$$ pairs of second courses and drinks, and $$$m_3$$$ pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!
If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $$$-1$$$. Otherwise, print one integer — the minimum total cost of the dinner.
The first line contains four integers $$$n_1$$$, $$$n_2$$$, $$$n_3$$$ and $$$n_4$$$ ($$$1 \le n_i \le 150000$$$) — the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $$$n_1$$$ integers $$$a_1, a_2, \dots, a_{n_1}$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($$$1 \le b_i, c_i, d_i \le 10^8$$$). The next line contains one integer $$$m_1$$$ ($$$0 \le m_1 \le 200000$$$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $$$m_1$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$) denoting that the first course number $$$x_i$$$ doesn't go well with the second course number $$$y_i$$$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($$$0 \le m_2, m_3 \le 200000$$$).
standard output
standard input
PyPy 3-64
Python
2,000
train_082.jsonl
7c28910e12ef8a4cf5693e0ead9c7784
512 megabytes
["4 3 2 1\n1 2 3 4\n5 6 7\n8 9\n10\n2\n1 2\n1 1\n2\n3 1\n3 2\n1\n1 1", "1 1 1 1\n1\n1\n1\n1\n1\n1 1\n0\n0"]
PASSED
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase from collections import defaultdict def main(): INF = int(1e18) n1, n2, n3, n4 = map(int, input().split()) aa = list(map(int, input().split())) bb = list(map(int, input().split())) cc = list(map(int, input().split())) dd = list(map(int, input().split())) m1 = int(input()) xx1, yy1 = [0] * m1, [0] * m1 for i in range(m1): xx1[i], yy1[i] = map(int, input().split()) m2 = int(input()) xx2, yy2 = [0] * m2, [0] * m2 for i in range(m2): xx2[i], yy2[i] = map(int, input().split()) m3 = int(input()) xx3, yy3 = [0] * m3, [0] * m3 for i in range(m3): xx3[i], yy3[i] = map(int, input().split()) ### order = list(range(n1)) order.sort(key=lambda i: aa[i]) rev = [0] * n1 for i in range(n1): rev[order[i]] = i edges = defaultdict(list) for x, y in zip(xx1, yy1): edges[y-1].append(rev[x-1]) left = [INF] * n2 for i in range(n2): if len(edges[i]) == n1: continue edges[i].sort() mex = 0 while mex < len(edges[i]): if mex != edges[i][mex]: break mex += 1 left[i] = bb[i] + aa[order[mex]] ### order = list(range(n4)) order.sort(key=lambda i: dd[i]) rev = [0] * n4 for i in range(n4): rev[order[i]] = i edges = defaultdict(list) for x, y in zip(xx3, yy3): edges[x-1].append(rev[y-1]) right = [INF] * n3 for i in range(n3): if len(edges[i]) == n4: continue edges[i].sort() mex = 0 while mex < len(edges[i]): if mex != edges[i][mex]: break mex += 1 right[i] = cc[i] + dd[order[mex]] ### order = list(range(n3)) order.sort(key=lambda i: right[i]) rev = [0] * n3 for i in range(n3): rev[order[i]] = i edges = defaultdict(list) for x, y in zip(xx2, yy2): edges[x-1].append(rev[y-1]) ans = INF for i in range(n2): if len(edges[i]) == n3 or left[i] == INF: continue edges[i].sort() mex = 0 while mex < len(edges[i]): if mex != edges[i][mex]: break mex += 1 ans = min(ans, left[i] + right[order[mex]]) if ans == INF: print(-1) else: print(ans) return 0 # 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") # endregion if __name__ == "__main__": main()
1613399700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["01100", "110010"]
cac8ca5565e06021a44bb4388b5913a5
NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; in the segment $$$[1\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$; in the segment $$$[2\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$; in the segment $$$[2\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; in the segment $$$[5\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\cdot 1=1$$$; in the segment $$$[1\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$; in the segment $$$[4\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$.
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.
Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be «0» if you want to put a rose in the $$$i$$$-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 10^3$$$) — the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\leq l_i\leq r_i\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.
standard output
standard input
PyPy 3
Python
1,300
train_045.jsonl
c6b7241e65f70fd52aa17c746cd65c0b
256 megabytes
["5 3\n1 3\n2 4\n2 5", "6 3\n5 6\n1 4\n4 6"]
PASSED
n,m=map(int,input().split()) arr=["01" for _ in range(n//2)] if n%2==1: arr.append("0") print("".join(arr))
1530808500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6 2", "0 1"]
91c3af92731cd7d406674598c0dcbbbc
null
This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.
standard output
standard input
PyPy 3
Python
1,900
train_019.jsonl
d388222e448b2e918b109ea56eaf37fb
256 megabytes
[")((())))(()())", "))("]
PASSED
s = input() ans = dict() stack = [-1] res = 0 for i in range(len(s)): c = s[i] if c == ')' and stack[-1] != -1 and s[stack[-1]] == '(': stack.pop() ans[i-stack[-1]] = ans.get(i-stack[-1],0)+1 res = max(i-stack[-1], res) else: stack.append(i) if res not in ans.keys(): print('0 1') else: print(" ".join([str(res),str(ans[res])]))
1269100800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["YES\nYES\nNO\nNO\nYES"]
bc5fb5d6882b86d83e5c86f21d806a52
null
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.
For each test case, print "YES" if Polycarp can distribute all $$$n$$$ coins between his sisters and "NO" otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.
standard output
standard input
Python 3
Python
800
train_000.jsonl
01617e2eb58b355f44572170c03385c0
256 megabytes
["5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3"]
PASSED
t = int(input()) for _ in range(t): a,b,c,n = map(int, input().split()) m = max(a,b,c) for i in [a,b,c]: p = m-i i+=p n-=p if n%3==0 and n>=0: print("YES") else: print("NO")
1579703700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["8\n1 2\n4 3\n3 2\n4 1\n-1\n12\n3 2\n1 2\n3 1"]
f6e219176e846b16c5f52dee81601c8e
null
Hanh lives in a shared apartment. There are $$$n$$$ people (including Hanh) living there, each has a private fridge. $$$n$$$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $$$n$$$ people can open it. For exampe, in the picture there are $$$n=4$$$ people and $$$5$$$ chains. The first person knows passcodes of two chains: $$$1-4$$$ and $$$1-2$$$. The fridge $$$1$$$ can be open by its owner (the person $$$1$$$), also two people $$$2$$$ and $$$4$$$ (acting together) can open it. The weights of these fridges are $$$a_1, a_2, \ldots, a_n$$$. To make a steel chain connecting fridges $$$u$$$ and $$$v$$$, you have to pay $$$a_u + a_v$$$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly $$$m$$$ steel chains so that all fridges are private. A fridge is private if and only if, among $$$n$$$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $$$i$$$ is not private if there exists the person $$$j$$$ ($$$i \ne j$$$) that the person $$$j$$$ can open the fridge $$$i$$$.For example, in the picture all the fridges are private. On the other hand, if there are $$$n=2$$$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $$$m$$$ chains, and if yes, output any solution that minimizes the total cost.
For each test case: If there is no solution, print a single integer $$$-1$$$. Otherwise, print a single integer $$$c$$$ — the minimum total cost. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), meaning that the $$$i$$$-th steel chain connects fridges $$$u_i$$$ and $$$v_i$$$. An arbitrary number of chains can be between a pair of fridges. If there are multiple answers, print any.
Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 10$$$). Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \le n \le 1000$$$, $$$1 \le m \le n$$$) — the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$) — weights of all fridges.
standard output
standard input
PyPy 3
Python
1,100
train_008.jsonl
12f858c06350edeb93ea73cac79c9704
256 megabytes
["3\n4 4\n1 1 1 1\n3 1\n1 2 3\n3 3\n1 2 3"]
PASSED
t=int(input()) while t>0: n,m =map(int,input().split()) a=[int(x) for x in input().split()] if(n==2): print(-1) elif(n>m): print(-1) else: print(2*sum(a)) for _ in range(0,n): print(_+1,(_+1)%n+1) t-=1
1574174100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["12339\n0\n15\n54306\n999999995\n185\n999999998"]
2589e832f22089fac9ccd3456c0abcec
NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$.
You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.
For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y &lt; x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.
standard output
standard input
Python 3
Python
800
train_001.jsonl
e6633cf1e52b2fbed347e696ec4d0ac9
256 megabytes
["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"]
PASSED
for i in range(int(input())): x,y,n=map(int,input().split()) for i in range(n//x,-1,-1): if x*i+y<=n: print(x*i+y) break
1593354900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4\n6\n41\n4\n4\n2\n334"]
6422d76f71702e77808b1cc041962bb8
Note An example of a possible shortest path for the first test case. An example of a possible shortest path for the second test case.
There are three cells on an infinite 2-dimensional grid, labeled $$$A$$$, $$$B$$$, and $$$F$$$. Find the length of the shortest path from $$$A$$$ to $$$B$$$ if: in one move you can go to any of the four adjacent cells sharing a side; visiting the cell $$$F$$$ is forbidden (it is an obstacle).
Output $$$t$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th test case: the length of the shortest path from the cell $$$A$$$ to the cell $$$B$$$ if the cell $$$F$$$ is not allowed to be visited.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first one contains two integers $$$x_A, y_A$$$ ($$$1 \le x_A, y_A \le 1000$$$) — coordinates of the start cell $$$A$$$. The second one contains two integers $$$x_B, y_B$$$ ($$$1 \le x_B, y_B \le 1000$$$) — coordinates of the finish cell $$$B$$$. The third one contains two integers $$$x_F, y_F$$$ ($$$1 \le x_F, y_F \le 1000$$$) — coordinates of the forbidden cell $$$F$$$. All cells are distinct. Coordinate $$$x$$$ corresponds to the column number and coordinate $$$y$$$ corresponds to the row number (see the pictures below).
standard output
standard input
PyPy 3
Python
800
train_103.jsonl
fb09d658c0d2ebcb32039a913d5189bb
512 megabytes
["7\n\n1 1\n3 3\n2 2\n\n2 5\n2 1\n2 3\n\n1000 42\n1000 1\n1000 1000\n\n1 10\n3 10\n2 10\n\n3 8\n7 8\n3 7\n\n2 1\n4 1\n1 1\n\n1 344\n1 10\n1 1"]
PASSED
import sys from sys import stdin, stdout # input = stdin.readline # def invr(): # return(map(int,input().split())) def main(): t = int(stdin.readline()) a = b = f = [0]*2 for u in range(0,t): stdin.readline() # for i in range(0,2): a = stdin.readline().split() a = int(a[0]), int(a[1]) b = stdin.readline().split() b = int(b[0]), int(b[1]) f = stdin.readline().split() f = int(f[0]), int(f[1]) dist = 0 x_diff = abs(b[0] - a[0]) y_diff = abs(b[1] - a[1]) dist = x_diff + y_diff if (x_diff == 0) and (f[0] == a[0] and (a[1] < f[1] < b[1] or b[1]<f[1]<a[1])): dist = dist + 2 if (y_diff == 0) and (f[1] == a[1] and (a[0] < f[0] < b[0] or b[0]<f[0]<a[0])): dist = dist + 2 print(dist) # a = int(a) # b = int(b) # x = invr() # print(a+b) # x = inp() # print(x) # x = inp() # print(x) return main()
1625927700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\n1\n2\n2\n3\n2\n2\n4\n1"]
b6608fadf1677e5cb78b6ed092a23777
null
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length The picture corresponds to the first example
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 &lt; x2 ≤ 109,  - 109 ≤ y1 &lt; y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
standard output
standard input
Python 3
Python
2,100
train_071.jsonl
f7999fe7238c083df300f8e2aff6fe10
256 megabytes
["8\n0 0 5 3\n2 -1 5 0\n-3 -4 2 -1\n-1 -1 2 0\n-3 0 0 5\n5 2 10 3\n7 -3 10 2\n4 -2 7 -1"]
PASSED
'''plan noticed that if both upperle ''' from sys import stdin, stdout # n = int(stdin.readline().rstrip()) # n = int(input()) all_lines = stdin.read().split('\n') stdout.write('YES\n') for line in all_lines[1:-1]: x1, y1, x2, y2 = (int(x) % 2 for x in line.split()) num = 2 * x2 + y2 + 1 # stdout.write(str(x2) + ' ' + str(y2) + '\n') stdout.write(str(num) + '\n') #stdout.flush() #exit() # for i in range(n): # coordinates.append([int(x) % 2 for x in input().split()]) # for i in range(n): # coordinates.append([int(x) % 2 for x in stdin.readline().rstrip().split()]) # stdout.write('YES\n') # for coordinate in coordinates: # x1, y1, x2, y2 = coordinate # stdout.write(str(2 * x2 + y2 + 1) + '\n')
1486042500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
3 seconds
["3", "7"]
3fd58cef6d06400992088da9822ff317
NoteThe optimal way in the first example is $$$2 \to 1 \to 3$$$. The optimal way in the second example is $$$2 \to 4$$$.
The Fair Nut is going to travel to the Tree Country, in which there are $$$n$$$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $$$u$$$ and go by a simple path to city $$$v$$$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.A filling station is located in every city. Because of strange law, Nut can buy only $$$w_i$$$ liters of gasoline in the $$$i$$$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.
Print one number — the maximum amount of gasoline that he can have at the end of the path.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$) — the number of cities. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \leq w_{i} \leq 10^9$$$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $$$n - 1$$$ lines describes road and contains three integers $$$u$$$, $$$v$$$, $$$c$$$ ($$$1 \leq u, v \leq n$$$, $$$1 \leq c \leq 10^9$$$, $$$u \ne v$$$), where $$$u$$$ and $$$v$$$ — cities that are connected by this road and $$$c$$$ — its length. It is guaranteed that graph of road connectivity is a tree.
standard output
standard input
Python 3
Python
1,800
train_048.jsonl
e4721c15cbbdb067e6b3225681791dd9
256 megabytes
["3\n1 3 3\n1 2 2\n1 3 2", "5\n6 3 2 5 0\n1 2 10\n2 3 3\n2 4 1\n1 5 1"]
PASSED
from collections import deque def recurse(x,d,w,parent,v,vb): best = 0 bestt = 0 ans = 0 for t in d[x]: node = t[0] if node == parent: continue weight = int(w[node-1])-t[1] ans = max(ans,v[node]) tot = weight+vb[node] if tot > best: bestt = best best = tot elif tot > bestt: bestt = tot ans = max(ans,best+bestt+int(w[x-1])) v[x] = ans vb[x] = best return (ans,best) n = int(input()) w = input().split() dic = {} for i in range(1,n+1): dic[i] = [] for i in range(n-1): u,v,c = map(int,input().split()) dic[u].append((v,c)) dic[v].append((u,c)) dq = deque() dq.append(1) visit = set() l = [] l.append((1,0)) while len(dq) > 0: cur = dq.pop() visit.add(cur) for t in dic[cur]: node = t[0] if node not in visit: l.append((node,cur)) dq.append(node) val = [0]*(n+1) valb = [0]*(n+1) for i in range(len(l)-1,-1,-1): recurse(l[i][0],dic,w,l[i][1],val,valb) print(val[1])
1544459700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["2\n1 0", "-1", "3\n9 4 0"]
6f8de802d2b6b0f48f2be0531b3ac8d4
NoteIn the first example, Gorf is on the bottom of the well and jump to the height $$$1$$$ meter below ground level. After that he slip down by meter and stays on height $$$2$$$ meters below ground level. Now, from here, he can reach ground level in one jump.In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level.In the third example, Gorf can reach ground level only from the height $$$5$$$ meters below the ground level. And Gorf can reach this height using a series of jumps $$$10 \Rightarrow 9 \dashrightarrow 9 \Rightarrow 4 \dashrightarrow 5$$$ where $$$\Rightarrow$$$ is the jump and $$$\dashrightarrow$$$ is slipping during breaks.
Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $$$n$$$ meters depth. Now Gorf is on the bottom of the well and has a long way up.The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on $$$x$$$ meters below ground level, then in one jump he can go up on any integer distance from $$$0$$$ to $$$a_x$$$ meters inclusive. (Note that Gorf can't jump down, only up).Unfortunately, Gorf has to take a break after each jump (including jump on $$$0$$$ meters). And after jumping up to position $$$x$$$ meters below ground level, he'll slip exactly $$$b_x$$$ meters down while resting.Calculate the minimum number of jumps Gorf needs to reach ground level.
If Gorf can't reach ground level, print $$$-1$$$. Otherwise, firstly print integer $$$k$$$ — the minimum possible number of jumps. Then print the sequence $$$d_1,\,d_2,\,\ldots,\,d_k$$$ where $$$d_j$$$ is the depth Gorf'll reach after the $$$j$$$-th jump, but before he'll slip down during the break. Ground level is equal to $$$0$$$. If there are multiple answers, print any of them.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the depth of the well. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le i$$$), where $$$a_i$$$ is the maximum height Gorf can jump from $$$i$$$ meters below ground level. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le n - i$$$), where $$$b_i$$$ is the distance Gorf will slip down if he takes a break on $$$i$$$ meters below ground level.
standard output
standard input
PyPy 3-64
Python
1,900
train_092.jsonl
fbae864d06746c3b0087d32e74821964
512 megabytes
["3\n0 2 2\n1 1 0", "2\n1 1\n1 0", "10\n0 1 2 3 5 5 6 7 8 5\n9 8 7 1 5 4 3 2 0 0"]
PASSED
from sys import stdin, stdout import sys import heapq from collections import defaultdict import math import bisect import io, os # from cffi import FFI import copy import itertools # for interactive problem # n = int(stdin.readline()) # print(x, flush=True) input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p #input = sys.stdin.buffer.readline # ffi = FFI() # ffi.cdef( # """ # typedef struct { # long long suf; # long long pre; # long long maxi; # bool is_plus; # long long lowest; # long long sum; # int length; # } node_t; # """ # ) # # MX = 2 << ((2 * 10 ** 5) - 1).bit_length() # data = ffi.new("node_t[]", MX + 3) # data[MX] = (0, 0, 0, True, 0, 0, 0) # id_node = data[MX] # res_left = MX + 1 # res_right = MX + 2 # # def combine(a, b): # if a.length == 0: # return b # if b.length == 0: # return a # # length = a.length + b.length # if a.is_plus: # pre = a.sum + b.pre # else: # pre = a.pre # if b.is_plus: # suf = a.suf + b.sum # else: # suf = b.suf # is_plus = a.is_plus and b.is_plus # sum = a.sum + b.sum # maxi = max(a.maxi, b.maxi, a.suf + b.pre) # lowest = min(a.lowest, a.sum + b.lowest) # return (suf, pre, maxi, is_plus, lowest, sum, length) # # def mapValue(x): # return (max(x, 0), max(x, 0), max(x, 0), (x >= 0), x, x, 1) # # class SegmentTree: # def __init__(self, N, A): # self._len = N # self._size = _size = 1 << (self._len - 1).bit_length() # for i in range(2 * _size): # data[i] = id_node # for i, x in enumerate(A): # data[_size + i] = mapValue(x) # for i in reversed(range(_size)): # data[i] = combine(data[i + i], data[i + i + 1]) # # def __delitem__(self, idx): # self[idx] = id_node # # def __getitem__(self, idx): # return data[idx + self._size] # # def __setitem__(self, idx, value): # idx += self._size # data[idx] = value # idx >>= 1 # while idx: # data[idx] = combine(data[2 * idx], 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 # data[res_left] = id_node # data[res_right] = id_node # while start < stop: # if start & 1: # data[res_left] = combine(data[res_left], data[start]) # start += 1 # if stop & 1: # stop -= 1 # data[res_right] = combine(data[stop], data[res_right]) # start >>= 1 # stop >>= 1 # data[res_left] = combine(data[res_left], data[res_right]) # return data[res_left] # def main(): # n, q = map(int, stdin.readline().split()) # segtree = SegmentTree(n, map(int, stdin.readline().split())) # ans = [] # for _ in range(q): # t, l, r = map(int, stdin.readline().split()) # l -= 1 # if t == 1: # segtree[l] = mapValue(r) # else: # ans.append(int(segtree.query(l, r).ans)) # print("\n".join(map(str, ans))) def kbits(n, k): result = [] for bits in itertools.combinations(range(n), k): s = ['0'] * n for bit in bits: s[bit] = '1' result.append(''.join(s)) return result def main(): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) dp = [math.inf] * n dp[-1] = 0 prev = [math.inf] * n prev_p = [math.inf] * n ans = math.inf prev_ans = -1 sched = n-1 stack = [n-1] while stack: temp = [] for i in stack: x = max(i - a[i], 0) if i - a[i] < 0: if ans > dp[i]+1: ans = dp[i]+1 prev_ans = i ans = min(dp[i]+1, ans) for j in range(x, sched): pos = j + b[j] if dp[pos] > dp[i] + 1: dp[pos] = dp[i] + 1 prev[pos] = i prev_p[pos] = j temp.append(pos) sched =min(x, sched) stack =temp if ans == math.inf: ans = -1 stdout.write(str(ans)+"\n") if ans != -1: arr = [-1] while prev_ans != math.inf: if prev_ans != -1: arr.append(prev_p[prev_ans]) prev_ans = prev[prev_ans] stdout.write(" ".join([str(x+1) for x in reversed(arr[:-1])]) + "\n") main()
1635143700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["0.5000000000", "1.3000000000"]
1df8aad60e5dff95bffb9adee5f8c460
null
One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates xi, and yi, by the time of it's appearance ti and by the number pi, which gives the probability that Copa hits this target if he aims at it.A target appears and disappears instantly, so Copa can hit the target only if at the moment ti his gun sight aimed at (xi, yi). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0.
Output the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10 - 6.
The first line contains integer n (1 ≤ n ≤ 1000) — amount of targets in the shooting gallery. Then n lines follow, each describing one target. Each description consists of four numbers xi, yi, ti, pi (where xi, yi, ti — integers,  - 1000 ≤ xi, yi ≤ 1000, 0 ≤ ti ≤ 109, real number pi is given with no more than 6 digits after the decimal point, 0 ≤ pi ≤ 1). No two targets may be at the same point.
standard output
standard input
Python 3
Python
1,800
train_007.jsonl
1afcb8d7042fea594f7eff8931e0bc4b
256 megabytes
["1\n0 0 0 0.5", "2\n0 0 0 0.6\n5 0 5 0.7"]
PASSED
import heapq def is_reachable(from_state, target): return (from_state[0]-target[0])**2 + (from_state[1]-target[1])**2 <= (target[2] - from_state[2])**2 num_iter = int(input()) targets = sorted([list(map(float, input().strip().split(' '))) for dummy in range(0, num_iter)], key=lambda single_target: single_target[2]) states = [] for i, target in enumerate(targets): score_estimate = target[3] sorted_states = heapq.nlargest(len(states), states) for j in range(len(sorted_states)): if is_reachable(sorted_states[j][1], target): score_estimate += sorted_states[j][1][3] break; target[3] = score_estimate heapq.heappush(states, (score_estimate, target)) max_score = heapq.nlargest(1, states)[0][1][3] print(max_score)
1285340400
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
1 second
["0\n1\n342"]
0690e2df87f60e5be34505d9e2817032
NoteIn the image below you can see the example solutions for the first two test cases. Chosen days off are shown in purple. Working segments are underlined in green.In test case $$$1$$$, the only options for days off are days $$$2$$$, $$$3$$$, and $$$4$$$ (because $$$1$$$ and $$$5$$$ are next to day $$$n$$$). So the only way to place them without selecting neighboring days is to choose days $$$2$$$ and $$$4$$$. Thus, $$$l_1 = l_2 = l_3 = 1$$$, and the answer $$$\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|) = 0$$$. For test case $$$2$$$, one possible way to choose days off is shown. The working segments have the lengths of $$$2$$$, $$$1$$$, and $$$4$$$ days. So the minimum difference is $$$1 = \min(1, 3, 2) = \min(|2 - 1|, |1 - 4|, |4 - 2|)$$$. It can be shown that there is no way to make it larger.
Your working week consists of $$$n$$$ days numbered from $$$1$$$ to $$$n$$$, after day $$$n$$$ goes day $$$1$$$ again. And $$$3$$$ of them are days off. One of the days off is the last day, day $$$n$$$. You have to decide when the other two are.Choosing days off, you pursue two goals: No two days should go one after the other. Note that you can't make day $$$1$$$ a day off because it follows day $$$n$$$. Working segments framed by days off should be as dissimilar as possible in duration. More specifically, if the segments are of size $$$l_1$$$, $$$l_2$$$, and $$$l_3$$$ days long, you want to maximize $$$\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$$$. Output the maximum value of $$$\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$$$ that can be obtained.
For each test case, output one integer — the maximum possible obtained value.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains the integer $$$n$$$ ($$$6 \le n \le 10^9$$$).
standard output
standard input
Python 3
Python
800
train_098.jsonl
0a7aeb817beb26231dd6f9b1cac9c774
256 megabytes
["3\n\n6\n\n10\n\n1033"]
PASSED
t = int(input()) for i in range(t): n = int(input()) print ((n-6)//3)
1664721300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
9c84eb518c273942650c7262e5d8b45f
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
standard output
standard input
PyPy 3
Python
1,100
train_000.jsonl
3efa832d96b478d2c89d224af50d44e6
256 megabytes
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
PASSED
#------------------------------what is this I don't know....just makes my mess faster-------------------------------------- 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") #----------------------------------Real game starts here-------------------------------------- ''' ___________________THIS IS AESTROIX CODE________________________ KARMANYA GUPTA ''' n , d = list(map(int, input().split())) for i in range(int(input())): x , y = list(map(int, input().split())) a = y-x b = y+x if a < d and a > -d and b > d and b < 2*n - d: print("YES") elif a == d or a == -d or b == d or b == 2*n - d: print("YES") else: print("NO")
1537707900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["7\n6\n1000\n5"]
ee8ca9b2c6104d1ff9ba1fc39e9df277
NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.
Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it: At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$). While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$). If $$$i &gt; n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible: Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$. Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$. Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$. Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$. Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.
For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_090.jsonl
46f0e18c29c4fe33381add15b7217029
256 megabytes
["4\n5\n7 3 1 2 3\n3\n2 1 4\n6\n2 1000 2 3 995 1\n5\n1 1 1 1 1"]
PASSED
if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) nums = list(map(int, input().split())) result, max_found = [], -float('inf') for x in nums: result.append(x) max_found = max(max_found, x) parent = {i:i for i in range(len(nums))} for i in range(len(nums)): next_idx = i + nums[i] while next_idx < len(nums) and parent[next_idx] == next_idx: result[i] += nums[next_idx] parent[next_idx] = i next_idx = next_idx + nums[next_idx] max_found = max(max_found, result[i]) print(max_found)
1609770900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["8", "1", "25", "29"]
373412134b2afd00618b19e4bf652d26
NoteIn the first example the diameter of the given tree is already less than or equal to $$$k$$$. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to $$$k$$$. There are $$$2^3$$$ sets, including the empty one.In the second example you have to remove the only edge. Otherwise, the diameter will be $$$1$$$, which is greater than $$$0$$$.Here are the trees for the third and the fourth examples:
You are given an integer $$$k$$$ and an undirected tree, consisting of $$$n$$$ vertices.The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to $$$k$$$.Two sets of edges are different if there is an edge such that it appears in only one of the sets.Count the number of valid sets of edges modulo $$$998\,244\,353$$$.
Print a single integer — the number of valid sets of edges modulo $$$998\,244\,353$$$.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 5000$$$, $$$0 \le k \le n - 1$$$) — the number of vertices of the tree and the maximum allowed diameter, respectively. Each of the next $$$n-1$$$ lines contains a description of an edge: two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \neq u$$$). The given edges form a tree.
standard output
standard input
PyPy 3
Python
2,400
train_104.jsonl
f5750a30e3e6a7bd3b68cdde1521e874
256 megabytes
["4 3\n1 2\n1 3\n1 4", "2 0\n1 2", "6 2\n1 6\n2 4\n2 6\n3 6\n5 6", "6 3\n1 2\n1 5\n2 3\n3 4\n5 6"]
PASSED
import sys from collections import deque input = lambda :sys.stdin.buffer.readline() mi = lambda :map(int,input().split()) li = lambda :list(mi()) mod = 998244353 N,K = mi() edge = [[] for i in range(N)] for _ in range(N-1): a,b = mi() edge[a-1].append(b-1) edge[b-1].append(a-1) parent = [-1 for i in range(N)] deq = deque([0]) res = [] while deq: v = deq.popleft() res.append(v) for nv in edge[v]: if nv!=parent[v]: parent[nv] = v deq.append(nv) dp = [[1] for i in range(N)] def merge(v,nv): res_dp = [0 for i in range(max(len(dp[v]),len(dp[nv])+1))] for i in range(len(dp[v])): for j in range(len(dp[nv])): if j+1+i <= K: res_dp[max(j+1,i)] += dp[v][i] * dp[nv][j] res_dp[max(j+1,i)] %= mod res_dp[i] += dp[v][i] * dp[nv][j] res_dp[i] %= mod dp[v] = res_dp for v in res[::-1]: for nv in edge[v]: if nv==parent[v]: continue merge(v,nv) print(sum(dp[0][i] for i in range(min(K+1,len(dp[0])))) % mod)
1616079000
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["2", "1", "-1", "3"]
20e13f21610c5614310bcd764662231c
NoteImagine we have string a = a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string. We will call string alal + 1al + 2...ar (1 ≤ l ≤ r ≤ |a|) the substring [l, r] of the string a. The substring [l, r] is unique in a if and only if there is no pair l1, r1 such that l1 ≠ l and the substring [l1, r1] is equal to the substring [l, r] in a.
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.
Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.
The first line of input contains s1 and the second line contains s2 (1 ≤ |s1|, |s2| ≤ 5000). Both strings consist of lowercase Latin letters.
standard output
standard input
Python 2
Python
2,200
train_045.jsonl
d03cd113f1d50fdebcc833d4e601fe15
512 megabytes
["apple\npepperoni", "lover\ndriver", "bidhan\nroy", "testsetses\nteeptes"]
PASSED
import sys import bisect class suffixautomaton: def __init__(self, words, symbol = "#"): self.words = [] self.sequence = "" self.terminal = set() self.nCounters = len(words) self.states = [[0, None, {}]] self.counters = [[0] * self.nCounters] for w in words: self.sequence += w self.words.append(len(self.sequence)) self.sequence += symbol symbol = chr(ord(symbol)+1) pushback = [] sz = 1 last = 0 for ci in range(len(self.sequence)): c = self.sequence[ci] cur = sz sz += 1 self.states.append([self.states[last][0] + 1, None, {}]) self.counters.append([0] * self.nCounters) word = bisect.bisect_left(self.words, ci) self.counters[-1][word] = 1 pushback.append((self.states[last][0] + 1, cur)) p = last while p <> None and c not in self.states[p][2]: self.states[p][2][c] = cur p = self.states[p][1] if p == None: self.states[cur][1] = 0 else: q = self.states[p][2][c] if (self.states[p][0] + 1 == self.states[q][0]): self.states[cur][1] = q else: clone = sz sz += 1 pushback.append((self.states[p][0] + 1, clone)) self.states.append([self.states[p][0] + 1, self.states[q][1], self.states[q][2].copy()]) self.counters.append([0] * self.nCounters) while p <> None and self.states[p][2][c] == q: self.states[p][2][c] = clone p = self.states[p][1] self.states[cur][1] = clone self.states[q][1] = clone last = cur pushback.sort(reverse = True) for _, i in pushback: for j in range(self.nCounters): self.counters[self.states[i][1]][j] += self.counters[i][j] while last <> 0: self.terminal.add(last) last = self.states[last][1] def __repr__(self): S = "" for i, s in enumerate(self.states): S += str(i) + " - " + str(self.counters[i]) + " - " + str(s) + "\n" return S def CustomaryFunction1(self): """ Minimal non-repeating substring among all uploaded string""" best = sys.maxint for i in range(len(self.states)): if reduce(lambda a, b: a and b, [self.counters[i][j] == 1 for j in range(self.nCounters)]): best = min(best, self.states[self.states[i][1]][0] + 1) if best == sys.maxint: return -1 return best def solve(): a = sys.stdin.readline().strip("\n\r") b = sys.stdin.readline().strip("\n\r") A = suffixautomaton([a, b]) print A.CustomaryFunction1() solve()
1399044600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["3.650281539872885\n18.061819283610362\n32.052255376143336"]
ba27ac62b84705d80fa580567ab64c3b
NoteIn the first test case, the miners are at $$$(0,1)$$$ and $$$(0,-1)$$$, while the diamond mines are at $$$(1,0)$$$ and $$$(-2,0)$$$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $$$\sqrt2 + \sqrt5$$$.
Diamond Miner is a game that is similar to Gold Miner, but there are $$$n$$$ miners instead of $$$1$$$ in this game.The mining area can be described as a plane. The $$$n$$$ miners can be regarded as $$$n$$$ points on the y-axis. There are $$$n$$$ diamond mines in the mining area. We can regard them as $$$n$$$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $$$(0, 0)$$$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $$$(a,b)$$$ uses his hook to mine a diamond mine at the point $$$(c,d)$$$, he will spend $$$\sqrt{(a-c)^2+(b-d)^2}$$$ energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?
For each test case, print a single real number — the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of miners and mines. Each of the next $$$2n$$$ lines contains two space-separated integers $$$x$$$ ($$$-10^8 \le x \le 10^8$$$) and $$$y$$$ ($$$-10^8 \le y \le 10^8$$$), which represent the point $$$(x,y)$$$ to describe a miner's or a diamond mine's position. Either $$$x = 0$$$, meaning there is a miner at the point $$$(0, y)$$$, or $$$y = 0$$$, meaning there is a diamond mine at the point $$$(x, 0)$$$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $$$n$$$ and the number of points on the y-axis is equal to $$$n$$$. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,200
train_085.jsonl
1652e275a552117ec7b198955d3cc277
256 megabytes
["3\n2\n0 1\n1 0\n0 -1\n-2 0\n4\n1 0\n3 0\n-5 0\n6 0\n0 3\n0 1\n0 2\n0 4\n5\n3 0\n0 4\n0 -3\n4 0\n2 0\n1 0\n-3 0\n0 -10\n0 -2\n0 -10"]
PASSED
mas = list(map(int, input().split())) t = mas[0] for j in range(t): mas = list(map(int, input().split())) n = mas[0] lst1 = [0 for i in range(n)] lst2 = [0 for i in range(n)] i1 = 0 i2 = 0 for i in range(2 * n): mas = list(map(int, input().split())) if (mas[0] == 0): lst1[i1] = mas[1] ** 2 i1 += 1 else: lst2[i2] = mas[0] ** 2 i2 += 1 lst1.sort() lst2.sort() s = 0 for i in range(n): s += (lst1[i] + lst2[i]) ** 0.5 print(s)
1615377900
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["4\n14\n26\n48"]
8775da9b78d8236c4606d150df450952
NoteIn the second test case: The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$. The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$ The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$. The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$. The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$. The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.
Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
For each test case print a single integer — the answer to the problem.
The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.
standard output
standard input
Python 3
Python
1,100
train_090.jsonl
9068b9ec11a55bab8da6fbd3cfb2372d
256 megabytes
["4\n2\n1 2\n3\n2 0 1\n4\n2 0 5 1\n5\n0 1 1 0 1"]
PASSED
def max(array): count = 0 for i in array: if i==0: count +=2 else: count +=1 return count for line in [*open(0)][2::2]: array = list(map(int,line.split())) maximum = 0 for i in range(len(array)): for j in range(i +1,len(array)+1): maximum += max(array[i:j]) print(maximum)
1644676500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1/2", "0/1"]
7afa48f3411521ce49ba9595b0bef079
null
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that in other words, n is multiplication of all elements of the given array.Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that , where is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7.Please note that we want of p and q to be 1, not of their remainders after dividing by 109 + 7.
In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7.
The first line of input contains a single integer k (1 ≤ k ≤ 105) — the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≤ ai ≤ 1018) — the elements of the array.
standard output
standard input
Python 3
Python
2,000
train_009.jsonl
c629b9e68106c7576bc6fbddfd056d70
256 megabytes
["1\n2", "3\n1 1 1"]
PASSED
k = int(input()) MOD = 10 ** 9 + 7 antithree = pow(3, MOD - 2, MOD) antitwo = pow(2, MOD - 2, MOD) power = 1 parity = False for t in map(int, input().split()): power *= t power %= MOD - 1 if t % 2 == 0: parity = True q = pow(2, power, MOD) * antitwo q %= MOD if parity: p = (q + 1) * antithree p %= MOD else: p = (q - 1) * antithree p %= MOD print(p, q, sep = '/')
1468514100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["1\n2", "2\n3 4", "-1"]
5bb8347fd91f00245c3acb4a5eeaf17f
null
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.Find the minimum possible number of moves required to make the colors of all edges equal.
If there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them.
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci () providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.
standard output
standard input
Python 3
Python
2,200
train_002.jsonl
aecfdaee4114ac7d34901855415dcc66
256 megabytes
["3 3\n1 2 B\n3 1 R\n3 2 B", "6 5\n1 3 R\n2 3 R\n3 4 B\n4 5 R\n4 6 R", "4 5\n1 2 R\n1 3 R\n2 3 B\n3 4 B\n1 4 B"]
PASSED
from collections import deque n, m = map(int, input().split()) adj = [[] for i in range(n)] for i in range(m): u, v, c = input().split() u, v = int(u)-1, int(v)-1 adj[u].append((v, c)) adj[v].append((u, c)) visited = S = T = None def bfs(i, k): q = deque([(i, 0)]) while q: u, p = q.pop() if visited[u] >= 0: if visited[u] == p: continue else: return False visited[u] = p if p: S.append(u) else: T.append(u) for v, c in adj[u]: nxt = p if c == k else p^1 q.appendleft((v, nxt)) return True def solve(k): global visited, S, T visited = [-1]*n res = [] for i in range(n): if visited[i] < 0: S, T = [], [] if not bfs(i, k): return [0]*(n+1) else: res.extend(S if len(S) < len(T) else T) return res res1 = solve("R") res2 = solve("B") if min(len(res1), len(res2)) > n: print (-1) else: print (min(len(res1), len(res2))) print (" ".join(map(lambda x: str(x+1), res1 if len(res1) < len(res2) else res2)))
1460729700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0\n3\n11\n72\n63244"]
d78cd4a06fb566d58275e92f976166f2
null
Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things: Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one); Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves: You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$. You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$. You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$. You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$. You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the lower bound on the sum of the array.
standard output
standard input
Python 3
Python
1,100
train_005.jsonl
448b264d1586de8f2cc29330307ee72c
256 megabytes
["5\n1\n5\n42\n1337\n1000000000"]
PASSED
import math t=int(input()) while t: t-=1 n=int(input()) if n==1 : print(0) elif n==2: print(1) else: mx=n c=0 for i in range(max(2,round(math.sqrt(n))-1),round(math.sqrt(n))+1): tem=i-1+math.ceil((n-i)/i) mx=min(tem,mx) print(mx)
1601280300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1212212", "0\n1212212", "2\n1212212"]
ad3f798f00cc9f3e3c9df932c2459ca3
NoteExplanation for the first sample: vertices $$$2$$$ and $$$5$$$ are Oddyseys. Explanation for the third sample: vertices $$$1$$$ and $$$6$$$ are Oddyseys.
Lee was planning to get closer to Mashtali's heart to proceed with his evil plan(which we're not aware of, yet), so he decided to beautify Mashtali's graph. But he made several rules for himself. And also he was too busy with his plans that he didn't have time for such minor tasks, so he asked you for help.Mashtali's graph is an undirected weighted graph with $$$n$$$ vertices and $$$m$$$ edges with weights equal to either $$$1$$$ or $$$2$$$. Lee wants to direct the edges of Mashtali's graph so that it will be as beautiful as possible.Lee thinks that the beauty of a directed weighted graph is equal to the number of its Oddysey vertices. A vertex $$$v$$$ is an Oddysey vertex if $$$|d^+(v) - d^-(v)| = 1$$$, where $$$d^+(v)$$$ is the sum of weights of the outgoing from $$$v$$$ edges, and $$$d^-(v)$$$ is the sum of the weights of the incoming to $$$v$$$ edges.Find the largest possible beauty of a graph that Lee can achieve by directing the edges of Mashtali's graph. In addition, find any way to achieve it.Note that you have to orient each edge.
In the first line print a single integer — the maximum beauty of the graph Lee can achieve. In the second line print a string of length $$$m$$$ consisting of $$$1$$$s and $$$2$$$s — directions of the edges. If you decide to direct the $$$i$$$-th edge from vertex $$$u_i$$$ to vertex $$$v_i$$$, $$$i$$$-th character of the string should be $$$1$$$. Otherwise, it should be $$$2$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n \le 10^5;\; 1 \le m \le 10^5)$$$ — the numbers of vertices and edges in the graph. The $$$i$$$-th line of the following $$$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;\; \bf{w_i \in \{1, 2\}} )$$$ — the endpoints of the $$$i$$$-th edge and its weight. Note that the graph doesn't have to be connected, and it might contain multiple edges.
standard output
standard input
PyPy 3-64
Python
3,000
train_085.jsonl
7b448deff90878934c7945b456799622
256 megabytes
["6 7\n1 2 1\n1 3 2\n2 3 2\n1 4 1\n4 5 1\n2 5 2\n2 6 2", "6 7\n1 2 2\n1 3 2\n2 3 2\n1 4 2\n4 5 2\n2 5 2\n2 6 2", "6 7\n1 2 1\n1 3 1\n2 3 1\n1 4 1\n4 5 1\n2 5 1\n2 6 1"]
PASSED
import sys input = sys.stdin.readline n, m = map(int, input().split()) adj1 = [[] for _ in range(n)] adj2 = [[] for _ in range(n)] edges = [] outv = 0 outvv = 0 deg1 = [0] * n deg2 = [0] * n parO = [] parP = [] for e in range(m): u, v, w = map(int, input().split()) u -= 1 v -= 1 parO.append(u) parP.append(v) if w == 1: adj1[u].append((v,e)) adj1[v].append((u,e)) deg1[u] += 1 deg1[v] += 1 else: adj2[u].append((v,e)) adj2[v].append((u,e)) deg2[u] += 1 deg2[v] += 1 used = [False] * m # w = 1 p1 = [] p1e = [] for curr in range(n): if deg1[curr] % 2 == 0: continue else: outvv += 1 u = curr path = [u] pe = [] while adj1[u]: v, e = adj1[u].pop() if not used[e]: path.append(v) pe.append(e) u = v used[e] = True if len(path) > 1: outv += 1 p1.append(path) p1e.append(pe) curr = 0 while curr < n: u = curr path = [u] pe = [] while adj1[u]: v, e = adj1[u].pop() if not used[e]: path.append(v) pe.append(e) u = v used[e] = True if len(path) > 1: p1.append(path) p1e.append(pe) else: curr += 1 # w = 2 p2 = [] p2e = [] for curr in range(n): if deg2[curr] % 2 == 0: continue u = curr path = [u] pe = [] while adj2[u]: v, e = adj2[u].pop() if not used[e]: path.append(v) pe.append(e) u = v used[e] = True if len(path) > 1: p2.append(path) p2e.append(pe) curr = 0 while curr < n: u = curr path = [u] pe = [] while adj2[u]: v, e = adj2[u].pop() if not used[e]: path.append(v) pe.append(e) u = v used[e] = True if len(path) > 1: p2.append(path) p2e.append(pe) else: curr += 1 assert(all(used)) adj3 = list(range(n)) adj4 = list(range(n)) for p in p1: if p[0] != p[-1]: adj3[p[0]] = p[-1] adj3[p[-1]] = p[0] for p in p2: if p[0] != p[-1]: adj4[p[0]] = p[-1] adj4[p[-1]] = p[0] colors = [0] * n for i in range(n): if colors[i] == 0: stack = [i] colors[i] = 1 while stack: nex = stack.pop() if colors[adj3[nex]] == 0: colors[adj3[nex]] = -colors[nex] stack.append(adj3[nex]) if colors[adj4[nex]] == 0: colors[adj4[nex]] = -colors[nex] stack.append(adj4[nex]) par = [-1] * m for i in range(len(p1)): p = p1[i] pe = p1e[i] assert p[0] == p[-1] or colors[p[0]] != colors[p[-1]] if colors[p[0]] == 1: for v, e in zip(p[:-1], pe): par[e] = v else: for v, e in zip(p[1:], pe): par[e] = v for i in range(len(p2)): p = p2[i] pe = p2e[i] assert p[0] == p[-1] or colors[p[0]] != colors[p[-1]] if colors[p[0]] == -1: for v, e in zip(p[:-1], pe): par[e] = v else: for v, e in zip(p[1:], pe): par[e] = v out = [] for i in range(m): assert par[i] != -1 if par[i] == parO[i]: out.append(1) else: assert par[i] == parP[i] out.append(2) assert outvv == 2 * outv print(2 * outv) print(''.join(map(str,out)))
1637678100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["-1\n2\n2\n1\n2\n0"]
8e7c0b703155dd9b90cda706d22525c9
NoteLet us demonstrate one of the suboptimal ways of getting a pair $$$(3, 5)$$$: Using an operation of the first type with $$$k=1$$$, the current pair would be equal to $$$(1, 1)$$$. Using an operation of the third type with $$$k=8$$$, the current pair would be equal to $$$(-7, 9)$$$. Using an operation of the second type with $$$k=7$$$, the current pair would be equal to $$$(0, 2)$$$. Using an operation of the first type with $$$k=3$$$, the current pair would be equal to $$$(3, 5)$$$.
William has two numbers $$$a$$$ and $$$b$$$ initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $$$k$$$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a new positive integer $$$k$$$) add number $$$k$$$ to both $$$a$$$ and $$$b$$$, or add number $$$k$$$ to $$$a$$$ and subtract $$$k$$$ from $$$b$$$, or add number $$$k$$$ to $$$b$$$ and subtract $$$k$$$ from $$$a$$$. Note that after performing operations, numbers $$$a$$$ and $$$b$$$ may become negative as well.William wants to find out the minimal number of operations he would have to perform to make $$$a$$$ equal to his favorite number $$$c$$$ and $$$b$$$ equal to his second favorite number $$$d$$$.
For each test case output a single number, which is the minimal number of operations which William would have to perform to make $$$a$$$ equal to $$$c$$$ and $$$b$$$ equal to $$$d$$$, or $$$-1$$$ if it is impossible to achieve this using the described operations.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$c$$$ and $$$d$$$ $$$(0 \le c, d \le 10^9)$$$, which are William's favorite numbers and which he wants $$$a$$$ and $$$b$$$ to be transformed into.
standard output
standard input
PyPy 3-64
Python
800
train_107.jsonl
e6592197408f88075d44bee115a12e51
256 megabytes
["6\n1 2\n3 5\n5 3\n6 6\n8 0\n0 0"]
PASSED
for _ in range(int(input())): a,b=map(int,input().split()) if a==0 and b==0: print(0) elif a==b: print(1) elif abs(a-b)&1==0: print(2) else: print(-1)
1630247700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]