prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
⌀ | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
⌀ | prob_desc_input_spec
stringlengths 38
2.42k
⌀ | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
⌀ | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
sequencelengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
sequencelengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 seconds | ["1\n0\n2\n3\n5\n141\n53384\n160909\n36"] | efdb966e414050c5e51e8beb7bb06b20 | NoteIn the first test case, the only special pair is $$$(3, 2)$$$.In the second test case, there are no special pairs.In the third test case, there are two special pairs: $$$(3, 2)$$$ and $$$(4, 3)$$$. | A pair of positive integers $$$(a,b)$$$ is called special if $$$\lfloor \frac{a}{b} \rfloor = a \bmod b$$$. Here, $$$\lfloor \frac{a}{b} \rfloor$$$ is the result of the integer division between $$$a$$$ and $$$b$$$, while $$$a \bmod b$$$ is its remainder.You are given two integers $$$x$$$ and $$$y$$$. Find the number of special pairs $$$(a,b)$$$ such that $$$1\leq a \leq x$$$ and $$$1 \leq b \leq y$$$. | For each test case print the answer on a single line. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$x$$$, $$$y$$$ ($$$1 \le x,y \le 10^9$$$). | standard output | standard input | Python 3 | Python | 1,700 | train_092.jsonl | a4e271d3387f754cea40c0432268f71d | 256 megabytes | ["9\n3 4\n2 100\n4 3\n50 3\n12 4\n69 420\n12345 6789\n123456 789\n12345678 9"] | PASSED | for test_case in range(int(input())):
x,y = map(int,input().split())
res = 0
k = 1
while k*(k+1) < x and k < y:
res += min(y,x//k-1)-k
k += 1
print(res)
| 1613141400 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["3\n1\n7"] | ce9a0649ccfc956559254f324dfa02a7 | NoteFor the first integer the optimal choice is $$$b = 1$$$, then $$$a \oplus b = 3$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$3$$$ and $$$0$$$ is $$$3$$$.For the second integer one optimal choice is $$$b = 2$$$, then $$$a \oplus b = 1$$$, $$$a \> \& \> b = 2$$$, and the greatest common divisor of $$$1$$$ and $$$2$$$ is $$$1$$$.For the third integer the optimal choice is $$$b = 2$$$, then $$$a \oplus b = 7$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$7$$$ and $$$0$$$ is $$$7$$$. | Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer $$$a$$$. You want to choose some integer $$$b$$$ from $$$1$$$ to $$$a - 1$$$ inclusive in such a way that the greatest common divisor (GCD) of integers $$$a \oplus b$$$ and $$$a \> \& \> b$$$ is as large as possible. In other words, you'd like to compute the following function:$$$$$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$$$$$Here $$$\oplus$$$ denotes the bitwise XOR operation, and $$$\&$$$ denotes the bitwise AND operation.The greatest common divisor of two integers $$$x$$$ and $$$y$$$ is the largest integer $$$g$$$ such that both $$$x$$$ and $$$y$$$ are divided by $$$g$$$ without remainder.You are given $$$q$$$ integers $$$a_1, a_2, \ldots, a_q$$$. For each of these integers compute the largest possible value of the greatest common divisor (when $$$b$$$ is chosen optimally). | For each integer, print the answer in the same order as the integers are given in input. | The first line contains an integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of integers you need to compute the answer for. After that $$$q$$$ integers are given, one per line: $$$a_1, a_2, \ldots, a_q$$$ ($$$2 \le a_i \le 2^{25} - 1$$$) — the integers you need to compute the answer for. | standard output | standard input | Python 3 | Python | 1,500 | train_005.jsonl | c601e61ffe1146b3139782c911890e37 | 256 megabytes | ["3\n2\n3\n5"] | PASSED | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 06:35:25 2020
@author: Dark Soul
"""
import math
q=int(input(''))
for _ in range(q):
n=int(input(''))
ans=-1
if n&(n+1)==0:
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
ans=n//i
break
if ans==-1:
ans=1
print(ans)
continue
x=bin(n)
x=x[2:]
print((2**(len(x)))-1) | 1549546500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["9\n6\n1", "225\n2001\n6014\n6939"] | 6def7ffa0989d5c5bcab3ac456b231fb | NoteIn the example test, $$$n=2$$$. Thus, there are $$$3$$$ pigs at minute $$$1$$$, and $$$6$$$ pigs at minute $$$2$$$. There are three queries: $$$x=1$$$, $$$x=5$$$, and $$$x=6$$$.If the wolf wants to eat $$$1$$$ pig, he can do so in $$$3+6=9$$$ possible attack plans, depending on whether he arrives at minute $$$1$$$ or $$$2$$$.If the wolf wants to eat $$$5$$$ pigs, the wolf cannot arrive at minute $$$1$$$, since there aren't enough pigs at that time. Therefore, the wolf has to arrive at minute $$$2$$$, and there are $$$6$$$ possible attack plans.If the wolf wants to eat $$$6$$$ pigs, his only plan is to arrive at the end of the convention and devour everybody.Remember to output your answers modulo $$$10^9+7$$$! | Three little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the $$$n$$$-th minute, the convention ends.The big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and eat exactly $$$x$$$ pigs. Then he will get away.The wolf wants Gregor to help him figure out the number of possible attack plans that involve eating exactly $$$x$$$ pigs for various values of $$$x$$$ ($$$1 \le x \le 3n$$$). Two attack plans are considered different, if they occur at different times or if the sets of little pigs to eat are different.Note that all queries are independent, that is, the wolf does not eat the little pigs, he only makes plans! | You should print $$$q$$$ lines, with line $$$i$$$ representing the number of attack plans if the wolf wants to eat $$$x_i$$$ pigs. Since each query answer can be large, output each answer modulo $$$10^9+7$$$. | The first line of input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^6$$$, $$$1 \le q \le 2\cdot 10^5$$$), the number of minutes the convention lasts and the number of queries the wolf asks. Each of the next $$$q$$$ lines contains a single integer $$$x_i$$$ ($$$1 \le x_i \le 3n$$$), the number of pigs the wolf will eat in the $$$i$$$-th query. | standard output | standard input | PyPy 3 | Python | 2,500 | train_083.jsonl | 6ebee54968ad72be04e37731346968e1 | 512 megabytes | ["2 3\n1\n5\n6", "5 4\n2\n4\n6\n8"] | PASSED | import sys
import __pypy__
int_add = __pypy__.intop.int_add
int_sub = __pypy__.intop.int_sub
int_mul = __pypy__.intop.int_mul
def make_mod_mul(mod=10**9 + 7):
fmod_inv = 1.0 / mod
def mod_mul(a, b, c=0):
res = int_sub(int_add(int_mul(a, b), c), int_mul(mod, int(fmod_inv * a * b + fmod_inv * c)))
if res >= mod:
return res - mod
elif res < 0:
return res + mod
else:
return res
return mod_mul
mod_mul = make_mod_mul()
mod = 10**9 + 7
stream = sys.stdin
read = stream.readline
n, q = map(int, read().split())
sz = 3 * (n + 1)
fac = [0] * (sz + 1)
inv = [0] * (sz + 1)
fac[0] = 1
for i in range(1, sz + 1):
fac[i] = mod_mul(fac[i - 1], i)
inv[sz] = pow(fac[sz], mod - 2, mod)
for i in range(sz - 1, -1, -1):
inv[i] = mod_mul(inv[i + 1], (i + 1))
def nCr(n, r):
num = fac[n]
den = mod_mul(inv[n - r], inv[r])
return mod_mul(num, den)
coef = [nCr(3 * n + 3, i) for i in range(3 * n + 4)]
coef[0] -= 1
ret = [0] * (sz + 1)
for i in range(3 * n + 3, 2, -1):
mul = coef[i]
mul3 = mod_mul(3, mul)
ret[i - 3] = mul
coef[i] -= mul
coef[i - 1] -= mul3
coef[i - 2] -= mul3
if coef[i - 1] < 0:
coef[i - 1] += mod
if coef[i - 2] < 0:
coef[i - 2] += mod
outp = [0] * q
for i in range(q):
x = int(read())
outp[i] = str(ret[x])
print('\n'.join(outp))
| 1627828500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4 2 0", "16 9", "9999800001"] | faf1abdeb6f0cf34972d5cb981116186 | NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack. | Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board. | Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put. | The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n2)) — the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≤ xi, yi ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook. | standard output | standard input | Python 3 | Python | 1,200 | train_012.jsonl | 65687845e1fa13e5cf9e419a39b69bdf | 256 megabytes | ["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"] | PASSED | n, m = map(int, input().split())
ans = [n ** 2]
rows, cols = set(), set()
for i in range(m):
x, y = map(int, input().split())
res = ans[-1]
if x not in rows:
res -= (n - len(cols))
rows.add(x)
if y not in cols:
res -= (n - len(rows))
cols.add(y)
ans.append(res)
print(*ans[1:])
| 1469205300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6", "0", "2"] | f44041707694eece7de0cc7c087f57d9 | NoteIn the first example, you can set $$$a_{1, 1} := 7, a_{1, 2} := 8$$$ and $$$a_{1, 3} := 9$$$ then shift the first, the second and the third columns cyclically, so the answer is $$$6$$$. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is $$$0$$$.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $$$2$$$. | You are given a rectangular matrix of size $$$n \times m$$$ consisting of integers from $$$1$$$ to $$$2 \cdot 10^5$$$.In one move, you can: choose any element of the matrix and change its value to any integer between $$$1$$$ and $$$n \cdot m$$$, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some $$$j$$$ ($$$1 \le j \le m$$$) and set $$$a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$$$ simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ (i.e. $$$a_{i, j} = (i - 1) \cdot m + j$$$) with the minimum number of moves performed. | Print one integer — the minimum number of moves required to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ ($$$a_{i, j} = (i - 1)m + j$$$). | The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$$$) — the size of the matrix. The next $$$n$$$ lines contain $$$m$$$ integers each. The number at the line $$$i$$$ and position $$$j$$$ is $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 2 \cdot 10^5$$$). | standard output | standard input | PyPy 3 | Python | 1,900 | train_004.jsonl | fd525d26e93ea7482fa829b9eb3250df | 256 megabytes | ["3 3\n3 2 1\n1 2 3\n4 5 6", "4 3\n1 2 3\n4 5 6\n7 8 9\n10 11 12", "3 4\n1 6 3 4\n5 10 7 8\n9 2 11 12"] | PASSED | import sys
input = sys.stdin.readline
from collections import *
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(m):
l = [i+1]
for _ in range(n-1):
l.append(l[-1]+m)
s = set(l)
idx = defaultdict(int)
for j in range(n):
idx[l[j]] = j
cnt = [n]*n
for j in range(n):
if a[j][i] in s:
move = (j-idx[a[j][i]])%n
cnt[move] -= 1
mi = 10**18
for j in range(n):
mi = min(mi, j+cnt[j])
ans += mi
print(ans) | 1579703700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds | ["YES\n3 1\n4 1\n1 2\n5 2\n2 6", "NO", "YES\n2 9\n2 10\n10 3\n3 1\n6 10\n8 2\n4 3\n5 6\n6 7", "YES\n2 5\n7 2\n3 7\n3 1\n1 6\n8 7\n4 3"] | a4849505bca48b408a5e8fb5aebf5cb6 | null | You are given three integers $$$n$$$, $$$d$$$ and $$$k$$$.Your task is to construct an undirected tree on $$$n$$$ vertices with diameter $$$d$$$ and degree of each vertex at most $$$k$$$, or say that it is impossible.An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $$$u$$$ it is the number of edges $$$(u, v)$$$ that belong to the tree, where $$$v$$$ is any other vertex of a tree). | If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print $$$n - 1$$$ lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from $$$1$$$ to $$$n$$$. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 | The first line of the input contains three integers $$$n$$$, $$$d$$$ and $$$k$$$ ($$$1 \le n, d, k \le 4 \cdot 10^5$$$). | standard output | standard input | Python 2 | Python | 2,100 | train_002.jsonl | 67d367d8f6c84392f200638e9f4aab1b | 256 megabytes | ["6 3 3", "6 2 3", "10 4 3", "8 5 3"] | PASSED | n,d,k=map(int,raw_input().strip().split())
ans=[]
if (d>n-1):
print ("NO")
exit(0)
if (k<2 and n>2):
print ("NO")
exit(0)
l1=[0 for i in range(d+2)]
count=d
cnt=d+2
def insert(par,v,r,e):
global count
global cnt
if count==n-1:
print ("YES")
for o in ans:
print o[0],o[1]
exit(0)
else:
ans.append([par,v])
cnt=cnt+1
count=count+1
if (e==0):
return
while(r!=0):
insert(v,cnt,k-1,e-1)
r=r-1
return
for i in range(1,d+1):
ans.append([i,i+1])
for i in range(1,d+2):
l1[i]=min(i-1,d+1-i)
for i in range(2,d+1):
r=k-2
while(r!=0):
insert(i,cnt,k-1,l1[i]-1)
r=r-1
if (count<n-1):
print ("NO")
else:
print ("YES")
for o in ans:
print o[0],o[1]
exit(0) | 1530628500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["NO\nYES\nNO\nYES\nYES"] | 26354d2628f26eb2eff9432bd46400d5 | NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$. | You have a board represented as a grid with $$$2 \times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically? | For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and NO, otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \le w, b \le n$$$). | standard output | standard input | Python 3 | Python | 800 | train_104.jsonl | 66083bccd6f1853bc132b8d95906a948 | 256 megabytes | ["5\n1 0 1\n1 0\n1 1 1\n0 0\n3 0 0\n1 3\n4 3 1\n2 2\n5 4 3\n3 1"] | PASSED | t=int(input())
for y in range(t):
n,k1,k2=map(int,input().split())
w,b=map(int,input().split())
kw=k1+k2
to=kw//2
tob=(n*2-kw)//2
# print(to)
if w<=to:
# print("this w")
w=0
avil=to-w
else:
# print("w n")
print("NO")
continue
# avil=avil+(n-to)
if b<=tob :
# print("this b")
b=0
else:
# print("b n")
print("NO")
continue
# print("above")
if w==0 and b==0:
print("YES")
| 1616079000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2", "2"] | 3cafbcf1a397def07d6a2d1dd5526281 | NoteIn the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses. | You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition. | On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1. | The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the sizes of the sheet of paper. Each of the next n lines contains m characters — the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty. | standard output | standard input | Python 2 | Python | 1,700 | train_036.jsonl | e9dce08673ebe48f1007ef3c91a107f7 | 256 megabytes | ["5 4\n####\n#..#\n#..#\n#..#\n####", "5 5\n#####\n#...#\n#####\n#...#\n#####"] | PASSED | from sys import setrecursionlimit
setrecursionlimit(3000)
def main():
n,m = map(int, raw_input().split())
S, total = [], 0
for i in xrange(n):
t = map(lambda s: 1 if s == "#" else 0, raw_input())
S.append(t)
total += sum(t)
if total in (1,2):
print -1
return
if total == 3:
print 1
return
def f():
for i in xrange(n):
for j in xrange(m):
if S[i][j]: return (i,j)
def neibors(l,r):
for dl, dr in [(1,0), (0,1), (0,-1), (-1,0)]:
lk, rk = l+dl, r+dr
if (lk >= 0) and (rk >= 0) and (lk < n) and (rk < m) and S[lk][rk]:
yield (lk, rk)
first, used, tin, up = f(), set(), {}, {}
def dfs((l,r), timer, p):
used.add((l,r))
tin[(l,r)] = up[(l,r)] = timer
timer += 1
childs = 0
for lk, rk in neibors(l,r):
if (lk,rk) == p: continue
if (lk,rk) in used:
up[(l,r)] = min(up[(l,r)], tin[(lk,rk)])
else:
timer = dfs((lk,rk), timer, (l,r))
up[(l,r)] = min(up[(l,r)], up[(lk,rk)])
if (up.get((lk, rk)) >= tin.get((l,r)) and p != -1):
print 1
exit(0)
childs += 1
if p == -1 and childs > 1:
print 1
exit(0)
return timer
dfs(first, 0, -1)
print 2
main() | 1338737400 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["7", "105", "761141116"] | 40a5e4b4193901cb3004dac24dba1d62 | NoteIn the first example, the answer is the sum of the first three numbers written out ($$$1 + 2 + 4 = 7$$$).In the second example, the numbers with numbers from $$$5$$$ to $$$14$$$: $$$5, 7, 9, 6, 8, 10, 12, 14, 16, 18$$$. Their sum is $$$105$$$. | Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers ($$$1, 3, 5, 7, \ldots$$$), and the second set consists of even positive numbers ($$$2, 4, 6, 8, \ldots$$$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: $$$1, 2, 4, 3, 5, 7, 9, 6, 8, 10$$$. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from $$$l$$$ to $$$r$$$ for given integers $$$l$$$ and $$$r$$$. The answer may be big, so you need to find the remainder of the division by $$$1000000007$$$ ($$$10^9+7$$$).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem. | Print a single integer — the answer modulo $$$1000000007$$$ ($$$10^9+7$$$). | The first line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 10^{18}$$$) — the range in which you need to find the sum. | standard output | standard input | PyPy 2 | Python | 1,800 | train_001.jsonl | 2722d2f1479cbd19c93dfd9142a191b1 | 256 megabytes | ["1 3", "5 14", "88005553535 99999999999"] | PASSED | def ways(l):
if l == 0:
return 0
count = 0
p=l
while p>=2:
p=p/2
count += 1
odd=count/2
even=count/2
if count%2==1:
odd += 1
ans=0
odd_terms=(pow(4,odd)-1)/3
even_terms=(2*(pow(4,even)-1))/3
total=odd_terms+even_terms
ans += pow(odd_terms,2,mod)
ans += (even_terms*(even_terms+1))%mod
if l-total !=0:
if count % 2 == 0:
rem=l-even_terms
ans += (pow(rem,2)-pow(odd_terms,2))%mod
else:
rem=l-odd_terms
ans += (rem*(rem+1)-(even_terms*(even_terms+1)))%mod
return ans
mod =1000000007
l,r=map(int,raw_input().split())
l=l-1
print (ways(r)%mod-ways(l)%mod)%mod
#print ways(r)
#print ways(l) | 1555601700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds | ["3\n\n4\n\n5\n\n\n1\n\n4\n\n6"] | 7a9b559eb3b601590e22eb128f2bf307 | NoteTest Case 1:In this case, the hidden password is $$$2$$$.The first query is $$$3$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$1$$$ since $$$2\oplus_2 1=3$$$.The second query is $$$4$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$5$$$ since $$$1\oplus_2 5=4$$$.The third query is $$$5$$$. It is equal to the current password. So, $$$1$$$ is returned, and the job is done.Test Case 2:In this case, the hidden password is $$$3$$$.The first query is $$$1$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$7$$$ since $$$3\oplus_3 7=1$$$. $$$[3=(10)_3$$$, $$$7=(21)_3$$$, $$$1=(01)_3$$$ and $$$(10)_3\oplus_3 (21)_3 = (01)_3]$$$.The second query is $$$4$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$6$$$ since $$$7\oplus_3 6=4$$$. $$$[7=(21)_3$$$, $$$6=(20)_3$$$, $$$4=(11)_3$$$ and $$$(21)_3\oplus_3 (20)_3 = (11)_3]$$$.The third query is $$$6$$$. It is equal to the current password. So, $$$1$$$ is returned, and the job is done.Note that these initial passwords are taken just for the sake of explanation. In reality, the grader might behave differently because it is adaptive. | This is the hard version of the problem. The only difference is that here $$$2\leq k\leq 100$$$. You can make hacks only if both the versions of the problem are solved.This is an interactive problem!Every decimal number has a base $$$k$$$ equivalent. The individual digits of a base $$$k$$$ number are called $$$k$$$-its. Let's define the $$$k$$$-itwise XOR of two $$$k$$$-its $$$a$$$ and $$$b$$$ as $$$(a + b)\bmod k$$$.The $$$k$$$-itwise XOR of two base $$$k$$$ numbers is equal to the new number formed by taking the $$$k$$$-itwise XOR of their corresponding $$$k$$$-its. The $$$k$$$-itwise XOR of two decimal numbers $$$a$$$ and $$$b$$$ is denoted by $$$a\oplus_{k} b$$$ and is equal to the decimal representation of the $$$k$$$-itwise XOR of the base $$$k$$$ representations of $$$a$$$ and $$$b$$$. All further numbers used in the statement below are in decimal unless specified.You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between $$$0$$$ and $$$n-1$$$ inclusive. So, you have decided to guess it. Luckily, you can try at most $$$n$$$ times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was $$$x$$$, and you guess a different number $$$y$$$, then the system changes the password to a number $$$z$$$ such that $$$x\oplus_{k} z=y$$$. Guess the password and break into the system. | null | The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) denoting the number of test cases. $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) and $$$k$$$ $$$(2\leq k\leq 100)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$. | standard output | standard input | PyPy 2 | Python | 2,200 | train_091.jsonl | 36f6ccc85cec8eb345d82cf04662655e | 256 megabytes | ["2\n5 2\n\n0\n\n0\n\n1\n5 3\n\n0\n\n0\n\n1"] | PASSED | from __future__ import division, print_function
import os,sys
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
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int, input().split())
def msj(): return map(str,input().strip().split(" "))
def le(): return list(map(int,input().split()))
def rc(): return map(float,input().split())
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
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 # min index where x is not less than num
def upper_bound(li, num):
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 # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
hoi=int(2**20)
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
def hu(a,b,opp):
d=1
c=0
while(0<b or 0<a):
c=c+(((b%opp)+(a%opp))%opp)*d
a=a//opp
b=b//opp
d=opp*d
return c
def rw(u,opp):
c=0
d=1
while(0<u):
c=c+((-u%opp)%opp)*d
u=u//opp
d=opp*d
return c
soi=int(1e9)
boi=int(1e9-7)
doi=int(1e9+7)
def main():
import sys
import math as my
input=sys.stdin.readline
y="Yes"
n="No"
for i in range(so()):
#c=0
op,opp=mj()
c=0
for i in range(op):
if(not i%2):
z=i
else:
z=rw(i,opp)
uo=hu(z,c,opp)
print(uo)
sys.stdout.flush()
oppp=so()
if(1==oppp):
break
if(-1==oppp):
return
c=hu(rw(c,opp),uo,opp)
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read() | 1625668500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["2.5000000000", "2.0000000000"] | d79166497eb61d81fdfa4ef80ec1c8e8 | NoteConsider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit. | Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street? | Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9. | The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 109) — the number of lanterns and the length of the street respectively. The next line contains n integers ai (0 ≤ ai ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street. | standard output | standard input | PyPy 2 | Python | 1,200 | train_000.jsonl | 3bc2feb6d2d9d557e6445f1256210d72 | 256 megabytes | ["7 15\n15 5 3 7 9 14 0", "2 5\n2 5"] | PASSED | y=int(raw_input().split()[1])
b=raw_input().split()
for c in range(len(b)):
b[c]=int(b[c])
b.sort()
p=float(b[0]-0)
q=float(y-b[-1])
#print p,q
z=0
ans=0
while z+1<=len(b)-1:
m=b[z+1]-b[z]
if m>ans:
ans=m
z+=1
ans=ans/2.0
#print ans
print max(p,q,ans) | 1417451400 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["12", "9", "4", "4", "3"] | c9c65223b8575676647fe943f8dff25a | null | You have to restore the wall. The wall consists of $$$N$$$ pillars of bricks, the height of the $$$i$$$-th pillar is initially equal to $$$h_{i}$$$, the height is measured in number of bricks. After the restoration all the $$$N$$$ pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $$$A$$$; remove a brick from the top of one non-empty pillar, the cost of this operation is $$$R$$$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $$$M$$$.You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $$$0$$$.What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height? | Print one integer — the minimal cost of restoration. | The first line of input contains four integers $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \le N \le 10^{5}$$$, $$$0 \le A, R, M \le 10^{4}$$$) — the number of pillars and the costs of operations. The second line contains $$$N$$$ integers $$$h_{i}$$$ ($$$0 \le h_{i} \le 10^{9}$$$) — initial heights of pillars. | standard output | standard input | PyPy 3 | Python | 2,100 | train_039.jsonl | 138a8320d475768651c6b25222c1b33e | 256 megabytes | ["3 1 100 100\n1 3 8", "3 100 1 100\n1 3 8", "3 100 100 1\n1 3 8", "5 1 2 4\n5 5 3 6 5", "5 1 2 2\n5 5 3 6 5"] | PASSED | # https://codeforces.com/contest/1355/problem/E
import bisect
def func(val):
cost = 0
toAdd,toRemove = 0,0
lessEqual = bisect.bisect_right(arr,val)
greater = n - lessEqual
toAdd = (lessEqual * val) - dp[lessEqual]
toRemove = (total - dp[lessEqual]) - (greater * val)
if toRemove >= toAdd:
confirmRemove = toRemove - toAdd
toRemove = toAdd
cost += (confirmRemove * R)
cost += min(toAdd * A + R * toRemove, toAdd * M)
else:
confirmAdd = toAdd - toRemove
cost += (confirmAdd * A)
toAdd = toRemove
cost += min(toAdd * A + R * toRemove, toAdd * M)
return cost
n, A, R, M = map(int, input().split())
arr = sorted([int(x) for x in input().split()])
dp = [0]
for item in arr:
dp.append(dp[-1]+item)
total = sum(arr)
ans = R * total
avg = total//n
heightsToCheck = arr + [avg,avg+1]
cost = min([func(h) for h in heightsToCheck])
print(min(ans,cost)) | 1589628900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["0", "2 1 3\n\n0"] | aea7e7220a8534c1053e8755a70dd499 | NoteWhen $$$n = 3$$$, any John's move can be reversed, thus $$$R(3) = 0$$$, and terminating the game immediately is correct.$$$R(4) = 1$$$, and one strategy to achieve this result is shown in the second sample case.Blank lines in sample interactions are for clarity and should not be printed. | This is an interactive problem.John and his imaginary friend play a game. There are $$$n$$$ lamps arranged in a circle. Lamps are numbered $$$1$$$ through $$$n$$$ in clockwise order, that is, lamps $$$i$$$ and $$$i + 1$$$ are adjacent for any $$$i = 1, \ldots, n - 1$$$, and also lamps $$$n$$$ and $$$1$$$ are adjacent. Initially all lamps are turned off.John and his friend take turns, with John moving first. On his turn John can choose to terminate the game, or to make a move. To make a move, John can choose any positive number $$$k$$$ and turn any $$$k$$$ lamps of his choosing on. In response to this move, John's friend will choose $$$k$$$ consecutive lamps and turn all of them off (the lamps in the range that were off before this move stay off). Note that the value of $$$k$$$ is the same as John's number on his last move. For example, if $$$n = 5$$$ and John have just turned three lamps on, John's friend may choose to turn off lamps $$$1, 2, 3$$$, or $$$2, 3, 4$$$, or $$$3, 4, 5$$$, or $$$4, 5, 1$$$, or $$$5, 1, 2$$$.After this, John may choose to terminate or move again, and so on. However, John can not make more than $$$10^4$$$ moves.John wants to maximize the number of lamps turned on at the end of the game, while his friend wants to minimize this number. Your task is to provide a strategy for John to achieve optimal result. Your program will play interactively for John against the jury's interactor program playing for John's friend.Suppose there are $$$n$$$ lamps in the game. Let $$$R(n)$$$ be the number of turned on lamps at the end of the game if both players act optimally. Your program has to terminate the game with at least $$$R(n)$$$ turned on lamps within $$$10^4$$$ moves. Refer to Interaction section below for interaction details.For technical reasons hacks for this problem are disabled. | null | null | standard output | standard input | Python 3 | Python | 2,600 | train_009.jsonl | adc11f1a9809409cbfd0da723c56abc9 | 512 megabytes | ["3", "4\n\n1"] | PASSED | #lizhou
n = int(input())
a = [0]*n
r = max(int(n-k-n/k+1) for k in range(1, n+1))
for i in range(1, n+1):
if int(n-i-n/i+1) == r:
k = i
break
def query(b):
for x in b:
a[x] = 1
print(k, end = " ")
print(*[x+1 for x in b])
x = int(input())-1
for i in range(k):
a[(x+i)%n] = 0
while True:
b = []
for i in range(n):
if a[i] == 0 and i%k < k-1 and i != n-1:
b.append(i)
if len(b) < k: break
query(b[:k])
if sum(a) >= r: break
print(0) | 1592491500 | [
"math",
"games"
] | [
1,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["4\n0\n1\n14"] | 9ca9df1ab3760edb8e7adc3be533c576 | NoteIn the first test case, there are three ways to draw the $$$2$$$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones): We see that the third way gives the maximum number of intersections, namely $$$4$$$.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords $$$1-3$$$ and $$$2-4$$$, as shown below: | On a circle lie $$$2n$$$ distinct points, with the following property: however you choose $$$3$$$ chords that connect $$$3$$$ disjoint pairs of points, no point strictly inside the circle belongs to all $$$3$$$ chords. The points are numbered $$$1, \, 2, \, \dots, \, 2n$$$ in clockwise order.Initially, $$$k$$$ chords connect $$$k$$$ pairs of points, in such a way that all the $$$2k$$$ endpoints of these chords are distinct.You want to draw $$$n - k$$$ additional chords that connect the remaining $$$2(n - k)$$$ points (each point must be an endpoint of exactly one chord).In the end, let $$$x$$$ be the total number of intersections among all $$$n$$$ chords. Compute the maximum value that $$$x$$$ can attain if you choose the $$$n - k$$$ chords optimally.Note that the exact position of the $$$2n$$$ points is not relevant, as long as the property stated in the first paragraph holds. | For each test case, output the maximum number of intersections that can be obtained by drawing $$$n - k$$$ additional chords. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le n$$$) — half the number of points and the number of chords initially drawn. Then $$$k$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, \, y_i \le 2n$$$, $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th chord. It is guaranteed that the $$$2k$$$ numbers $$$x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$$$ are all distinct. | standard output | standard input | PyPy 3-64 | Python | 1,800 | train_098.jsonl | 34dad85d1d2e8c565c3605b1aa09d1bd | 256 megabytes | ["4\n4 2\n8 2\n1 5\n1 1\n2 1\n2 0\n10 6\n14 6\n2 20\n9 10\n13 18\n15 12\n11 7"] | PASSED | import sys
input = sys.stdin.readline
inf = float('inf')
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
t = getInt()
# t = 1
def solve():
n, k = getList()
a = [sorted(getList()) for _ in range(k)]
g = set(range(1, 2*n+1))
u = set(sum(a, []))
g = sorted(g-u)
for i in range(len(g)//2):
a.append([g[i], g[(i+(n-k))]])
def intersect(a, b):
u = [max(a[0], b[0]), min(a[1], b[1])]
return u[0] <= u[1] and u != a and u != b
res = 0
for i in range(n):
for j in range(i):
res += intersect(a[i], a[j])
print(res)
for _ in range(t):
solve()
| 1627223700 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler", "icm codeforces\nicm technex"] | 3c06e3cb2d8468e738b736a9bf88b4ca | NoteIn first example, the killer starts with ross and rachel. After day 1, ross is killed and joey appears. After day 2, rachel is killed and phoebe appears. After day 3, phoebe is killed and monica appears. After day 4, monica is killed and chandler appears. | Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern. | Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order. | First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≤ n ≤ 1000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters. | standard output | standard input | PyPy 2 | Python | 900 | train_005.jsonl | 09bab30e474f73e8ae26b4980bbdfffd | 256 megabytes | ["ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler", "icm codeforces\n1\ncodeforces technex"] | PASSED | now_list = raw_input().split(' ')
n = int(raw_input())
print ' '.join(now_list)
for i in xrange(n):
x, y = raw_input().split(' ')
now_list.remove(x)
now_list.append(y)
print ' '.join(now_list)
| 1487861100 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["5\n60\n1439\n1180\n1"] | f4982de28aca7080342eb1d0ff87734c | null | New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases. | For each test case, print the answer on it — the number of minutes before the New Year. | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1439$$$) — the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \le h < 24$$$, $$$0 \le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros. | standard output | standard input | Python 3 | Python | 800 | train_015.jsonl | 55ad85192ed602a3b20444f16f87e522 | 256 megabytes | ["5\n23 55\n23 0\n0 1\n4 20\n23 59"] | PASSED | testCase = int(input())
Output = 0
while testCase != 0:
H, Min = map(int, input().split())
if 0 <= H < 24 and 0 <= Min < 60:
Output = ((23-H) * 60) + (60 - Min)
print(Output)
testCase = testCase - 1
| 1577552700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["First", "First", "Second"] | 2de867c08946eade5f674a98b377343d | null | Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. | If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). | The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. | standard output | standard input | Python 3 | Python | 1,900 | train_017.jsonl | f9c87f3bd177e15c586a426c71170373 | 256 megabytes | ["2 3\na\nb", "3 1\na\nb\nc", "1 2\nab"] | PASSED | N = 100000
Z = 26
#别用这玩意儿: trie = [[0] * Z] * N 巨坑!https://www.cnblogs.com/PyLearn/p/7795552.html
trie = [[0 for i in range(Z)] for j in range(N)]
n = 0
k = 0
nodeNum = 0
def insertNode():
u = 0
string = input()
global nodeNum
for i in range(len(string)):
c = ord(string[i]) - ord('a')
if trie[u][c] == 0:
nodeNum += 1
trie[u][c] = nodeNum
u = trie[u][c]
# print(u)
stateWin = [False for i in range(N)]
stateLose = [False for i in range(N)]
def dfs(u):
leaf = True
for c in range(Z):
if (trie[u][c]) != 0:
leaf = False
dfs(trie[u][c])
stateWin[u] |= (not(stateWin[trie[u][c]]))
stateLose[u] |= (not(stateLose[trie[u][c]]))
if leaf == True:
stateWin[u] = False
stateLose[u] = True
n,k = map(int,input().split())
for i in range(n):
insertNode()
dfs(0)
# print(stateWin[0])
# print(stateLose[0])
if (stateWin[0] and (stateLose[0] or (k % 2 == 1) )):
print("First")
else:
print("Second") | 1407511800 | [
"games",
"strings",
"trees"
] | [
1,
0,
0,
0,
0,
0,
1,
1
] |
|
3 seconds | ["3.4142135624", "37.7044021497"] | 51c355a5b56f9b1599e7d985f0b7c04e | null | In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.The resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur.The very same resolution says that the cat's fur is a white square with the length of 105. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes (0;0) and the upper right one — to the point with coordinates (105;105). The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point.We'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color. | Print a single number, the answer to the problem, perimeter of the union of triangles. Your answer should differ from the correct one in no more than 10 - 6. | The first input line contains a single integer n (0 ≤ n ≤ 100). It is the number of spots on the cat's fur. The i-th of the last n lines contains 6 integers: x1i, y1i, x2i, y2i, x3i, y3i. They are the coordinates of the i-th triangular spot (0 < xji, yji < 105). | standard output | standard input | Python 2 | Python | 2,300 | train_002.jsonl | 55208628c101d596b3c0e3b7a6bad399 | 256 megabytes | ["1\n1 1 2 1 1 2", "3\n3 3 10 3 3 10\n1 1 9 4 5 6\n2 2 11 7 6 11"] | PASSED | from math import *
eps=1e-14
n = input()
l = [map(int,raw_input().split()) for _ in xrange(n)]
res = 0
def isect(a1,b1,c1,x1,y1,x2,y2):
a2,b2,c2=y1-y2,x2-x1,x1*y2-y1*x2
d = a1*b2-a2*b1
if d==0: return None, None
x = -1.0*(c1*b2-c2*b1)/d
y = -1.0*(c2*a1-a2*c1)/d
#print x1,y1,x2,y2,x,y
if min(x1,x2)-eps<=x<=max(x1,x2)+eps and min(y1,y2)-eps<=y<=max(y1,y2)+eps: return x,y
return None, None
def cres(xmi,xma,rx):
#print rx
n = 0
sx = xma-xmi
for j,(x,i) in enumerate(rx):
if n>0:
sx-=max(0,min(x,xma)-max(xmi,rx[j-1][0]))
if i: n+=1
else: n-=1
return sx
def count(x,y,xx,yy,i):
a1,b1,c1=y-yy,xx-x,x*yy-y*xx
xmi=min(x,xx)
xma=max(x,xx)
ymi=min(y,yy)
yma=max(y,yy)
rx=[]
ry=[]
for j,(ax,ay,bx,by,cx,cy) in enumerate(l):
if i==j: continue
x1,y1=isect(a1,b1,c1,ax,ay,bx,by)
x2,y2=isect(a1,b1,c1,cx,cy,bx,by)
x3,y3=isect(a1,b1,c1,cx,cy,ax,ay)
x = filter(lambda x: x is not None, [x1,x2,x3])
if len(x)<2: continue
y = filter(lambda x: x is not None, [y1,y2,y3])
#print xmi,xma,ymi,yma,x,y
rx.append((min(x),True))
rx.append((max(x),False))
ry.append((min(y),True))
ry.append((max(y),False))
rx.sort()
ry.sort()
return hypot(cres(xmi,xma,rx),cres(ymi,yma,ry))
for i,(ax,ay,bx,by,cx,cy) in enumerate(l):
res+=count(ax,ay,bx,by,i)
res+=count(cx,cy,bx,by,i)
res+=count(ax,ay,cx,cy,i)
print "%.7f"%res
| 1298649600 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["unique\n5", "not unique"] | bfbd7a73e65d240ee7e8c83cc68ca0a1 | NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4. | Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be. | Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique". | The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds. | standard output | standard input | Python 2 | Python | 1,800 | train_006.jsonl | e6c9662e1079a38a6394080ee9d5b85e | 256 megabytes | ["3\n1 2 4", "2\n1 2"] | PASSED | I = lambda: map(int, raw_input().split())
n = input()
S = [None]*n
S = I()
#print S
counter = 1
decr = 0
alpha = 0.0
lower = 0.0
for i in xrange(n):
if(i == 0):
alpha = 10*S[0]+10
decr = 10*S[0]
counter += 1
else:
decr = 10*(S[i]-S[i-1]) + decr
alpha = min(alpha,(decr + 10 )/float (counter))
#print " alpha = " , alpha
if S[i]-1 != S[i-1]:
lower = max(lower, ( decr )/float (counter))
#print "lower = ", lower
counter += 1
alpha = alpha - 0.0000000001
if lower == 0.0 : lower = 10.0
#print " alpha = " , alpha
fuel = counter*alpha - decr
least = counter*lower - decr
#print fuel , least
if int(fuel)/10 == int(least)/10 :
print "unique"
print S[n-1]+ int(fuel)/10
else:
print "not unique"
| 1292140800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["abab\n-1\naaa\nab\nz"] | 8d4cdf75f726b59a8fcc374e1417374a | NoteThe first test case was explained in the statement.In the second test case, the answer does not exist. | You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first. | Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes). | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$) — the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters. | standard output | standard input | PyPy 3 | Python | 1,700 | train_007.jsonl | 8611089238d9864067855d6f2391005d | 256 megabytes | ["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"] | PASSED | import string
for _ in range(int(input())):
n,m=map(int,input().split())
s=[input() for _ in range(n)]
totry=string.ascii_lowercase
for i in range(m):
t1=0
for l in totry:
ans=s[0][:i]+l+s[0][i+1:]
t=0
for st in s:
r=0
for tr in range(m):
if st[tr]!=ans[tr]:
if r:
t=1
break
else:r+=1
if t:break
else:
print(ans)
t1=1
break
if t1:break
else:print(-1)
'''
2
3 3
bab
aba
abb
3 3
abc
acb
abc
''' | 1590327300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["2\n0\n13\n1\n4\n7\n0"] | a7ae834884ce801ffe111bd8161e89d2 | NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$. | This is the hard version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ is $$$$$$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$$$$$Here, $$$\lfloor \frac{x}{y} \rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \le p_i \le k$$$ for all $$$1 \le i \le n$$$. | For each test case, print a single integer — the minimum possible cost of an array $$$p$$$ satisfying the condition above. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \ldots \le a_n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 2,400 | train_093.jsonl | c3378cdf501f3cc31c0ea5e47090e67f | 64 megabytes | ["7\n\n5 2\n\n4 5 6 8 11\n\n5 12\n\n4 5 6 8 11\n\n3 1\n\n2 9 15\n\n7 3\n\n2 3 5 5 6 9 10\n\n6 56\n\n54 286 527 1436 2450 2681\n\n3 95\n\n16 340 2241\n\n2 2\n\n1 3"] | PASSED | #!/usr/bin/env python3
import sys
import heapq
input = sys.stdin.readline # to read input quickly
def ceiling_division(numer, denom):
return -((-numer)//denom)
mask = 2**18 - 1
m0 = mask
m1 = mask << 18
m2 = mask << 36
def ungroup(x):
return (x&m2) >> 36, (x&m1) >> 18, (x&m0)
def group(a,b,c):
val = (a << 36) ^ (b << 18) ^ c
return val
for case_num in range(int(input())):
n,k = list(map(int,input().split()))
n_cooldown = 18*n
cnt = n_cooldown
arr = [group((x//k),k,x) for x in map(int,input().split())]
minn = ungroup(arr[0])[0]
maxx = ungroup(arr[-1])[0]
minres = maxx - minn
if minres == 0:
print(0)
continue
maxx = max(1, maxx)
while ungroup(arr[0])[1] > 1 and cnt > 0:
nx,i,x = ungroup(heapq.heappop(arr))
i = max(1, min(ceiling_division(x, maxx), x // (nx+1)))
nx = (x//i)
heapq.heappush(arr, group(nx,i,x))
maxx = max(maxx, nx)
minn = ungroup(arr[0])[0]
cnt -= 1
if maxx - minn < minres:
minres = maxx - minn
cnt = n_cooldown
if minres == 0:
break
print(minres) | 1658154900 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["110110", "01100011", "01"] | 6ac00fcd4a483f9f446e692d05fd31a4 | NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence. | The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way? | In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them. | The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only. | standard output | standard input | Python 3 | Python | 1,600 | train_054.jsonl | 0b72121ba7e0922a43d287ce4565e9c3 | 512 megabytes | ["101101\n110", "10010110\n100011", "10\n11100"] | PASSED | import sys
def count_bits(s):
return [s.count("0"), s.count("1")]
# 1 - in case where a >= b
# 0 - otherwise
def compare_bits_count(a, b):
if a[0] >= b[0] and a[1] >= b[1]:
return 1
else:
return 0
def subtract_bits_count(a, b):
return [a[0] - b[0], a[1] - b[1]]
def z_function(s):
n = len(s)
l = 0
r = 0
z = [0 for x in range(n)]
for i in range(1, n):
z[i] = max(0, min(r - i, z[i - l]))
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l = i
r = i + z[i]
return z
s = input()
t = input()
s_bits_count = count_bits(s)
t_bits_count = count_bits(t)
if compare_bits_count(s_bits_count, t_bits_count) == 0:
print(s)
sys.exit()
result = t
s_bits_count = subtract_bits_count(s_bits_count, t_bits_count)
r = ""
z = z_function(t)
for i in range(len(t) // 2, len(t)):
if z[i] == len(t) - i:
r = t[len(t) - i:]
r_bits_count = count_bits(r)
break
if len(r) == 0:
r = t
r_bits_count = t_bits_count
while s_bits_count[0] > 0 or s_bits_count[1] > 0:
if compare_bits_count(s_bits_count, r_bits_count) == 1:
result += r
s_bits_count = subtract_bits_count(s_bits_count, r_bits_count)
else:
result += '0' * s_bits_count[0]
result += '1' * s_bits_count[1]
break
print(result)
| 1552035900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["Yes\nNo\nYes"] | 34aa41871ee50f06e8acbd5eee94b493 | NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example. | Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them. | Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively. | standard output | standard input | Python 3 | Python | 900 | train_000.jsonl | d53ffbdbe544d9997b359900cde00fa8 | 256 megabytes | ["3\n3 3 3\n1 10 2\n2 1 1"] | PASSED | t=int(input())
for _ in range(t):
l=list(map(int,input().split()))
if 2*max(l)<=sum(l)+1:
print('Yes')
else:
print('No') | 1577457600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3", "0 2 4", "-1", "13 15 17 19 21"] | e5ac0312381701a25970dd9a98cda3d4 | NoteIn the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have $$$3$$$ friends.In the second test case, there are three possible solutions (apart from symmetries): $$$a$$$ is friend of $$$b$$$, $$$c$$$ is friend of $$$d$$$, and Bob has no friends, or $$$a$$$ is a friend of $$$b$$$ and both $$$c$$$ and $$$d$$$ are friends with Bob, or Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. | Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if $$$a$$$ is a friend of $$$b$$$, then $$$b$$$ is also a friend of $$$a$$$. Each user thus has a non-negative amount of friends.This morning, somebody anonymously sent Bob the following link: graph realization problem and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. | Print all possible values of $$$a_{n+1}$$$ — the amount of people that Bob can be friend of, in increasing order. If no solution exists, output $$$-1$$$. | The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$), the number of people on the network excluding Bob. The second line contains $$$n$$$ numbers $$$a_1,a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq n$$$), with $$$a_i$$$ being the number of people that person $$$i$$$ is a friend of. | standard output | standard input | Python 3 | Python | 2,400 | train_033.jsonl | d179a722084be6092d643ecc0adb97fb | 256 megabytes | ["3\n3 3 3", "4\n1 1 1 1", "2\n0 2", "35\n21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22"] | PASSED | def main():
n=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
mod=sum(a)%2
counts=[0]*(n+1)
for guy in a:
counts[guy]+=1
cumcounts=[counts[0]]
for i in range(n):
cumcounts.append(cumcounts[-1]+counts[i+1])
partialsums=[0]
curr=0
for i in range(n):
curr+=(i+1)*counts[i+1]
partialsums.append(curr)
partialsums.append(0)
cumcounts.append(0)
sumi=0
diffs=[]
altdiffs=[]
for i in range(n):
sumi+=a[i]
rhs=i*(i+1)
if a[i]>i:
rhs+=partialsums[i]+(i+1)*(n-i-1-cumcounts[i])
else:
rhs+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1])
diffs.append(sumi-rhs)
rhs2=(i+1)*(i+2)
if a[i]>i+1:
rhs2+=partialsums[i+1]+(i+2)*(n-i-1-cumcounts[i+1])
else:
rhs2+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1])
altdiffs.append(sumi-rhs2)
mini=max(diffs)
maxi=-max(altdiffs)
mini=max(mini,0)
maxi=min(maxi,n)
out=""
if mini%2!=mod:
mini+=1
if maxi%2==mod:
maxi+=1
for guy in range(mini,maxi,2):
out+=str(guy)+" "
if mini>maxi:
print(-1)
else:
print(out)
main() | 1546180500 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second | ["NO", "YES"] | 9cf8b711a3fcf5dd5059f323f107a0bd | null | You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: for any numbers i, j (1 ≤ i, j ≤ n) the following inequality holds: aij ≥ 0; . Matrix b is strictly positive, if for any numbers i, j (1 ≤ i, j ≤ n) the inequality bij > 0 holds. You task is to determine if there is such integer k ≥ 1, that matrix ak is strictly positive. | If there is a positive integer k ≥ 1, such that matrix ak is strictly positive, print "YES" (without the quotes). Otherwise, print "NO" (without the quotes). | The first line contains integer n (2 ≤ n ≤ 2000) — the number of rows and columns in matrix a. The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1, ai2, ..., ain (0 ≤ aij ≤ 50). It is guaranteed that . | standard output | standard input | PyPy 2 | Python | 2,200 | train_077.jsonl | 7c3a71881ab6ade147d41ec0b2f50cc6 | 256 megabytes | ["2\n1 0\n0 1", "5\n4 5 6 1 2\n1 2 3 4 5\n6 4 1 2 4\n1 1 1 1 1\n4 4 4 4 4"] | PASSED | #!py2
def solve(N, A):
graph = [set() for _ in xrange(N)]
rgraph = [set() for _ in xrange(N)]
for u, row in enumerate(A):
for v, val in enumerate(row):
if val:
graph[u].add(v)
rgraph[v].add(u)
# Try to write row 0 in terms of row i
stack, seen = [0], {0}
while stack:
node = stack.pop()
for nei in graph[node]:
if nei not in seen:
seen.add(nei)
stack.append(nei)
if len(seen) != N:
return False
# Try to write row i in terms of row 0
stack, seen = [0], {0}
while stack:
node = stack.pop()
for nei in rgraph[node]:
if nei not in seen:
seen.add(nei)
stack.append(nei)
return len(seen) == N
N = int(raw_input())
A = [[+(x != '0') for x in raw_input().split()]
for _ in xrange(N)]
print "YES" if solve(N, A) else "NO"
| 1394983800 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
15 seconds | ["RL", "DLDDLLLRRRUURU", "IMPOSSIBLE"] | 61689578b2623e750eced6f770fda2cc | NoteIn the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less. In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up. In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above. | Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes). | The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle. Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once. | standard output | standard input | Python 3 | Python | 1,700 | train_077.jsonl | e6341ca044cd6a9a4d20792b5bfdde8a | 256 megabytes | ["2 3 2\n.**\nX..", "5 6 14\n..***.\n*...X.\n..*...\n..*.**\n....*.", "3 3 4\n***\n*X*\n***"] | PASSED | from queue import Queue
import sys
#sys.stdin = open('input.txt')
n, m, k = map(lambda x: int(x), input().split(' '))
if k&1:
print('IMPOSSIBLE')
sys.exit()
s = [None]*n
for i in range(n):
s[i] = [None]*m
t = input()
for j in range(m):
s[i][j] = t[j]
if t[j] == 'X': x, y = j, i
def bfs(x, y):
res = [[10000000]*m for i in range(n)]
if s[y][x] == '*': return res
q = Queue()
q.put((x, y))
step = 0
def add(x, y):
if res[y][x] != 10000000 or s[y][x] == '*' or step >= res[y][x]: return
q.put((x, y))
res[y][x] = step+1
res[y][x] = step
while not q.empty():
x, y = q.get()
step = res[y][x]
#print('-')
if y < n-1: add(x, y+1) #D
if x > 0: add(x-1, y) #L
if x < m-1: add(x+1, y) #R
if y > 0: add(x, y-1) #U
return res
res = bfs(x, y)
path = []
add = lambda s: path.append(s)
for i in range(k):
step = k-i
#print(step, (y, x), k-i)
if y < n-1 and res[y+1][x] <= step: #D
add('D')
y = y+1
elif x > 0 and res[y][x-1] <= step: #L
add('L')
x = x-1
elif x < m-1 and res[y][x+1] <= step: #R
add('R')
x = x+1
elif y > 0 and res[y-1][x] <= step: #U
add('U')
y = y-1
else:
print('IMPOSSIBLE')
sys.exit()
print(str.join('', path))
| 1488628800 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["YES", "NO"] | c659bdeda1c1da08cfc7f71367222332 | Note First example: you can simply swap two letters in string "ab". So we get "ba". Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b". | Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not. | Print "YES", if the dwarves belong to the same race. Otherwise, print "NO". | The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length. | standard output | standard input | Python 3 | Python | 1,100 | train_005.jsonl | 74f9f2db9474289817555c34f9037caf | 256 megabytes | ["ab\nba", "aa\nab"] | PASSED | p=input()
p=p.replace('',' ')
p=p.split()
q=input()
q=q.replace('',' ')
q=q.split()
if len(p)==len(q):
c=0
l=[]
for i in range(len(p)):
if p[i]!=q[i]:
c+=1
l.append(p[i])
l.append(q[i])
if c==2:
d=0
for i in range(4):
if l.count(l[i])!=2:
d=1
break
if d==0:
print('YES')
else:
print('NO')
else:
print('NO')
else:
print('NO') | 1336145400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["()", "(()(()))", "()()"] | cf1c39e85eded68515aae9eceac73313 | NoteIn the first sample the cursor is initially at position 5. Consider actions of the editor: command "R" — the cursor moves to the position 6 on the right; command "D" — the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5; command "L" — the cursor moves to the position 4 on the left; command "D" — the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to (). | Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))": 1st bracket is paired with 8th, 2d bracket is paired with 3d, 3d bracket is paired with 2d, 4th bracket is paired with 7th, 5th bracket is paired with 6th, 6th bracket is paired with 5th, 7th bracket is paired with 4th, 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: «L» — move the cursor one position to the left, «R» — move the cursor one position to the right, «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below. All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor? | Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence. | The first line contains three positive integers n, m and p (2 ≤ n ≤ 500 000, 1 ≤ m ≤ 500 000, 1 ≤ p ≤ n) — the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even. It is followed by the string of n characters "(" and ")" forming the correct bracket sequence. Then follow a string of m characters "L", "R" and "D" — a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty. | standard output | standard input | Python 3 | Python | 1,700 | train_059.jsonl | 370a247f79c018a6b474d2a1688db039 | 256 megabytes | ["8 4 5\n(())()()\nRDLD", "12 5 3\n((()())(()))\nRRDLD", "8 8 8\n(())()()\nLLLLLLDD"] | PASSED | class Node:
def __init__(self, index):
self.left = index - 1
self.right = index + 1
self.pair = -1
if __name__ == "__main__":
n, m, p = map(int, input().split())
brackets = input()
operations = input()
nodes = [Node(i) for i in range(n + 1)]
stack = []
for i in range(n):
if brackets[i] == "(":
stack.append(i + 1)
else:
pair_id = stack.pop()
nodes[pair_id].pair = i + 1
nodes[i + 1].pair = pair_id
for i in range(m):
if operations[i] == "L":
p = nodes[p].left
elif operations[i] == "R":
p = nodes[p].right
else:
pair_id = nodes[p].pair
left = min(p, pair_id)
right = max(p, pair_id)
left_node = nodes[left].left
right_node = nodes[right].right
nodes[left_node].right = right_node
if right_node != n + 1:
nodes[right_node].left = left_node
p = right_node
else:
p = left_node
p = nodes[0].right
result = []
while p != n + 1:
result.append(brackets[p - 1])
p = nodes[p].right
print("".join(result)) | 1462464300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1", "1999982505"] | 54e9c6f24c430c5124d840b5a65a1bc4 | NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$. | Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to: Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$). | standard output | standard input | PyPy 3 | Python | 1,500 | train_001.jsonl | 3b75768ab9d2fa9782acad40a87ed191 | 256 megabytes | ["3\n1 3 2", "3\n1000000000 1000000000 1000000000"] | PASSED | import copy
import math
n = int(input())
nums = list(map(int,input().split()))
nums.sort()
f_1 = 0
for i in range(n):
f_1 += math.fabs(1 - nums[i])
term = f_1 + nums[-1]
max_c = math.floor(math.pow(term,1/(n-1)))
cost2 = float('inf')
prev_cost = 0
for c in range(1,max_c+1):
cost = 0
for i in range(n):
cost += math.fabs((c**i - nums[i]))
cost2 = min(cost,cost2)
print(int(cost2)) | 1598798100 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["YES\nYES\nNO\nNO"] | c0ad2a6d14b0c9e09af2221d88a34d52 | NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \neq b$$$. | You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: has at least one red bean (or the number of red beans $$$r_i \ge 1$$$); has at least one blue bean (or the number of blue beans $$$b_i \ge 1$$$); the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \le d$$$) Can you distribute all beans? | For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). | The first line contains the 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 $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \le r, b \le 10^9$$$; $$$0 \le d \le 10^9$$$) — the number of red and blue beans and the maximum absolute difference in each packet. | standard output | standard input | Python 3 | Python | 800 | train_101.jsonl | a149ae3b91445d8dcb18e6884f39240a | 256 megabytes | ["4\n1 1 0\n2 7 3\n6 1 4\n5 4 0"] | PASSED | for i in range(int(input())):
arr = [int(_) for _ in input().split()]
if abs(arr[0] / min(arr[:2]) - arr[1] / min(arr[:2])) <= arr[2]:
print('YES')
else:
print('NO')
# val = abs(arr[0] / 2 - arr[1] / 2) <= arr[2]
| 1619706900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1.931851653\n3.196226611\n126.687663595"] | c466c909fff92353ea676b643ca76908 | null | The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single odd integer $$$n$$$ ($$$3 \le n \le 199$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | standard output | standard input | PyPy 3 | Python | 2,000 | train_004.jsonl | acd939ebac1b4aafb82d9aa8b69f4f7c | 256 megabytes | ["3\n3\n5\n199"] | PASSED | from math import sin,radians
def C2(n):
interiorangle = 360/(2*n)
side = sin(radians(45))
angle = 45
number = (n-1)/2
for i in range(int(number)):
angle += interiorangle
if angle > 90:
angle = 180 - angle
side += sin(radians(angle))
angle = 180 - angle
else:
side += sin(radians(angle))
angle = 45
for i in range(int(number)):
angle -= interiorangle
if angle < 0:
angle = -1 * angle
side += sin(radians(angle))
angle = -1 * angle
else:
side += sin(radians(angle))
print(float(side))
a = int(input())
for _ in range(a):
x = int(input())
C2(x) | 1589707200 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["a", "bc", "b"] | 161f3f76bfe141899ad0773545b38c03 | NoteIn the second sample before string "bc" follow strings "a", "ab", "abc", "b". | One day in the IT lesson Anna and Maria learned about the lexicographic order.String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages.The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework. | Print the string Anna and Maria need — the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes). | The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≤ k ≤ 105). | standard output | standard input | Python 3 | Python | 2,100 | train_018.jsonl | f2c521438dade5afc86d45edc3340ba6 | 256 megabytes | ["aa\n2", "abc\n5", "abab\n7"] | PASSED | # -*- coding: utf-8 -*-
"""
Created on Sat May 7 16:53:11 2016
@author: Alex
"""
from heapq import heappush,heappop,heapify
string = input()
l = len(string)
k = int(input())
A = l*(l+1)/2
if A<k:
print("No such line.")
else:
heap = [(string[i],i+1) for i in range(l)]
heapify(heap)
cnt = 0
while cnt<k:
now,nextp = heappop(heap)
cnt+=1
if nextp<l:
heappush(heap,(now+string[nextp],nextp+1))
print(now) | 1321337400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | null | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | standard output | standard input | Python 2 | Python | 2,100 | train_060.jsonl | 87d9b7abd9713d16eff012c23009e499 | 256 megabytes | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | PASSED | import math,sys
eps = 1e-8
n = input()
al = [map(int,raw_input().split()) for i in xrange(n+1)]
vp,vs = map(int,raw_input().split())
px,py,pz = p0 = map(int,raw_input().split())
al = [(x-px,y-py,z-pz) for x,y,z in al]
d3=lambda x,y,z:x*x+y*y+z*z
t0,ts = 0,0
rt = None
for i in range(n):
c = [y-x for x,y in zip(al[i],al[i+1])]
ll = d3(*c)
l = ll**0.5
ts+=l
te = ts/vs
v = [vs*x for x in c]
s = [l*x-a*t0 for x,a in zip(al[i],v)]
a = d3(*v)-vp*vp*ll
b = 2*sum(x*i for x,i in zip(s,v))
c = d3(*s)
d = b*b-4*a*c
fa = abs(a)<eps
f = lambda t: (t0-eps<t<te+eps)
if fa:
if abs(b)>eps and f(-c/b):
rt = -c/b
break
elif d>-eps:
if d<eps: d=0
a*=2.0
d**=0.5
tl = [t for t in ((-b+d)/a,(-b-d)/a) if f(t)]
if tl:
rt = min(tl)
break
t0 = te
if rt is None: print "NO"
else:
print "YES"
print "%.9f"%rt
print " ".join(["%.9f"%((x+a*rt)/l+p) for x,a,p in zip(s,v,p0)])
| 1299340800 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["164", "27"] | 28c555fefd5c36697a5082c61d8a82b3 | NoteIn the first sample, one of the optimal solutions is to divide those $$$4$$$ numbers into $$$2$$$ groups $$$\{2, 8\}, \{5, 3\}$$$. Thus the answer is $$$(2 + 8)^2 + (5 + 3)^2 = 164$$$.In the second sample, one of the optimal solutions is to divide those $$$6$$$ numbers into $$$3$$$ groups $$$\{1, 2\}, \{1, 2\}, \{1, 2\}$$$. Thus the answer is $$$(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$$$. | Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ on Bob's homework paper, where $$$n$$$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $$$2$$$ numbers. Suppose the numbers are divided into $$$m$$$ groups, and the sum of the numbers in the $$$j$$$-th group is $$$s_j$$$. Bob's aim is to minimize the sum of the square of $$$s_j$$$, that is $$$$$$\sum_{j = 1}^{m} s_j^2.$$$$$$Bob is puzzled by this hard problem. Could you please help him solve it? | A single line containing one integer, denoting the minimum of the sum of the square of $$$s_j$$$, which is $$$$$$\sum_{i = j}^{m} s_j^2,$$$$$$ where $$$m$$$ is the number of groups. | The first line contains an even integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$), denoting that there are $$$n$$$ integers on Bob's homework paper. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^4$$$), describing the numbers you need to deal with. | standard output | standard input | PyPy 3 | Python | 900 | train_004.jsonl | 1d7642edf48293b29f51ec811b2d01c3 | 256 megabytes | ["4\n8 5 2 3", "6\n1 1 1 2 2 2"] | PASSED |
n = int(input())
a = list(map(int, input().split(" ")))
a.sort()
min_sum = 0
i = 0
j = n - 1
while i <= j:
if i == j:
min_sum += a[j]
else:
min_sum += (a[i] + a[j]) ** 2
i += 1
j -= 1
print(min_sum) | 1548938100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4", "9"] | dceeb739a56bb799550138aa8c127996 | NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth). | Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally? | Print exactly one integer — the maximum number of students that can get a favorite drink. | The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student. | standard output | standard input | Python 3 | Python | 1,000 | train_021.jsonl | 31aeedb9329d4f4d7680c66eb3cba918 | 256 megabytes | ["5 3\n1\n3\n1\n1\n2", "10 3\n2\n1\n3\n2\n3\n3\n1\n3\n1\n2"] | PASSED | import math
n, k = map(int, input().split())
a = [0] * k
for i in range(n):
temp = int(input())
a[temp-1] += 1
nSet = math.ceil(n/2)
ans = 0
# First deal with situation where a[i] > 1
for i in range(k):
while a[i] > 1 and nSet > 0:
ans += 2
nSet -= 1
a[i] -= 2
# Then deal with only one left situation for each drink
for i in range(k):
while a[i] > 0 and nSet > 0:
ans += 1
nSet -= 1
a[i] -= 1
print(ans) | 1563374100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1 2\n1 2\n1 3\n2 3"] | b01fb9d4d78a02e3c634800b4b177d75 | NoteNote that you can add the same edge that you cut.In the first test case, after cutting and adding the same edge, the vertex $$$2$$$ is still the only centroid.In the second test case, the vertex $$$2$$$ becomes the only centroid after cutting the edge between vertices $$$1$$$ and $$$3$$$ and adding the edge between vertices $$$2$$$ and $$$3$$$. | Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.For example, the centroid of the following tree is $$$2$$$, because when you cut it, the size of the largest connected component of the remaining graph is $$$2$$$ and it can't be smaller. However, in some trees, there might be more than one centroid, for example: Both vertex $$$1$$$ and vertex $$$2$$$ are centroids because the size of the largest connected component is $$$3$$$ after cutting each of them.Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. | For each test case, print two lines. In the first line print two integers $$$x_1, y_1$$$ ($$$1 \leq x_1, y_1 \leq n$$$), which means you cut the edge between vertices $$$x_1$$$ and $$$y_1$$$. There should exist edge connecting vertices $$$x_1$$$ and $$$y_1$$$. In the second line print two integers $$$x_2, y_2$$$ ($$$1 \leq x_2, y_2 \leq n$$$), which means you add the edge between vertices $$$x_2$$$ and $$$y_2$$$. The graph after these two operations should be a tree. If there are multiple solutions you can print any. | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\leq n\leq 10^5$$$) — the number of vertices. Each of the next $$$n-1$$$ lines contains two integers $$$x, y$$$ ($$$1\leq x,y\leq n$$$). It means, that there exists an edge connecting vertices $$$x$$$ and $$$y$$$. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3 | Python | 1,700 | train_029.jsonl | 51565fc3d42f0f25dcc38f6c43bb0be3 | 512 megabytes | ["2\n5\n1 2\n1 3\n2 4\n2 5\n6\n1 2\n1 3\n1 4\n2 5\n2 6"] | PASSED | ######################################################
############Created by Devesh Kumar###################
#############[email protected]####################
##########For CodeForces(Devesh1102)#################
#####################2020#############################
######################################################
import sys
input = sys.stdin.readline
import sys
import heapq
import copy
import math
import decimal
# import sys.stdout.flush as flush
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
# n = 100
# parent = [-1 for i in range(n)]
# def find(a):
# if parent[a] == a:
# return a
# else:
# parent[a] = find(parent[a])
# def union(a,b):
# print(lsp )
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def insr2():
s = input()
s = list(s[:len(s) - 1])
s = [ord(s[i]) - ord("a") for i in range(len(s))]
return s
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
ans = 0
def pr_list(a):
print( *a , sep=" ")
def swap(a,b):
temp = a
a = b
b = temp
return [ a,b]
# return [b,a]
def pri(a,b):
s = "? " + str(a) + " " + str(b)
print(s)
sys.stdout.flush()
def main():
tests = inp()
# tests = 1
mod = 1000000007
limit = 10**18
ans = 0
stack = []
hashm = {}
arr = []
heapq.heapify(arr)
def find_next(hashm,itr):
for i in range(itr,len(hashm)):
if hashm[i] == 0:
return i
for test in range(tests):
n= inp()
edges = [{} for i in range(n+1)]
dum = []
for j in range(n-1):
[a,b] = inlt()
edges[a][b] = 1
edges[b][a] = 1
dum = [a,b]
# e = copy.deepcopy(edges)
children = [0 for i in range (n+1)]
done = [-1 for i in range(n+1)]
stack = [1]
done [1] = 1
while(stack!= []):
# print(stack)
curr= stack[-1]
flag = 0
for child in edges[curr]:
if done[child] == -1:
done[child] = 1
flag = 1
stack.append(child)
if curr in edges[child]:
del edges[child][curr]
if flag == 1:
continue
curr= stack.pop()
c = 0
for i in edges[curr]:
c = c + children[i] + 1
children[curr] = c
# print(children)
# print(edges)
centroid = [[sys.maxsize,i] for i in range(n+1)]
for i in range(1,n+1):
sums = 0
maxi = -1*sys.maxsize
for j in edges[i]:
sums= sums+ children[j] + 1
maxi = max(maxi,children[j] + 1)
maxi = max(maxi, n-1 - sums)
centroid[i][0] = maxi
centroid.sort()
# print(centroid)
if centroid[0][0] != centroid[1][0]:
pr_list(dum)
pr_list(dum)
continue
a = centroid[0][1]
b = centroid[1][1]
def find_leaf(a,b):
done = [0 for i in range(n+1)]
done[a] = 1
# print(e)
stack = [a]
leaf = []
while(stack!=[] and leaf == []):
curr= stack.pop()
for i in edges[curr]:
if len(edges[i])== 0 :
leaf = [curr,i]
return leaf
elif i!= b and done[i] != 1:
done[i] = 1
stack.append(i)
return leaf
leaf = find_leaf(a,b)
if leaf == []:
leaf = find_leaf(b,a)
pr_list(leaf)
n_edge = [leaf[1], a]
pr_list(n_edge)
else:
pr_list(leaf)
n_edge = [leaf[1], b]
pr_list(n_edge)
if __name__== "__main__":
main()
| 1599918300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["YES\nNO\nYES"] | eba7fc8d103ba3d643c1424cbbebf571 | null | There are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place: either employee y became the boss of employee x (at that, employee x didn't have a boss before); or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); or comes a request of type "determine whether employee x signs certain documents". Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies. | For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes. | The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of employees and the number of events. Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 ≤ t ≤ 3). If t = 1, then next follow two integers x and y (1 ≤ x, y ≤ n) — numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently. If t = 2, then next follow integer x (1 ≤ x ≤ n) — the number of the employee who got a document packet. If t = 3, then next follow two integers x and i (1 ≤ x ≤ n; 1 ≤ i ≤ [number of packets that have already been given]) — the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order. It is guaranteed that the input has at least one query of the third type. | standard output | standard input | Python 3 | Python | 2,100 | train_051.jsonl | eacbdc33f4e998b7bd6f37c7a294131b | 512 megabytes | ["4 9\n1 4 3\n2 4\n3 3 1\n1 2 3\n2 2\n3 1 2\n1 3 1\n2 2\n3 1 3"] | PASSED | n, m = map(int, input().split())
ev = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
qry = [[] for _ in range(m + 1)]
roots = set(range(1, n + 1))
qcnt = 0
for e in ev:
if e[0] == 1:
g[e[2]].append(e[1])
roots.remove(e[1])
elif e[0] == 3:
qry[e[2]].append((qcnt, e[1]))
qcnt += 1
tin, tout = [0] * (n + 1), [0] * (n + 1)
st = [(u, 0) for u in roots]
time = 0
while st:
u, w = st.pop()
if w:
tout[u] = time
continue
time += 1
tin[u] = time
st.append((u, 1))
for v in g[u]:
st.append((v, 0))
p = list(range(n + 1))
def find(x):
if x != p[x]:
p[x] = find(p[x])
return p[x]
pcnt = 0
ans = [None] * qcnt
for e in ev:
if e[0] == 1:
p[find(e[1])] = find(e[2])
elif e[0] == 2:
pcnt += 1
for qid, x in qry[pcnt]:
ans[qid] = 'YES' if find(e[1]) == find(x) and tin[x] <= tin[e[1]] <= tout[x] else 'NO'
print(*ans, sep='\n') | 1410535800 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["12 14", "8"] | 9eccd64bb49b74ed0eed3dbf6636f07d | NoteIn the first example, for $$$f(3)$$$, we consider four possible polygons: ($$$p_1, p_2, p_3$$$), with perimeter $$$12$$$. ($$$p_1, p_2, p_4$$$), with perimeter $$$8$$$. ($$$p_1, p_3, p_4$$$), with perimeter $$$12$$$. ($$$p_2, p_3, p_4$$$), with perimeter $$$12$$$. For $$$f(4)$$$, there is only one option, taking all the given points. Its perimeter $$$14$$$.In the second example, there is only one possible polygon. Its perimeter is $$$8$$$. | You are given $$$n$$$ points on the plane. The polygon formed from all the $$$n$$$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $$$1$$$ to $$$n$$$, in clockwise order.We define the distance between two points $$$p_1 = (x_1, y_1)$$$ and $$$p_2 = (x_2, y_2)$$$ as their Manhattan distance: $$$$$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$$$$Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $$$p_1, p_2, \ldots, p_k$$$ $$$(k \geq 3)$$$, then the perimeter of the polygon is $$$d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1)$$$.For some parameter $$$k$$$, let's consider all the polygons that can be formed from the given set of points, having any $$$k$$$ vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $$$f(k)$$$ to be the maximal perimeter.Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: In the middle polygon, the order of points ($$$p_1, p_3, p_2, p_4$$$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($$$p_1, p_2, p_3, p_4$$$), which is the left polygon.Your task is to compute $$$f(3), f(4), \ldots, f(n)$$$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $$$3$$$ to $$$n$$$). | For each $$$i$$$ ($$$3\leq i\leq n$$$), output $$$f(i)$$$. | The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 3\cdot 10^5$$$) — the number of points. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^8 \leq x_i, y_i \leq 10^8$$$) — the coordinates of point $$$p_i$$$. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. | standard output | standard input | Python 2 | Python | 2,100 | train_026.jsonl | bd41715d0639fbd0991e1924adcb4216 | 256 megabytes | ["4\n2 4\n4 3\n3 0\n1 3", "3\n0 0\n0 2\n2 0"] | PASSED | n = int(raw_input())
X = []
Y = []
for _ in range(n):
x,y = map(int,raw_input().strip(' ').strip('\n').split(' '))
X.append(x)
Y.append(y)
maxx,minx = max(X),min(X)
maxy,miny = max(Y),min(Y)
ans = -10e18
for i in range(n):
dx = max(maxx-X[i],X[i]-minx)
dy = max(maxy-Y[i],Y[i]-miny)
ans = max(ans,dx+dy)
ans = str(2*ans)+' '
rec = 2*(maxx+maxy-minx-miny)
for i in range(3,n):
ans += str(rec)+' '
ans = ans.strip('')
print ans | 1541355000 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["1", "24"] | f5cb28bf83f3b1b7c7df4037e65bddf2 | NoteIn the first example, there is only one non-empty subset {1} with cost 11 = 1.In the second example, there are seven non-empty subsets.- {1} with cost 12 = 1- {2} with cost 12 = 1- {1, 2} with cost 22 = 4- {3} with cost 12 = 1- {1, 3} with cost 22 = 4- {2, 3} with cost 22 = 4- {1, 2, 3} with cost 32 = 9The total cost is 1 + 1 + 4 + 1 + 4 + 4 + 9 = 24. | You have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is xk. Output the sum of costs over all non-empty subsets of people. | Output the sum of costs for all non empty subsets modulo 109 + 7. | Only line of input contains two integers N (1 ≤ N ≤ 109) representing total number of people and k (1 ≤ k ≤ 5000). | standard output | standard input | PyPy 2 | Python | 2,400 | train_036.jsonl | 88fc6f288789e850ed1f3dbb9b506b14 | 256 megabytes | ["1 1", "3 2"] | PASSED | import sys
range = xrange
input = raw_input
N,K = [int(x) for x in input().split()]
MOD = 10**9+7
coeff = [0]*(K+1)
coeff[0] = 1
for iters in range(K):
#print coeff
for i in reversed(range(iters+1)):
coeff[i+1] += coeff[i]
coeff[i]= coeff[i]*i%MOD
#print coeff
mod2inv = 500000004
pow2 = pow(2,N,MOD)
summa = 0
for i in range(len(coeff)):
summa = (summa + coeff[i]*pow2)%MOD
pow2 = (pow2*mod2inv*(N-i))%MOD
print summa
| 1518705300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3", "1680"] | faf2c92c3a61ba5e33160bc7a18ad928 | NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3 | Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen. | A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007. | The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000. | standard output | standard input | Python 2 | Python | 1,500 | train_029.jsonl | 6ff623793a4889c1c5c6550fa317c279 | 256 megabytes | ["3\n2\n2\n1", "4\n1\n2\n3\n4"] | PASSED | import math
ncol = int(raw_input())
#print ncol
col = []
n = 0
for i in range(0,ncol):
col.append(int(raw_input()))
n += col[i]
#print n
m = 1
length = col[0]
for i in range(1,ncol):
k2 = col[i]
m *= math.factorial(length+k2-1)/(math.factorial(k2-1)*math.factorial(length))
length += k2
m = m%1000000007
print m
| 1435163400 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["7 7\n1 2 3\n2 3 2\n3 4 2\n2 4 4", "7 13\n1 2 2\n1 3 4\n1 4 3\n4 5 4"] | c0eec5938787a63fce3052b7e209eda3 | NoteThe graph of sample 1: Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).Definition of terms used in the problem statement:A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 ≤ i < k and the sum of weight is minimized where w(i, j) is the edge weight between i and j. (https://en.wikipedia.org/wiki/Shortest_path_problem)A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (https://en.wikipedia.org/wiki/Prime_number)A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (https://en.wikipedia.org/wiki/Minimum_spanning_tree)https://en.wikipedia.org/wiki/Multiple_edges | Jamie has recently found undirected weighted graphs with the following properties very interesting: The graph is connected and contains exactly n vertices and m edges. All edge weights are integers and are in range [1, 109] inclusive. The length of shortest path from 1 to n is a prime number. The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. The graph contains no loops or multi-edges. If you are not familiar with some terms from the statement you can find definitions of them in notes section. Help Jamie construct any graph with given number of vertices and edges that is interesting! | In the first line output 2 integers sp, mstw (1 ≤ sp, mstw ≤ 1014) — the length of the shortest path and the sum of edges' weights in the minimum spanning tree. In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 ≤ u, v ≤ n, 1 ≤ w ≤ 109) describing the edge connecting u and v and having weight w. | First line of input contains 2 integers n, m — the required number of vertices and edges. | standard output | standard input | Python 2 | Python | 1,600 | train_002.jsonl | 5b26c2c16cca9df949466059016f9c87 | 256 megabytes | ["4 4", "5 4"] | PASSED | def main():
n, m = map(int, raw_input().split())
if n == 2:
print 2, 2
print 1, 2, 2
quit()
else:
print 2, 100003
for i in xrange(2, n - 1):
print 1, i, 1
print 1, n - 1, 100003 - n + 1
print 1, n, 2
c, d = 2, 3
for _ in xrange(m - n + 1):
print c, d, 1000000000
if d == n:
c += 1
d = c + 1
else:
d += 1
main()
| 1516372500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
5 seconds | ["7 8 9 4 5 6 1 2 3"] | 32077a3111c3f28ad56eab0c085a882d | null | You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, so pk = qk for 1 ≤ k < i and pi < qi. | Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get. | The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the length of the permutation p and the number of pairs of positions. The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p. Each of the last m lines contains two integers (aj, bj) (1 ≤ aj, bj ≤ n) — the pairs of positions to swap. Note that you are given a positions, not the values to swap. | standard output | standard input | PyPy 2 | Python | 1,700 | train_036.jsonl | 5f3adb1f8b18c3213117f90794273be5 | 256 megabytes | ["9 6\n1 2 3 4 5 6 7 8 9\n1 4\n4 7\n2 5\n5 8\n3 6\n6 9"] | PASSED | n, m = map(int, raw_input().split())
val = [_ for _ in map(int, raw_input().split())]
adj = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, raw_input().split())
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
vis = [False for _ in range(n)]
for v in range(n):
if vis[v] or len(adj[v]) == 0:
continue
seen, cur = [v], 0
vis[v] = True
while cur < len(seen):
v = seen[cur]
cur += 1
for nv in adj[v]:
if not vis[nv]:
seen.append(nv)
vis[nv] = True
seen.sort()
num = [val[i] for i in seen]
num.sort()
for i in range(len(seen)):
val[seen[i]] = num[-i-1]
print(' '.join(map(str, val))) | 1468425600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["? 1 2 1 1 1 3\n? 1 2 2 1 2 3\n? 1 2 3 1 3 3\n? 1 1 1 1 1 2\n! 2"] | f1b4048e5cd2aa0a533af9d08f7d58ba | NoteIn the example test the matrix $$$a$$$ of size $$$3 \times 4$$$ is equal to: 1 2 1 23 3 3 32 1 2 1 | This is an interactive problem.There exists a matrix $$$a$$$ of size $$$n \times m$$$ ($$$n$$$ rows and $$$m$$$ columns), you know only numbers $$$n$$$ and $$$m$$$. The rows of the matrix are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the matrix are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$x$$$-th row and the $$$y$$$-th column is denoted as $$$(x, y)$$$.You are asked to find the number of pairs $$$(r, c)$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$, $$$r$$$ is a divisor of $$$n$$$, $$$c$$$ is a divisor of $$$m$$$) such that if we split the matrix into rectangles of size $$$r \times c$$$ (of height $$$r$$$ rows and of width $$$c$$$ columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal.You can use queries of the following type: ? $$$h$$$ $$$w$$$ $$$i_1$$$ $$$j_1$$$ $$$i_2$$$ $$$j_2$$$ ($$$1 \le h \le n$$$, $$$1 \le w \le m$$$, $$$1 \le i_1, i_2 \le n$$$, $$$1 \le j_1, j_2 \le m$$$) — to check if non-overlapping subrectangles of height $$$h$$$ rows and of width $$$w$$$ columns of matrix $$$a$$$ are equal or not. The upper left corner of the first rectangle is $$$(i_1, j_1)$$$. The upper left corner of the second rectangle is $$$(i_2, j_2)$$$. Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect. You can use at most $$$ 3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor$$$ queries. All elements of the matrix $$$a$$$ are fixed before the start of your program and do not depend on your queries. | When ready, print a line with an exclamation mark ('!') and then the answer — the number of suitable pairs $$$(r, c)$$$. After that your program should terminate. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of rows and columns, respectively. | standard output | standard input | Python 3 | Python | 2,600 | train_105.jsonl | 69807fc8ec9bc8172ce430138c0a162a | 256 megabytes | ["3 4\n1\n1\n1\n0"] | PASSED | import sys
input = sys.stdin.readline
def solve():
r, c = map(int, input().split())
r1 = r
r2 = r
i = 2
while True:
if r2 % i == 0:
while r2 % i == 0:
r2 //= i
while r1 % i == 0:
#print('r',i)
if i == 2:
print('?',r1//i,c,1,1,r1//i+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
r1 //= 2
else:
z = i//2
h1 = r1//i
h = h1*z
print('?',h,c,1,1,h+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
print('?',h,c,1+h1,1,h+h1+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
if z != 1:
print('?',h1,c,1,1,h1+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
r1 //= i
if i * i <= r2:
i += 1
elif r2 == 1:
break
elif i >= r2:
break
else:
i = r2
i = 2
c1 = c
c2 = c
while True:
if c2 % i == 0:
while c2 % i == 0:
c2 //= i
while c1 % i == 0:
#print('c',i)
if i == 2:
print('?',r,c1//i,1,1,1,1+c1//i)
sys.stdout.flush()
if int(input()) == 0:
break
c1 //= 2
else:
z = i//2
w1 = c1//i
w = w1*z
print('?',r,w,1,1,1,1+w)
sys.stdout.flush()
if int(input()) == 0:
break
print('?',r,w,1,1+w1,1,1+w+w1)
sys.stdout.flush()
if int(input()) == 0:
break
if z != 1:
print('?',r,w1,1,1,1,1+w1)
sys.stdout.flush()
if int(input()) == 0:
break
c1 //= i
if i * i <= c2:
i += 1
elif c2 == 1:
break
elif i >= c2:
break
else:
i = c2
r //= r1
c //= c1
d1 = 0
for i in range(1,r+1):
if r % i == 0:
d1 += 1
d2 = 0
for i in range(1,c+1):
if c % i == 0:
d2 += 1
print('!', d1*d2)
solve()
| 1615039500 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds | ["4", "20"] | ecbc339ad8064681789075f9234c269a | null | In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down. | Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down. | The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l < m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l]. | standard output | standard input | PyPy 3 | Python | 1,700 | train_038.jsonl | a2b652b157428b0c0ef5c47464f7a96e | 64 megabytes | ["2 2 5 3", "5 4 11 8"] | PASSED | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
#-------------------------------------------------------------------------
n,d,m,l=map(int,input().split())
ch=1
for i in range (1,10**6+1):
x=i*d
k=x//m+1
x1=(k-1)*m
if x1+l<x or k>n:
print(x)
ch=0
break
if ch:
f=math.ceil(((n-1)*m+l+1)/d)
f=f*d
print(f) | 1276700400 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["3 1 1 \n700000000 700000000 \n0 0 0 0 0 \n0 0 2 1 0 \n0 0 \n9 9 999999990 \n0 0 0 \n3 1 3 1 1 1 \n0 0", "0 1 1 0 0 0 0 0 \n0 0 0 0 0 0 0 0 0 \n0 0 0 3 1 1 3 0 0 \n0 2 0 0 2 5 9 1 4"] | 9be594097a1b2249c4227bde12c5552c | NoteIn the first test case of the first sample there is only one segment of color $$$2$$$, and all other segments have color $$$1$$$. Therefore, for segments of color $$$1$$$, the answer is equal to the distance to the $$$3$$$rd segment, and for $$$3$$$rd one, the answer is equal to the minimum of the distances to segments of color $$$1$$$.In the second test case of the first sample there are only $$$2$$$ segments, and for both of them the answer is equal to the distance between them.In the third test case of the first sample, each segment intersects at least one of its ends with a segment of a different color, so all answers are equal to $$$0$$$.The fourth test case of the first sample is described in the problem statement.In the fifth test case of the first sample, one segment lies completely inside the other, and for both of them the answer is $$$0$$$.In the sixth test case of the first sample, all segments are points of different colors. | Dmitry has $$$n$$$ segments of different colors on the coordinate axis $$$Ox$$$. Each segment is characterized by three integers $$$l_i$$$, $$$r_i$$$ and $$$c_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le c_i \le n$$$), where $$$l_i$$$ and $$$r_i$$$ are are the coordinates of the ends of the $$$i$$$-th segment, and $$$c_i$$$ is its color.Dmitry likes to find the minimum distances between segments. However, he considers pairs of segments of the same color uninteresting. Therefore, he wants to know for each segment the distance from this segment to the nearest differently colored segment.The distance between two segments is the minimum of the distances between a point of the first segment and a point of the second segment. In particular, if the segments intersect, then the distance between them is equal to $$$0$$$.For example, Dmitry has $$$5$$$ segments: The first segment intersects with the second (and these are segments of different colors), so the answers for them are equal to $$$0$$$. For the $$$3$$$-rd segment, the nearest segment of a different color is the $$$2$$$-nd segment, the distance to which is equal to $$$2$$$. For the $$$4$$$-th segment, the nearest segment of a different color is the $$$5$$$-th segment, the distance to which is equal to $$$1$$$. The $$$5$$$-th segment lies inside the $$$2$$$-nd segment (and these are segments of different colors), so the answers for them are equal to $$$0$$$. | For each test case, on a separate line print $$$n$$$ integers, where the $$$i$$$-th number is equal to the distance from the $$$i$$$-th segment to the nearest segment of a different color. | The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of segments. The next $$$n$$$ lines contain descriptions of the segments. Each segment is described by three integers $$$l_i$$$, $$$r_i$$$ and $$$c_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le c_i \le n$$$) — coordinates of the left and right ends of $$$i$$$-th segment, as well as the color of this segment. It is guaranteed that there are at least $$$2$$$ segments of different colors. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 2,000 | train_084.jsonl | ee26ba0f05f2664ce9bc05badfd3fa9d | 256 megabytes | ["9\n\n3\n\n1 2 1\n\n3 4 1\n\n5 6 2\n\n2\n\n100000000 200000000 1\n\n900000000 1000000000 2\n\n5\n\n1 2 1\n\n2 3 2\n\n3 4 3\n\n4 5 4\n\n5 6 5\n\n5\n\n1 5 1\n\n4 9 2\n\n1 2 1\n\n8 9 2\n\n5 7 3\n\n2\n\n1 100 2\n\n10 90 1\n\n3\n\n1 1 1\n\n10 10 2\n\n1000000000 1000000000 3\n\n3\n\n3 4 1\n\n2 5 1\n\n1 6 2\n\n6\n\n5 6 2\n\n11 12 3\n\n7 8 2\n\n3 4 2\n\n1 2 1\n\n9 10 2\n\n2\n\n1 3 1\n\n2 3 2", "4\n\n8\n\n11 16 7\n\n12 15 7\n\n2 5 8\n\n17 22 5\n\n1 8 8\n\n19 23 8\n\n16 16 6\n\n6 7 5\n\n9\n\n1 4 3\n\n5 11 1\n\n8 11 3\n\n1 10 1\n\n2 11 1\n\n1 10 4\n\n3 11 1\n\n5 7 1\n\n1 11 1\n\n9\n\n25 25 1\n\n26 26 1\n\n24 24 2\n\n13 14 2\n\n12 16 2\n\n17 18 1\n\n19 19 1\n\n24 27 2\n\n24 27 1\n\n9\n\n15 18 1\n\n20 22 2\n\n13 22 2\n\n13 22 2\n\n3 13 2\n\n6 10 2\n\n3 6 2\n\n19 24 2\n\n22 24 2"] | PASSED | t = int(input())
def dist(i,j):
if i >= j:
return 0
else:
return j-i
while t > 0:
n = int(input())
seg = []
for i in range(n):
seg.append(list(map(int,input().split()))+[i+1])
seg.sort(key=lambda x:(x[0],x[1]))
color = {}
i = 0
while i < n:
if seg[i][2] in color:
if seg[i][2] == seg[i-1][2]:
j = i
while j < n-1 and seg[j][2] == seg[j+1][2]:
j = j + 1
color[seg[i][2]][-1][1] = j+1
for k in range(i,j+1):
color[seg[i][2]].append([k,j+1])
i = j+1
continue
else:
color[seg[i][2]].append([i,i+1])
i = i + 1
else:
color[seg[i][2]] = [[i,i+1],]
i = i + 1
mindis= [1000000000]*(n+1)
signal = [0]*(n+1)
nowmaxj = [[0,0],[0,0]]
i = 0
while i < n:
nowcolor = seg[i][2]
u = signal[nowcolor]
end = color[nowcolor][u][1]
signal[nowcolor] += end - i
maxj = 0
if end != n:
for j in range(i,end):
maxj = max(maxj,seg[j][1])
mindis[seg[j][3]] = min(mindis[seg[j][3]],dist(seg[j][1],seg[end][0]))
for k in range(2):
if nowmaxj[k][1] != 0 and nowmaxj[k][1] != nowcolor:
mindis[seg[j][3]] = min(mindis[seg[j][3]],dist(nowmaxj[k][0],seg[j][0]))
else:
for j in range(i,end):
for k in range(2):
if nowmaxj[k][1] != 0 and nowmaxj[k][1] != nowcolor:
mindis[seg[j][3]] = min(mindis[seg[j][3]],dist(nowmaxj[k][0],seg[j][0]))
break
if maxj > nowmaxj[0][0]:
if nowmaxj[0][1] == nowcolor:
nowmaxj[0][0] = maxj
else:
nowmaxj[1][0] = nowmaxj[0][0]
nowmaxj[1][1] = nowmaxj[0][1]
nowmaxj[0] = [maxj,nowcolor]
elif maxj > nowmaxj[1][0]:
if nowcolor != nowmaxj[0][1]:
nowmaxj[1] = [maxj,nowcolor]
i = end
print(" ".join(map(str,mindis[1:])))
t = t - 1 | 1665498900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["4", "629909355", "675837193"] | 7ad1f3f220c12a68c1242a22f4fd7761 | NoteFor the first sample case, the first player has $$$4$$$ possible moves. No matter what the first player plays, the second player only has $$$1$$$ possible move, so there are $$$4$$$ possible games. | Omkar and Akmar are playing a game on a circular board with $$$n$$$ ($$$2 \leq n \leq 10^6$$$) cells. The cells are numbered from $$$1$$$ to $$$n$$$ so that for each $$$i$$$ ($$$1 \leq i \leq n-1$$$) cell $$$i$$$ is adjacent to cell $$$i+1$$$ and cell $$$1$$$ is adjacent to cell $$$n$$$. Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$. Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move. | Output a single integer — the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$. | The only line will contain an integer $$$n$$$ ($$$2 \leq n \leq 10^6$$$) — the number of cells on the board. | standard output | standard input | Python 3 | Python | 2,600 | train_094.jsonl | 0ca1ebea0d32ae542243957267a7ece4 | 256 megabytes | ["2", "69420", "42069"] | PASSED | from math import factorial
def win(a):
bw = None;bc = 0
for i in range(len(a)):
if a[i] is None:
for j in range(2):
if a[i-1] == j or a[(i+1)%len(a)] == j:continue
a[i] = j;w, c = win(a);a[i] = None
if bw != False:
bw = w
if w == False:bc = c
else:bc += c
else:bc += c
if bw is None:return False, 1
else:return ((not bw), bc)
F = dict()
def win1(left, d):
global F;a = []
if left == 0:return 0
if (left, d) in F:return F[(left, d)]
if left == 1:
if d == 0:a.append(0)
else:F[(left, d)] = 0;return 0
else:
if d == 1:
a.append(win1(0,1) ^ win1(left-1,0))
for i in range(1,left-1):a.append(win1(i,1) ^ win1(left-i-1,0));a.append(win1(i,0) ^ win1(left-i-1,1))
else:
a.append(win1(0,1) ^ win1(left-1,1))
for i in range(1,left-1):a.append(win1(i,1) ^ win1(left-i-1,1));a.append(win1(i,0) ^ win1(left-i-1,0))
s = set(a)
for i in range(100000):
if i not in s:F[(left, d)] = i;return i
def rec(a, i):
if i == len(a):
for i in range(len(a)):
if a[i] == 1 and (a[i-1] == 1 or a[(i+1)%len(a)] == 1):return 0
print(a);return 1
r = 0
for j in range(2):a[i] = j;r += rec(a, i+1)
return r
MOD = 10**9+7;F = [0]*(10**6+3);F[0] = 1
for i in range(1,len(F)):F[i] = (F[i-1]*i)%MOD
FI = [0]*len(F);FI[-1] = pow(F[-1], MOD-2, MOD)
for i in range(len(F)-2,-1,-1):FI[i] = (FI[i+1]*(i+1))%MOD
def C(n, k):return (F[n]*FI[n-k]*FI[k]) % MOD
def H(n, k):
if k == 0:return 1
return C(n-k,k)+C(n-k-1,k-1)
def solve():
n = int(input());r = 0
for i in range(n):
if i*2 > n:break
if (n - i) % 2 == 0:r = (r + H(n, i) * F[n-i]) % MOD
print((2*r)%MOD)
solve() | 1622990100 | [
"geometry",
"math",
"games"
] | [
1,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["10\n0\n4"] | 128d9ad5e5dfe4943e16fcc6a103e51b | NoteIn the first test case, we initially have a piece of size $$$1$$$, so all final pieces must have size $$$1$$$. The total number of steps is: $$$0 + 1 + 2 + 3 + 4 = 10$$$.In the second test case, we have just one piece, so we don't need to do anything, and the answer is $$$0$$$ steps.In the third test case, one of the possible cut options is: $$$600,\ 900,\ (600 | 700),\ (1000 | 1000),\ (1000 | 1000 | 550)$$$. You can see this option in the picture below. The maximum piece has size $$$1000$$$, and it is less than $$$2$$$ times bigger than the minimum piece of size $$$550$$$. $$$4$$$ steps are done. We can show that it is the minimum possible number of steps. | There are $$$n$$$ pieces of tangerine peel, the $$$i$$$-th of them has size $$$a_i$$$. In one step it is possible to divide one piece of size $$$x$$$ into two pieces of positive integer sizes $$$y$$$ and $$$z$$$ so that $$$y + z = x$$$.You want that for each pair of pieces, their sizes differ strictly less than twice. In other words, there should not be two pieces of size $$$x$$$ and $$$y$$$, such that $$$2x \le y$$$. What is the minimum possible number of steps needed to satisfy the condition? | For each test case, output a single line containing the minimum number of steps. | The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 100$$$). Then one line follows, containing $$$n$$$ integers $$$a_1 \le a_2 \le \ldots \le a_n$$$ ($$$1 \le a_i \le 10^7$$$). | standard output | standard input | Python 3 | Python | 900 | train_098.jsonl | c178e0e806b0ecf466dece9e12880c67 | 256 megabytes | ["3\n\n5\n\n1 2 3 4 5\n\n1\n\n1033\n\n5\n\n600 900 1300 2000 2550"] | PASSED | def f(x,m):
if x%(2*m-1)!=0:
return x//(2*m-1)
else:
return x//(2*m-1)-1
N=int(input())
for i in range(N):
n=int(input())
L=list(map(int,input().split()))
M=max(L)
m=min(L)
L1=[x for x in L if x>=2*m]
Lm=[m for i in range(len(L1))]
L2=list(map(f,L1,Lm))
print(sum(L2))
| 1664721300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n2\n2\n10\n5\n9"] | 1f29461c42665523d0a4d56b13f7e480 | NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten. | You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies. | Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input. | The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively. | standard output | standard input | PyPy 3 | Python | 1,100 | train_008.jsonl | 78c76e91c876168cff4ab60aae4818a6 | 256 megabytes | ["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"] | PASSED | n = int(input())
for _ in range(n):
a = list(map(int, input().split()))
a = sorted(a)
if(a[0]+a[1] >= a[2]):
print(sum(a)//2);
else:
print(sum(a)-a[2]);
| 1575038100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3", "9", "130653412"] | 1b336555c94d5d5198abe5426ff6fa7a | NoteFor a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions: z&_ = 61&63 = 61 = z _&z = 63&61 = 61 = z z&z = 61&61 = 61 = z | While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63. | Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7. | The only line of the input contains a single word s (1 ≤ |s| ≤ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'. | standard output | standard input | PyPy 2 | Python | 1,500 | train_007.jsonl | 7f2ae05a46346d3040611ddacd32d9cc | 256 megabytes | ["z", "V_V", "Codeforces"] | PASSED | s = raw_input()
d = 0
ans = 1
for c in map(ord, s):
d = 0
if ord("0") <= c <= ord("9"):
d += c - ord("0")
elif ord("A") <= c <= ord("Z"):
d += c - ord("A") + 10
elif ord("a") <= c <= ord("z"):
d += c - ord("a") + 36
elif ord("-") == c:
d += 62
else:
d += 63
ans *= pow(3, format(d, "06b").count("0"), 10 ** 9 + 7)
ans %= 10 ** 9 + 7
print ans
| 1464798900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["Yes\nNo\nYes\nYes\nNo\nYes\nNo\nNo\nYes\nNo"] | 2d27f3530aa140be0add639a1edfd880 | NoteThe first test case is clarified above.In the second test case, it is impossible to make all array elements equal.In the third test case, you need to apply this operation once to all elements equal to $$$5$$$.In the fourth test case, you need to apply this operation to all elements until they become equal to $$$8$$$.In the fifth test case, it is impossible to make all array elements equal.In the sixth test case, you need to apply this operation to all elements until they become equal to $$$102$$$. | You are given an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$You can apply the following operation an arbitrary number of times: select an index $$$i$$$ ($$$1 \le i \le n$$$) and replace the value of the element $$$a_i$$$ with the value $$$a_i + (a_i \bmod 10)$$$, where $$$a_i \bmod 10$$$ is the remainder of the integer dividing $$$a_i$$$ by $$$10$$$. For a single index (value $$$i$$$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $$$a_i$$$ is taken into account each time. For example, if $$$a_i=47$$$ then after the first operation we get $$$a_i=47+7=54$$$, and after the second operation we get $$$a_i=54+4=58$$$.Check if it is possible to make all array elements equal by applying multiple (possibly zero) operations.For example, you have an array $$$[6, 11]$$$. Let's apply this operation to the first element of the array. Let's replace $$$a_1 = 6$$$ with $$$a_1 + (a_1 \bmod 10) = 6 + (6 \bmod 10) = 6 + 6 = 12$$$. We get the array $$$[12, 11]$$$. Then apply this operation to the second element of the array. Let's replace $$$a_2 = 11$$$ with $$$a_2 + (a_2 \bmod 10) = 11 + (11 \bmod 10) = 11 + 1 = 12$$$. We get the array $$$[12, 12]$$$. Thus, by applying $$$2$$$ operations, you can make all elements of an array equal. | For each test case print: YES if it is possible to make all array elements equal; NO otherwise. You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer) . | The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. What follows is a description of each test case. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \le a_i \le 10^9$$$) — array elements. 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,400 | train_103.jsonl | 3d2093b68a460abe765d08ba42298b9f | 256 megabytes | ["10\n\n2\n\n6 11\n\n3\n\n2 18 22\n\n5\n\n5 10 5 10 5\n\n4\n\n1 2 4 8\n\n2\n\n4 5\n\n3\n\n93 96 102\n\n2\n\n40 6\n\n2\n\n50 30\n\n2\n\n22 44\n\n2\n\n1 5"] | PASSED | t = int(input())
for ti in range(t):
n = int(input())
a = sorted(list(map(int, input().split())))
is0 = False
res = "YES"
while a[0] % 10 != 2:
a[0] += a[0] % 10
if a[0] % 10 == 0:
is0 = True
break
for i in range(n - 1):
while a[i + 1] % 10 != 2:
a[i + 1] += a[i + 1] % 10
if a[i + 1] % 10 == 0:
if not is0:
res = "NO"
break
if res == "NO":
break
if is0:
if a[i] != a[i + 1]:
res = "NO"
if (a[i + 1] - a[i]) % 20 != 0:
res = "NO"
print(res) | 1659364500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["1\n2"] | 7b80d3f3cd4f93e4277c76c76dc41f42 | NoteIn the first test case, you can do the following to achieve a length of $$$1$$$:Pick $$$i=2$$$ to get $$$[2, 4, 1]$$$Pick $$$i=1$$$ to get $$$[6, 1]$$$Pick $$$i=1$$$ to get $$$[7]$$$In the second test case, you can't perform any operations because there is no valid $$$i$$$ that satisfies the requirements mentioned above. | Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array $$$a$$$ of $$$n$$$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $$$i$$$ such that $$$1 \leq i < n$$$ and $$$a_{i} \neq a_{i+1}$$$, delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array and put $$$a_{i}+a_{i+1}$$$ in their place. For example, for array $$$[7, 4, 3, 7]$$$ you can choose $$$i = 2$$$ and the array will become $$$[7, 4+3, 7] = [7, 7, 7]$$$. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by $$$1$$$. What is the shortest possible length of the password after some number (possibly $$$0$$$) of operations? | For each password, print one integer: the shortest possible length of the password after some number of operations. | 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 line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the password. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the initial contents of your password. The sum of $$$n$$$ over all test cases will not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 2 | Python | 800 | train_003.jsonl | 581c7f544173e2b83ed06c0109da7265 | 256 megabytes | ["2\n4\n2 1 3 1\n2\n420 420"] | PASSED | from __future__ import division, print_function
import os,sys
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
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split(" "))
def msi(): return map(str,input().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
import math
def getSum(n):
sum = 0
while(n > 0):
sum += int(n%10)
n = int(n/10)
return sum
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def gcd(x, y):
while y:
x, y = y, x % y
return x
def egcd(a, b):
if a == 0 :
return b, 0, 1
gcd, x1, y1 = egcd(b%a, a)
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
def checkPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def fib(n):
if n==0:
return (0,1)
p=fib(n>>1)
c=p[0]*(2*p[1]-p[0])
d=p[0]*p[0]+p[1]*p[1]
if (n&1):
return c+2*d
else:
return c+d
def read():
sys.stdin = open('input.txt', 'r')
def powLog(x,y):
res=1
while y>0:
if y&1:
res=res*x
x=x*x
y>>=1
return res
def main():
for _ in range(ii()):
n=ii()
a=set(li())
if len(a)==1:
print(n)
else:
print(1)
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read() | 1597588500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["ACC\nACC\nACC\nWA\nACC\nACC\nWA", "WA\nACC\nACC"] | 95ccc87fe9e431f9c6eeffeaf049f797 | null | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. | For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK. | The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively. In the fourth line there is a single integer n (0 ≤ n ≤ 1000), the number of students. Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively. | standard output | standard input | PyPy 3 | Python | 1,300 | train_030.jsonl | c6f70d857fd53d32b24fe65ee7a5aa54 | 256 megabytes | ["Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful", "Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;"] | PASSED | def s():
import re,itertools
pattern = re.compile('[^a-z]+')
def st(x):
return pattern.sub('',x.lower())
s = set([''.join(i)for i in itertools.permutations([st(input())for _ in range(3)])])
for i in range(int(input())):
print('ACC'if st(input()) in s else 'WA')
s() | 1298390400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["1", "5"] | c15ad483441864b3222eb62723b598e1 | NoteIn the first example the only element can be removed. | You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai. | Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one. | The first line contains the only integer n (1 ≤ n ≤ 105) — the length of the permutation. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation. All the integers are distinct. | standard output | standard input | Python 3 | Python | 1,700 | train_005.jsonl | ce3aabd502c6918c7a3f96acb2c5ac21 | 256 megabytes | ["1\n1", "5\n5 1 2 3 4"] | PASSED | import sys
cases = sys.stdin.readline()
my_list = [int(a) for a in sys.stdin.readline().split(" ")]
#my_list = [4, 5, 3, 2, 1]
max_val_a = my_list[0]
max_val_b = 0
my_counts = dict()
for x in my_list:
my_counts[x] = 0
my_counts[max_val_a] = -1
for x in my_list:
#print(my_counts)
if(x > max_val_a):
my_counts[x] = my_counts[x] - 1
max_val_a, max_val_b = x, max_val_a
elif (x < max_val_a and x > max_val_b):
my_counts[max_val_a] = my_counts[max_val_a] + 1
max_val_b = x
#print(my_counts)
highest = max(my_counts.values())
print(min([k for k, v in my_counts.items() if v == highest])) | 1513008300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3 6\n4 5\n3 4\n1 9\n2 3\n4 5\n6 10"] | 96fac9f9377bf03e144067bf93716d3d | NoteIn the first test case, $$$b = \{3+6, 4+5\} = \{9, 9\}$$$ and $$$\mathrm{gcd}(9, 9) = 9$$$.In the second test case, $$$b = \{9+10\} = \{19\}$$$ and $$$\mathrm{gcd}(19) = 19$$$.In the third test case, $$$b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\}$$$ and $$$\mathrm{gcd}(3, 6, 9, 93) = 3$$$. | Ashish has an array $$$a$$$ of consisting of $$$2n$$$ positive integers. He wants to compress $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$. To do this, he first discards exactly $$$2$$$ (any two) elements from $$$a$$$. He then performs the following operation until there are no elements left in $$$a$$$: Remove any two elements from $$$a$$$ and append their sum to $$$b$$$. The compressed array $$$b$$$ has to have a special property. The greatest common divisor ($$$\mathrm{gcd}$$$) of all its elements should be greater than $$$1$$$.Recall that the $$$\mathrm{gcd}$$$ of an array of positive integers is the biggest integer that is a divisor of all integers in the array.It can be proven that it is always possible to compress array $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$ such that $$$gcd(b_1, b_2..., b_{n-1}) > 1$$$. Help Ashish find a way to do so. | For each test case, output $$$n-1$$$ lines — the operations performed to compress the array $$$a$$$ to the array $$$b$$$. The initial discard of the two elements is not an operation, you don't need to output anything about it. The $$$i$$$-th line should contain two integers, the indices ($$$1$$$ —based) of the two elements from the array $$$a$$$ that are used in the $$$i$$$-th operation. All $$$2n-2$$$ indices should be distinct integers from $$$1$$$ to $$$2n$$$. You don't need to output two initially discarded elements from $$$a$$$. If there are multiple answers, you can find any. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 1000$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ ($$$1 \leq a_i \leq 1000$$$) — the elements of the array $$$a$$$. | standard output | standard input | Python 3 | Python | 1,100 | train_016.jsonl | 9b97c90fcc9a49511e40527837170e52 | 256 megabytes | ["3\n3\n1 2 3 4 5 6\n2\n5 7 9 10\n5\n1 3 3 4 5 90 100 101 2 3"] | PASSED | # cook your dish here
T=int(input())
for _ in range(T):
n=int(input())
s=list(map(int,input().split()))
odd=[]
even=[]
for i in range(len(s)):
if(s[i]%2!=0):
odd.append(i+1)
else:
even.append(i+1)
count=0
for i in range(0,len(odd)-1,2):
if(count<n-1):
print(odd[i],odd[i+1])
count+=1
else:
break
for i in range(0,len(even)-1,2):
if(count<n-1):
print(even[i],even[i+1])
count+=1
else:
break | 1592663700 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["3\n1\n3\n0"] | e0de8a6441614d1e41a53223b5fa576b | NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves: the first move: $$$i=9$$$; the second move: $$$i=9$$$; the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders. | You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible: initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$; $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$; $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$; $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders. | For each test case, output one integer — the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^4$$$) — the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\,000$$$. | standard output | standard input | PyPy 3-64 | Python | 1,000 | train_098.jsonl | 4c879f2d0fbc86b5275d7ea344a96adf | 256 megabytes | ["4\n6\n0 2 5 5 4 8\n6\n2 0 2 1 0 0\n9\n7 1 3 4 2 10 3 9 6\n6\n0 1 2 3 4 5"] | PASSED | for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
count = 0
ht = {0: 0, 1: 0, 2: 0}
for i in arr:
ht[i % 3] += 1
while True:
# print(ht)
diff = 1
if ht[0] == ht[1] == ht[2]:
print(count)
break
if ht[0] > ht[1] and ht[0] > n // 3:
diff = abs(n // 3 - ht[0])
ht[1] += diff
ht[0] -= diff
elif ht[1] > ht[2] and ht[1] > n // 3:
diff = abs(n // 3 - ht[1])
ht[2] += diff
ht[1] -= diff
elif ht[2] > ht[0] and ht[2] > n // 3:
diff = abs(n // 3 - ht[2])
ht[0] += diff
ht[2] -= diff
count += diff
| 1613486100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["Yes", "No", "Yes"] | bedb98780a71d7027798d14aa5f1f100 | NoteThe picture below illustrates one of the possible trees for the first example. The picture below illustrates one of the possible trees for the third example. | Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset. To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed $$$1$$$.Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here. | If it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than $$$1$$$, print "Yes" (quotes for clarity). Otherwise, print "No" (quotes for clarity). | The first line contains the number of vertices $$$n$$$ ($$$2 \le n \le 700$$$). The second line features $$$n$$$ distinct integers $$$a_i$$$ ($$$2 \le a_i \le 10^9$$$) — the values of vertices in ascending order. | standard output | standard input | PyPy 3 | Python | 2,100 | train_061.jsonl | c3d37b01356f6d8acc95dce16f758cde | 256 megabytes | ["6\n3 6 9 18 36 108", "2\n7 17", "9\n4 8 10 12 15 18 33 44 81"] | PASSED | from sys import stdin
from math import gcd
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
c = []
ld=[]
rd=[]
def check(l, r, e):
if r == l: return c[l][e] > 0
if e < l and ld[l][r-l] != 0:
return ld[l][r-l] == 1
elif e > r and rd[l][r-l] != 0:
return rd[l][r-l] == 1
for i in range(l, r+1):
if c[i][e]>0:
if i==l or check(l, i-1, i):
if i==r or check(i+1, r, i):
if e < l:
ld[l][r-l] = 1
else:
rd[l][r-l] = 1
return True
if e < l:
ld[l][r - l] = -1
else:
rd[l][r - l] = -1
return False
for i in range(n):
c.append([0]*n)
ld.append([0]*n)
rd.append([0] * n)
for i in range(n):
for j in range(i+1,n):
if gcd(a[i],a[j]) > 1:
c[i][j] = c[j][i] = 1
ans=False
for i in range(n):
if i == 0 or check(0, i - 1, i):
if i == n-1 or check(i + 1, n-1, i):
ans = True
break
if ans:
print("Yes")
else:
print("No")
| 1534685700 | [
"number theory",
"math",
"trees"
] | [
0,
0,
0,
1,
1,
0,
0,
1
] |
|
1 second | ["1337\n0"] | edf394051c6b35f593abd4c34b091eae | NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money. | You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations: Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation: $$$x = 0$$$, $$$y = 6$$$; $$$x = 0$$$, $$$y = 8$$$; $$$x = -1$$$, $$$y = 7$$$; $$$x = 1$$$, $$$y = 7$$$. Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation: $$$x = -1$$$, $$$y = 6$$$; $$$x = 1$$$, $$$y = 8$$$. Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it. | For each test case print one integer — the minimum amount of dollars you have to spend. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$). | standard output | standard input | Python 3 | Python | 1,000 | train_017.jsonl | fce6803770ef2dfbdcde7627ba335e5f | 256 megabytes | ["2\n1 3\n391 555\n0 0\n9 4"] | PASSED | t=int(input())
while(t>0):
t=t-1
l=[]
x,y=map(int,input().split())
a,b=map(int,input().split())
if(x==0 and y==0):
print(x)
elif(x>y):
a1=x-y
a1=a1*a
b1=y
b1=b1*b
l.append(abs(a1)+b1)
a1=x*a
b1=y*a
l.append(abs(a1)+b1)
print(min(l))
elif(x<y):
a1 = x - y
a1 = a1 * a
b1 = x
b1 = b1 * b
l.append(abs(a1) + b1)
a1 = x * a
b1 = y * a
l.append(abs(a1) + b1)
print(min(l))
elif(x==y):
a1=x*2*a
l.append(a1)
b1=x*b
l.append(b1)
print(min(l)) | 1587911700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["42", "7"] | 9044eacc1833c667985c343a71fb4a58 | NoteThe image for the first example: Several key points are marked blue, the answer contains some non-marked points as well.The image for the second example: | You are given $$$n$$$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.Count the number of distinct points with integer coordinates, which are covered by at least one segment. | Print a single integer — the number of distinct points with integer coordinates, which are covered by at least one segment. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of segments. Each of the next $$$n$$$ lines contains four integers $$$Ax_i, Ay_i, Bx_i, By_i$$$ ($$$-10^6 \le Ax_i, Ay_i, Bx_i, By_i \le 10^6$$$) — the coordinates of the endpoints $$$A$$$, $$$B$$$ ($$$A \ne B$$$) of the $$$i$$$-th segment. It is guaranteed that no two segments lie on the same line. | standard output | standard input | PyPy 3 | Python | 2,400 | train_030.jsonl | e8da77cb46ac51e2c16d6199d540469a | 256 megabytes | ["9\n0 0 4 4\n-1 5 4 0\n4 0 4 4\n5 2 11 2\n6 1 6 7\n5 6 11 6\n10 1 10 7\n7 0 9 8\n10 -1 11 -1", "4\n-1 2 1 2\n-1 0 1 0\n-1 0 0 3\n0 3 1 0"] | PASSED | from math import gcd
from bisect import *
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, val):
return Point(self.x + val.x, self.y + val.y)
def __sub__(self, val):
return Point(self.x - val.x, self.y - val.y)
def __mul__(self, ratio):
return Point(self.x * ratio, self.y * ratio)
def __truediv__(self, ratio):
return Point(self.x / ratio, self.y / ratio)
@staticmethod
def det(A, B):
return A.x * B.y - A.y * B.x
@staticmethod
def dot(A, B):
return A.x * B.x + A.y * B.y
def onSegment(self, A, B):
if self.det(B-A, self-A) != 0:
return False
if self.dot(B-A, self-A) < 0:
return False
if self.dot(A-B, self-B) < 0:
return False
return True
def intPoints(x1, y1, x2, y2):
dx, dy = abs(x2 - x1), abs(y2 - y1)
return gcd(dx, dy) + 1
def crosspoint(L1, L2):
A, B = Point(L1[0], L1[1]), Point(L1[2], L1[3])
C, D = Point(L2[0], L2[1]), Point(L2[2], L2[3])
S1, S2 = Point.det(C-A, D-A), Point.det(C-D, B-A)
delta = (B - A) * S1
if S2 == 0 or delta.x % S2 != 0 or delta.y % S2 != 0:
return None
delta = delta / S2;
P = A + delta
if not P.onSegment(A, B) or not P.onSegment(C, D):
return None
return (P.x, P.y)
n = int(input())
lines = [ tuple(int(z) for z in input().split()) \
for i in range(n) ]
count = dict()
for i in range(n):
for j in range(i):
P = crosspoint(lines[i], lines[j])
if P != None:
count[P] = count.get(P, 0) + 1
answer = sum(intPoints(*L) for L in lines)
tri = [ x*(x+1)//2 for x in range(n+1) ]
for z in count:
k = bisect_right(tri, count[z])
answer -= k - 1;
print(answer)
| 1536330900 | [
"number theory",
"geometry"
] | [
0,
1,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"] | 0937a7e2f912fc094cc4275fd47cd457 | NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled. | Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≤ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists. | On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order. | The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills. | standard output | standard input | Python 3 | Python | 1,500 | train_024.jsonl | e090f3bd4d35427b7cdf99338edfc957 | 256 megabytes | ["3\n1 2 1", "5\n2 3 3 1 1"] | PASSED | n = int(input())
a = list(map(int, input().split()))
all = []
for i in range(n):
all.append([a[i], i + 1])
all.sort(key = lambda x: x[0])
team_1 = []
team_2 = []
for i in range(n):
if i % 2 == 0:
team_1.append(all[i][1])
else:
team_2.append(all[i][1])
print(len(team_1))
print(*team_1)
print(len(team_2))
print(*team_2) | 1328886000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nNO"] | 465f1c612fa43313005d90cc8e9e6a24 | NoteHere is a visualization of the first test case (the orange values denote the initial values and the blue ones the desired values): One possible order of operations to obtain the desired values for each node is the following: Operation $$$1$$$: Add $$$2$$$ to nodes $$$2$$$ and $$$3$$$. Operation $$$2$$$: Add $$$-2$$$ to nodes $$$1$$$ and $$$4$$$. Operation $$$3$$$: Add $$$6$$$ to nodes $$$3$$$ and $$$4$$$. Now we can see that in total we added $$$-2$$$ to node $$$1$$$, $$$2$$$ to node $$$2$$$, $$$8$$$ to node $$$3$$$ and $$$4$$$ to node $$$4$$$ which brings each node exactly to it's desired value.For the graph from the second test case it's impossible to get the target values. | You have a connected undirected graph made of $$$n$$$ nodes and $$$m$$$ edges. The $$$i$$$-th node has a value $$$v_i$$$ and a target value $$$t_i$$$.In an operation, you can choose an edge $$$(i, j)$$$ and add $$$k$$$ to both $$$v_i$$$ and $$$v_j$$$, where $$$k$$$ can be any integer. In particular, $$$k$$$ can be negative.Your task to determine if it is possible that by doing some finite number of operations (possibly zero), you can achieve for every node $$$i$$$, $$$v_i = t_i$$$. | For each test case, if it is possible for every node to reach its target after some number of operations, print "YES". Otherwise, print "NO". | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. Then the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$n-1\leq m\leq \min(2\cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of nodes and edges respectively. The second line contains $$$n$$$ integers $$$v_1\ldots, v_n$$$ ($$$-10^9 \leq v_i \leq 10^9$$$) — initial values of nodes. The third line contains $$$n$$$ integers $$$t_1\ldots, t_n$$$ ($$$-10^9 \leq t_i \leq 10^9$$$) — target values of nodes. Each of the next $$$m$$$ lines contains two integers $$$i$$$ and $$$j$$$ representing an edge between node $$$i$$$ and node $$$j$$$ ($$$1 \leq i, j \leq n$$$, $$$i\ne j$$$). It is guaranteed that the graph is connected and there is at most one edge between the same pair of nodes. It is guaranteed that the sum of $$$n$$$ over all testcases does not exceed $$$2 \cdot 10^5$$$ and the sum of $$$m$$$ over all testcases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,200 | train_084.jsonl | 24f06b8c054eb9061543f625a56e741c | 256 megabytes | ["2\n4 4\n5 1 2 -3\n3 3 10 1\n1 2\n1 4\n3 2\n3 4\n4 4\n5 8 6 6\n-3 1 15 4\n1 2\n1 4\n3 2\n3 4"] | PASSED | import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import gcd as GCD
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
class Graph:
def __init__(self,V,edges=False,graph=False,directed=False,weighted=False):
self.V=V
self.directed=directed
self.weighted=weighted
if not graph:
self.edges=edges
self.graph=[[] for i in range(self.V)]
if weighted:
for i,j,d in self.edges:
self.graph[i].append((j,d))
if not self.directed:
self.graph[j].append((i,d))
else:
for i,j in self.edges:
self.graph[i].append(j)
if not self.directed:
self.graph[j].append(i)
else:
self.graph=graph
self.edges=[]
for i in range(self.V):
if self.weighted:
for j,d in self.graph[i]:
if self.directed or not self.directed and i<=j:
self.edges.append((i,j,d))
else:
for j in self.graph[i]:
if self.directed or not self.directed and i<=j:
self.edges.append((i,j))
def SS_BFS(self,s,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False):
seen=[False]*self.V
seen[s]=True
if linked_components:
lc=[s]
if parents:
ps=[None]*self.V
ps[s]=s
if unweighted_dist or bipartite_graph:
uwd=[float('inf')]*self.V
uwd[s]=0
if weighted_dist:
wd=[float('inf')]*self.V
wd[s]=0
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
if linked_components:
lc.append(y)
if parents:
ps[y]=x
if unweighted_dist or bipartite_graph:
uwd[y]=uwd[x]+1
if weighted_dist:
wd[y]=wd[x]+d
if bipartite_graph:
bg=[[],[]]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if type(uwd[i])==float or type(uwd[j])==float:
continue
if not uwd[i]%2^uwd[j]%2:
bg=False
break
else:
for x in range(self.V):
if type(uwd[x])==float:
continue
bg[uwd[x]%2].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if unweighted_dist:
tpl+=(uwd,)
if weighted_dist:
tpl+=(wd,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def AP_BFS(self,bipartite_graph=False,linked_components=False,parents=False):
seen=[False]*self.V
if bipartite_graph:
bg=[None]*self.V
cnt=-1
if linked_components:
lc=[]
if parents:
ps=[None]*self.V
for s in range(self.V):
if seen[s]:
continue
seen[s]=True
if bipartite_graph:
cnt+=1
bg[s]=(cnt,s&2)
if linked_components:
lc.append([s])
if parents:
ps[s]=s
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
if bipartite_graph:
bg[y]=(cnt,bg[x][1]^1)
if linked_components:
lc[-1].append(y)
if parents:
ps[y]=x
if bipartite_graph:
bg_=bg
bg=[[[],[]] for i in range(cnt+1)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if not bg_[i][1]^bg_[j][1]:
bg[bg_[i][0]]=False
for x in range(self.V):
if bg[bg_[x][0]]:
bg[bg_[x][0]][bg_[x][1]].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def SS_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False,unweighted_dist=False,weighted_dist=False):
seen=[False]*self.V
finished=[False]*self.V
if directed_acyclic or cycle_detection or topological_sort:
dag=True
if euler_tour:
et=[]
if linked_components:
lc=[]
if parents or cycle_detection:
ps=[None]*self.V
ps[s]=s
if postorder or topological_sort:
post=[]
if preorder:
pre=[]
if unweighted_dist or bipartite_graph:
uwd=[float('inf')]*self.V
uwd[s]=0
if weighted_dist:
wd=[float('inf')]*self.V
wd[s]=0
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
if euler_tour:
et.append(x)
if linked_components:
lc.append(x)
if preorder:
pre.append(x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
if parents or cycle_detection:
ps[y]=x
if unweighted_dist or bipartite_graph:
uwd[y]=uwd[x]+1
if weighted_dist:
wd[y]=wd[x]+d
elif not finished[y]:
if (directed_acyclic or cycle_detection or topological_sort) and dag:
dag=False
if cycle_detection:
cd=(y,x)
elif not finished[x]:
finished[x]=True
if euler_tour:
et.append(~x)
if postorder or topological_sort:
post.append(x)
if bipartite_graph:
bg=[[],[]]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if type(uwd[i])==float or type(uwd[j])==float:
continue
if not uwd[i]%2^uwd[j]%2:
bg=False
break
else:
for x in range(self.V):
if type(uwd[x])==float:
continue
bg[uwd[x]%2].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if cycle_detection:
if dag:
cd=[]
else:
y,x=cd
cd=self.Route_Restoration(y,x,ps)
tpl+=(cd,)
if directed_acyclic:
tpl+=(dag,)
if euler_tour:
tpl+=(et,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if postorder:
tpl+=(post,)
if preorder:
tpl+=(pre,)
if topological_sort:
if dag:
tp_sort=post[::-1]
else:
tp_sort=[]
tpl+=(tp_sort,)
if unweighted_dist:
tpl+=(uwd,)
if weighted_dist:
tpl+=(wd,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def AP_DFS(self,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False):
seen=[False]*self.V
finished=[False]*self.V
if bipartite_graph:
bg=[None]*self.V
cnt=-1
if directed_acyclic or cycle_detection or topological_sort:
dag=True
if euler_tour:
et=[]
if linked_components:
lc=[]
if parents or cycle_detection:
ps=[None]*self.V
if postorder or topological_sort:
post=[]
if preorder:
pre=[]
for s in range(self.V):
if seen[s]:
continue
if bipartite_graph:
cnt+=1
bg[s]=(cnt,s&2)
if linked_components:
lc.append([])
if parents:
ps[s]=s
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
if euler_tour:
et.append(x)
if linked_components:
lc[-1].append(x)
if preorder:
pre.append(x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
if bipartite_graph:
bg[y]=(cnt,bg[x][1]^1)
if parents or cycle_detection:
ps[y]=x
elif not finished[y]:
if directed_acyclic and dag:
dag=False
if cycle_detection:
cd=(y,x)
elif not finished[x]:
finished[x]=True
if euler_tour:
et.append(~x)
if postorder or topological_sort:
post.append(x)
if bipartite_graph:
bg_=bg
bg=[[[],[]] for i in range(cnt+1)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if not bg_[i][1]^bg_[j][1]:
bg[bg_[i][0]]=False
for x in range(self.V):
if bg[bg_[x][0]]:
bg[bg_[x][0]][bg_[x][1]].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if cycle_detection:
if dag:
cd=[]
else:
y,x=cd
cd=self.Route_Restoration(y,x,ps)
tpl+=(cd,)
if directed_acyclic:
tpl+=(dag,)
if euler_tour:
tpl+=(et,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if postorder:
tpl+=(post,)
if preorder:
tpl+=(pre,)
if topological_sort:
if dag:
tp_sort=post[::-1]
else:
tp_sort=[]
tpl+=(tp_sort,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def Tree_Diameter(self,weighted=False):
def Farthest_Point(u):
dist=self.SS_BFS(u,weighted_dist=True) if self.weighted else self.SS_BFS(u,unweighted_dist=True)
fp=0
for i in range(self.V):
if dist[fp]<dist[i]:
fp=i
return fp,dist[fp]
u,d=Farthest_Point(0)
v,d=Farthest_Point(u)
return u,v,d
def SCC(self):
reverse_graph=[[] for i in range(self.V)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
reverse_graph[j].append(i)
postorder=self.AP_DFS(postorder=True)
scc=[]
seen=[False]*self.V
for s in postorder[::-1]:
if seen[s]:
continue
queue=deque([s])
seen[s]=True
lst=[]
while queue:
x=queue.popleft()
lst.append(x)
for y in reverse_graph[x]:
if self.weighted:
y=y[0]
if not seen[y]:
seen[y]=True
queue.append(y)
scc.append(lst)
return scc
def Build_LCA(self,s):
self.euler_tour,self.parents,depth=self.SS_DFS(s,euler_tour=True,parents=True,unweighted_dist=True)
self.dfs_in_index=[None]*self.V
self.dfs_out_index=[None]*self.V
for i,x in enumerate(self.euler_tour):
if x>=0:
self.dfs_in_index[x]=i
else:
self.dfs_out_index[~x]=i
self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),float('inf'))
lst=[None]*2*self.V
for i in range(2*self.V):
if self.euler_tour[i]>=0:
lst[i]=depth[self.euler_tour[i]]
else:
lst[i]=depth[self.parents[~self.euler_tour[i]]]
self.ST.Build(lst)
def LCA(self,a,b):
m=min(self.dfs_in_index[a],self.dfs_in_index[b])
M=max(self.dfs_in_index[a],self.dfs_in_index[b])
x=self.euler_tour[self.ST.Fold_Index(m,M+1)]
if x>=0:
return x
else:
return self.parents[~x]
def Dijkstra(self,s,route_restoration=False):
dist=[float('inf')]*self.V
dist[s]=0
hq=[(0,s)]
if route_restoration:
parents=[None]*self.V
parents[s]=s
while hq:
dx,x=heapq.heappop(hq)
if dist[x]<dx:
continue
for y,dy in self.graph[x]:
if dist[y]>dx+dy:
dist[y]=dx+dy
if route_restoration:
parents[y]=x
heapq.heappush(hq,(dist[y],y))
if route_restoration:
return dist,parents
else:
return dist
def Bellman_Ford(self,s,route_restoration=False):
dist=[float('inf')]*self.V
dist[s]=0
if route_restoration:
parents=[s]*self.V
for _ in range(self.V-1):
for i,j,d in self.edges:
if dist[j]>dist[i]+d:
dist[j]=dist[i]+d
if route_restoration:
parents[j]=i
if not self.directed and dist[i]>dist[j]+d:
dist[i]=dist[j]+d
if route_restoration:
parents[i]=j
negative_cycle=[]
for i,j,d in self.edges:
if dist[j]>dist[i]+d:
negative_cycle.append(j)
if not self.directed and dist[i]>dist[j]+d:
negative_cycle.append(i)
if negative_cycle:
is_negative_cycle=[False]*self.V
for i in negative_cycle:
if is_negative_cycle[i]:
continue
else:
queue=deque([i])
is_negative_cycle[i]=True
while queue:
x=queue.popleft()
for y,d in self.graph[x]:
if not is_negative_cycle[y]:
queue.append(y)
is_negative_cycle[y]=True
if route_restoration:
parents[y]=x
for i in range(self.V):
if is_negative_cycle[i]:
dist[i]=-float('inf')
if route_restoration:
return dist,parents
else:
return dist
def Warshall_Floyd(self,route_restoration=False):
dist=[[float('inf')]*self.V for i in range(self.V)]
for i in range(self.V):
dist[i][i]=0
if route_restoration:
parents=[[j for j in range(self.V)] for i in range(self.V)]
for i,j,d in self.edges:
if dist[i][j]>d:
dist[i][j]=d
if route_restoration:
parents[i][j]=i
if not self.directed and dist[j][i]>d:
dist[j][i]=d
if route_restoration:
parents[j][i]=j
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
if dist[i][j]>dist[i][k]+dist[k][j]:
dist[i][j]=dist[i][k]+dist[k][j]
if route_restoration:
parents[i][j]=parents[k][j]
for i in range(self.V):
if dist[i][i]<0:
for j in range(self.V):
if dist[i][j]!=float('inf'):
dist[i][j]=-float('inf')
if route_restoration:
return dist,parents
else:
return dist
def Route_Restoration(self,s,g,parents):
route=[g]
while s!=g and parents[g]!=g:
g=parents[g]
route.append(g)
route=route[::-1]
return route
def Kruskal(self):
UF=UnionFind(self.V)
sorted_edges=sorted(self.edges,key=lambda x:x[2])
minimum_spnning_tree=[]
for i,j,d in sorted_edges:
if not UF.Same(i,j):
UF.Union(i,j)
minimum_spnning_tree.append((i,j,d))
return minimum_spnning_tree
def Ford_Fulkerson(self,s,t):
max_flow=0
residual_graph=[defaultdict(int) for i in range(self.V)]
if self.weighted:
for i,j,d in self.edges:
if not d:
continue
residual_graph[i][j]+=d
if not self.directed:
residual_graph[j][i]+=d
else:
for i,j in self.edges:
residual_graph[i][j]+=1
if not self.directed:
residual_graph[j][i]+=1
while True:
parents=[None]*self.V
parents[s]=s
seen=[False]*self.V
seen[s]=True
queue=deque([s])
while queue:
x=queue.popleft()
for y in residual_graph[x].keys():
if not seen[y]:
seen[y]=True
queue.append(y)
parents[y]=x
if y==t:
tt=t
while tt!=s:
residual_graph[parents[tt]][tt]-=1
residual_graph[tt][parents[tt]]+=1
if not residual_graph[parents[tt]][tt]:
residual_graph[parents[tt]].pop(tt)
tt=parents[tt]
max_flow+=1
break
else:
continue
break
else:
break
return max_flow
def BFS(self,s):
seen=[False]*self.V
seen[s]=True
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
return
def DFS(self,s):
seen=[False]*self.V
finished=[False]*self.V
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
elif not finished[x]:
finished[x]=True
return
t=int(readline())
for _ in range(t):
N,M=map(int,readline().split())
edges=[]
v=list(map(int,readline().split()))
t=list(map(int,readline().split()))
for _ in range(M):
a,b=map(int,readline().split())
a-=1;b-=1
edges.append((a,b))
if sum(v)%2!=sum(t)%2:
ans='NO'
else:
G=Graph(N,edges=edges)
bg=G.AP_DFS(bipartite_graph=True)[0]
if not bg:
ans='YES'
else:
v=sum(v[a] for a in bg[0])-sum(v[b] for b in bg[1])
t=sum(t[a] for a in bg[0])-sum(t[b] for b in bg[1])
if v==t:
ans='YES'
else:
ans='NO'
print(ans) | 1624026900 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second | ["2\n2 3", "1\n2"] | dd26f45869b73137e5e5cc6820cdc2e4 | null | Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol. | In the first line print single integer k — the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one. | The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters — string s. The third line contains m lowercase English letters — string t. | standard output | standard input | PyPy 2 | Python | 1,000 | train_012.jsonl | 06d50f5fefee68e61096267cc049b0c9 | 256 megabytes | ["3 5\nabc\nxaybz", "4 10\nabcd\nebceabazcd"] | PASSED | n, m = map(int, raw_input().split())
s = raw_input()
t = raw_input()
ans = float('inf')
pos = []
for i in xrange(m-n+1):
count = 0
tempPos = []
for j in xrange(n):
if t[i+j] != s[j]:
count += 1
tempPos.append(j+1)
if count < ans:
ans = count
pos = tempPos
print ans
for i in pos:
print i, | 1499011500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["3"] | 5ea0351ac9f949dedae1928bfb7ebffa | null | Let's introduce the designation , where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aсba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w. | In a single line print an integer — the largest number p. If the required value of p doesn't exist, print 0. | The first line contains two integers b, d (1 ≤ b, d ≤ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100. | standard output | standard input | Python 2 | Python | 2,000 | train_028.jsonl | 9a74738784a0838c806bfede442df63f | 256 megabytes | ["10 3\nabab\nbab"] | PASSED |
from itertools import repeat,chain
from fractions import gcd
def eternal(c,d, n = None):
while True:
yield chain.from_iterable(repeat(c,d))
def cyclic_array(arr):
n = len(arr)
def cyclar(i):
return arr[i % n]
return cyclar
def find_repeat(enum,q_r_gen, a_n):
ac_count =0
a_count = 0
remainders ={}
tempq=''
tempa = ''
for q,q_r in enumerate(q_r_gen):
tempq=''
for c_c in q_r:
tempq= tempq +c_c
for a_count,a_c in enum:
if a_c == c_c:
tempa = tempa +a_c
ac_count+=1
break
#print len(tempa),len(tempq)
if (a_count % a_n) in remainders:
#print tempq[:20],tempa[:20]
break
else:
remainders[(a_count % a_n)]=(a_count,q)
repeat_length = a_count - remainders[a_count % a_n][0]
q_count = q-remainders[a_count % a_n][1]
return remainders[a_count % a_n][0],repeat_length,q_count
def main(a,b,c,d):
#print a, c
a_r = chain.from_iterable(repeat(a,b))
#print "".join(chain.from_iterable(repeat(a,b)))
enum =enumerate(a_r)
q_r_gen = eternal(c,d)
i = 0
flag = True
if len(a) > len(c)*d:
multiplier =1
start,repeat_length,q_count = find_repeat(enum,q_r_gen, len(a))
else:
multiplier =((len(c)*d)//len(a))+1
#print "Multi",multiplier
enum2 = enumerate(chain.from_iterable(repeat(a*multiplier,b//multiplier)))
start,repeat_length,q_count =find_repeat(enum2,q_r_gen, multiplier*len(a))
if repeat_length >0:
advance_n = (((len(a)*multiplier)*(b//multiplier))//repeat_length)-1
advance = repeat_length * advance_n
sofar = q_count * advance_n
else:
advance_n =0
advance = 0
sofar = 0
#print advance_n,advance, repeat_length, len(a)*b, sofar , len(c)*d
ca = cyclic_array(a)
ra = iter(range(advance,len(a)*b))
ac_count =0
for q_r in q_r_gen:
for i,c_c in enumerate(q_r):
flag = False
for a_count in ra:
#print a_count
if ca(a_count) == c_c:
ac_count+=1
flag = True
break
if not flag:
break
print sofar + (ac_count // (len(c)*d))
if __name__ == "__main__":
b,d = [int(s) for s in (raw_input()).split()]
a = raw_input()
c = raw_input()
aset = set(a)
cset = set(c)
if cset.difference(aset):
print 0
elif a == c:
print b // d
else:
main(a,b,c,d)
| 1370619000 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["Bob\nAlice\nAlice"] | 4c5187193cf7f2d2721cedbb15b2a1c3 | NoteIn the first testcase, in her turn, Alice can only choose $$$i = 2$$$, making the array equal $$$[1, 0]$$$. Then Bob, in his turn, will also choose $$$i = 2$$$ and make the array equal $$$[0, 0]$$$. As $$$a_1 = 0$$$, Alice loses.In the second testcase, once again, players can only choose $$$i = 2$$$. Then the array will change as follows: $$$[2, 1] \to [1, 1] \to [1, 0] \to [0, 0]$$$, and Bob loses.In the third testcase, we can show that Alice has a winning strategy. | Alice and Bob are playing a game on an array $$$a$$$ of $$$n$$$ positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If $$$a_1 = 0$$$, the player loses the game, otherwise: Player chooses some $$$i$$$ with $$$2\le i \le n$$$. Then player decreases the value of $$$a_1$$$ by $$$1$$$ and swaps $$$a_1$$$ with $$$a_i$$$. Determine the winner of the game if both players play optimally. | For each test case, if Alice will win the game, output "Alice". Otherwise, output "Bob". You can output each letter in any case. For example, "alIcE", "Alice", "alice" will all be considered identical. | The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$ — the elements of the array $$$a$$$. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,200 | train_087.jsonl | 9f687f7bb394d63b4df6f246c7bbbc5f | 256 megabytes | ["3\n\n2\n\n1 1\n\n2\n\n2 1\n\n3\n\n5 4 4"] | PASSED | for i in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
d=min(l)
if d==l[0]:
print("Bob")
else:
print("Alice") | 1667572500 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["1", "8"] | 3b7cafc280a9b0dba567863c80b978b0 | NoteIn the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets. | You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: All cells in a set have the same color. Every two cells in a set share row or column. | Output single integer — the number of non-empty sets from the problem description. | The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly. The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black. | standard output | standard input | PyPy 2 | Python | 1,300 | train_015.jsonl | 0a5a4486701e3377db660db3213414ac | 256 megabytes | ["1 1\n0", "2 3\n1 0 1\n0 1 0"] | PASSED | n,m = map(int, raw_input().split(" "))
a =[]
for i in range(n):
b = map(int, raw_input().split(" "))
a.append(b)
ans=0
for i in range(n):
d={1:0, 0:0}
for j in a[i]:
if j==0:
d[0]+=1
else:
d[1]+=1
ans+=pow(2,d[0])-1
ans+=pow(2,d[1])-1
c =[[] for i in range(m)]
for i in range(m):
for j in range(n):
c[i].append(a[j][i])
for i in range(m):
d={1:0, 0:0}
for j in c[i]:
if j==0:
d[0]+=1
else:
d[1]+=1
ans+=pow(2,d[0])-1
ans+=pow(2,d[1])-1
ans-=(n*m)
print ans | 1503592500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1227\n-1\n17703\n2237344218521717191"] | 8f00837e04627e445dfb8b6cd0216640 | NoteIn the first test case of the example, $$$1227$$$ is already an ebne number (as $$$1 + 2 + 2 + 7 = 12$$$, $$$12$$$ is divisible by $$$2$$$, while in the same time, $$$1227$$$ is not divisible by $$$2$$$) so we don't need to delete any digits. Answers such as $$$127$$$ and $$$17$$$ will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, $$$1$$$ digit such as $$$17703$$$, $$$77013$$$ or $$$17013$$$. Answers such as $$$1701$$$ or $$$770$$$ will not be accepted as they are not ebne numbers. Answer $$$013$$$ will not be accepted as it contains leading zeroes.Explanation: $$$1 + 7 + 7 + 0 + 3 = 18$$$. As $$$18$$$ is divisible by $$$2$$$ while $$$17703$$$ is not divisible by $$$2$$$, we can see that $$$17703$$$ is an ebne number. Same with $$$77013$$$ and $$$17013$$$; $$$1 + 7 + 0 + 1 = 9$$$. Because $$$9$$$ is not divisible by $$$2$$$, $$$1701$$$ is not an ebne number; $$$7 + 7 + 0 = 14$$$. This time, $$$14$$$ is divisible by $$$2$$$ but $$$770$$$ is also divisible by $$$2$$$, therefore, $$$770$$$ is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 $$$\rightarrow$$$ 22237320442418521717191 (delete the last digit). | Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by $$$2$$$ but the number itself is not divisible by $$$2$$$. For example, $$$13$$$, $$$1227$$$, $$$185217$$$ are ebne numbers, while $$$12$$$, $$$2$$$, $$$177013$$$, $$$265918$$$ are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer $$$s$$$, consisting of $$$n$$$ digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between $$$0$$$ (do not delete any digits at all) and $$$n-1$$$.For example, if you are given $$$s=$$$222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 $$$\rightarrow$$$ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to $$$70$$$ and is divisible by $$$2$$$, but number itself is not divisible by $$$2$$$: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it. | For each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits. | The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3000$$$) — the number of digits in the original number. The second line of each test case contains a non-negative integer number $$$s$$$, consisting of $$$n$$$ digits. It is guaranteed that $$$s$$$ does not contain leading zeros and the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$. | standard output | standard input | Python 3 | Python | 900 | train_005.jsonl | 43ca9ecef047c647f9aaa3a015cbf9dc | 256 megabytes | ["4\n4\n1227\n1\n0\n6\n177013\n24\n222373204424185217171912"] | PASSED | t =int(input())
while t!=0:
t-=1
n=int(input())
s=input()
ar=[]
sar=[]
for i in s:
if i!='0':
ar.append(int(i))
sar.append(i)
if len(ar)==0 or len(ar)==1 :
print(-1)
continue
else:
tsum=sum(ar)
if tsum%2==0 and ar[len(ar)-1]%2!=0:
print("".join(sar))
elif tsum%2==0 and (ar[len(ar)-1]%2)==0:
# print(1)
while len(ar)>0 and (ar[len(ar)-1])%2==0:
#print(ar[len(ar)-1])
ar.pop()
sar.pop()
if(len(ar)==0):
print(-1)
continue
print("".join(sar))
continue
elif tsum%2!=0 and (ar[len(ar)-1]%2)==0:
for i in ar:
if(i%2==1):
ar.remove(i)
sar.remove(str(i))
break
while len(ar)>0 and (ar[len(ar)-1])%2==0:
ar.pop()
sar.pop()
if(len(ar)==0):
print(-1)
continue
print("".join(sar))
continue
elif tsum%2!=0 and (ar[len(ar)-1]%2)!=0:
if(sum(ar)%2!=0):
for i in ar:
if(i%2==1):
ar.remove(i)
sar.remove(str(i))
break
if(ar[len(ar)-1]%2==0):
print(-1)
continue
print("".join(sar))
continue
else:
print(-1)
| 1580652300 | [
"math",
"strings"
] | [
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds | ["11.084259940083", "33.121375178000"] | ae8687ed3cb5df080fb6ee79b040cef1 | NoteConsider the first sample.Adil will use the following path: .Bera will use the following path: .Adil's path will be units long, while Bera's path will be units long. | It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: Choose to stop or to continue to collect bottles. If the choice was to continue then choose some bottle and walk towards it. Pick this bottle and walk to the recycling bin. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. | Print one real number — the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. 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 . | First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≤ ax, ay, bx, by, tx, ty ≤ 109) — initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≤ n ≤ 100 000) — the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≤ xi, yi ≤ 109) — position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. | standard output | standard input | Python 3 | Python | 1,800 | train_000.jsonl | 8694d69785e15093f3cc9909d405f96b | 256 megabytes | ["3 1 1 2 0 0\n3\n1 1\n2 1\n2 3", "5 0 4 2 2 0\n5\n5 2\n3 0\n5 5\n3 5\n3 3"] | PASSED | ax,ay,bx,by,tx,ty=map(int,input().split())
n=int(input())
l=[tuple(map(int,input().split())) for _ in range(n)]
a,b=[],[]
for i in range(n):
x,y=l[i]
lt=((tx-x)*(tx-x)+(ty-y)*(ty-y))**0.5
la=((ax-x)*(ax-x)+(ay-y)*(ay-y))**0.5
lb=((bx-x)*(bx-x)+(by-y)*(by-y))**0.5
a+=[(la-lt,i)]
b+=[(lb-lt,i)]
a.sort();b.sort()
if a[0][1]==b[0][1] and n>1: ans=min(a[0][0],b[0][0],a[0][0]+b[1][0],a[1][0]+b[0][0])
else:
if a[0][1]==b[0][1]: ans=min(a[0][0],b[0][0])
else: ans=min(a[0][0],b[0][0],a[0][0]+b[0][0])
for i in range(n):
x,y=l[i]
lt=((tx-x)*(tx-x)+(ty-y)*(ty-y))**0.5
ans+=lt+lt
print(ans) | 1462984500 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["141", "25", "183"] | de6361f522936eac3d88b7268b8c2793 | NoteIn sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.In sample case two it doesn't matter whether to use autocompletion or not. | Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». | Print a single integer — the minimum number of clicks. | The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. | standard output | standard input | Python 3 | Python | 1,900 | train_035.jsonl | 55d9a0f55e02784d19864ca9f406eea2 | 256 megabytes | ["snow affects sports such as skiing, snowboarding, and snowmachine travel.\nsnowboarding is a recreational activity and olympic and paralympic sport.", "'co-co-co, codeforces?!'", "thun-thun-thunder, thunder, thunder\nthunder, thun-, thunder\nthun-thun-thunder, thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, thunder"] | PASSED | class Ddict:
def __init__(self):
self.dicts={}
def add(self,key):
d=self.dicts
for i in key:
if i not in d:
d[i]={}
d=d[i]
d[' ']=''
def find(self,key):
if key=='':
return '',''
d=self.dicts
q=[]
h=[key[0]]
for i in key:
if i not in d:
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
q.append(i)
if len(d)!=1:
h=q[:]
d=d[i]
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
words = Ddict()
ans=0
while True:
try:
x=input()
if not x:
break
except:
break
ans+=len(x)+1
ws=[[]]
for i in x:
if i in '.,?!\'- ':
if ws[-1]:
ws.append([])
else:
ws[-1].append(i)
ws=list(map(lambda e:''.join(e),ws))
for w in ws:
next_word,helped_word = words.find(w)
if next_word and next_word!=helped_word:
ans-=len(next_word)-len(helped_word)-1
words.add(w)
print(ans)
| 1519486500 | [
"trees",
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
1
] |
|
1 second | ["0\n1\n12\n499999999"] | c34db7897f051b0de2f49f2696c6ee2f | NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$. | You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$. | For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$. | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$). | standard output | standard input | Python 3 | Python | 800 | train_086.jsonl | 49df8e8d76f98d081f15aa806539cd06 | 256 megabytes | ["4\n1 1\n999999999 1000000000\n8 26\n1 999999999"] | PASSED | import os, sys
import math
from io import BytesIO, IOBase
from collections import Counter
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
x,y=map(int,input().split())
k=abs(x-y)
if k==0:
print(0)
else:
t=y//2+1
if t<x:
print(y%x)
else:
print(y%t) | 1629988500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["27", "9"] | 0cc9e1f64f615806d07e657be7386f5b | NoteIn the first sample the result equals (1 + 08) + (10 + 8) = 27.In the second sample the result equals 1 + 0 + 8 = 9. | Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him! | Print the answer to the problem modulo 109 + 7. | The first line contains two integers, n and k (0 ≤ k < n ≤ 105). The second line contains a string consisting of n digits. | standard output | standard input | Python 3 | Python | 2,200 | train_002.jsonl | fece09dfb0961b9b215cffd62afd564f | 256 megabytes | ["3 1\n108", "3 2\n108"] | PASSED | n, k = map(int, input().split())
t = list(map(int, input()))
p, d = 1, 10 ** 9 + 7
s, f = 0, [1] * n
for i in range(2, n): f[i] = (i * f[i - 1]) % d
c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d
if k:
u = [0] * (n + 1)
p = [1] * (n + 1)
for i in range(n):
u[i] = (p[i] * c(k - 1, n - 2 - i) + u[i - 1]) % d
p[i + 1] = (10 * p[i]) % d
for i in range(n):
v = u[n - 2 - i] + p[n - 1 - i] * c(k, i)
s = (s + t[i] * v) % d
else:
for i in t: s = (s * 10 + i) % d
print(s)
| 1425279600 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["1", "2", "-1"] | 9115965ff3421230eac37b22328c6153 | NoteIn the first example, the greatest common divisor is $$$1$$$ in the beginning. You can remove $$$1$$$ so that the greatest common divisor is enlarged to $$$2$$$. The answer is $$$1$$$.In the second example, the greatest common divisor is $$$3$$$ in the beginning. You can remove $$$6$$$ and $$$9$$$ so that the greatest common divisor is enlarged to $$$15$$$. There is no solution which removes only one integer. So the answer is $$$2$$$.In the third example, there is no solution to enlarge the greatest common divisor. So the answer is $$$-1$$$. | Mr. F has $$$n$$$ positive integers, $$$a_1, a_2, \ldots, a_n$$$.He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. | Print an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. You should not remove all of the integers. If there is no solution, print «-1» (without quotes). | The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the number of integers Mr. F has. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 1.5 \cdot 10^7$$$). | standard output | standard input | PyPy 2 | Python | 1,800 | train_009.jsonl | a7be496d9cfe2abb4ffed5d77715e8f0 | 256 megabytes | ["3\n1 2 4", "4\n6 9 15 30", "3\n1 1 1"] | PASSED | def gcd(a, b):
while b:
c = a%b
a = b
b = c
return a
import sys
raw_input = sys.stdin.readline
sieve = [0] * (15000001)
i = 2
while i <= 15000000:
sieve[i] = 2
i += 2
i = 3
while i < 15000000:
if sieve[i]:
i += 2
continue
sieve[i] = i
j = i*i
while j < 15000000:
if sieve[j] == 0:
sieve[j] = i
j += i
i += 2
n = int(raw_input())
l = [int(x) for x in raw_input().split()]
totalGCD = l[0]
for x in l:
totalGCD = gcd(x, totalGCD)
for i in xrange(n):
l[i] /= totalGCD
# TODO: defaultdict might be too slow?!
from collections import defaultdict
dp = defaultdict(int)
for x in l:
y = x
while y > 1:
lp = sieve[y]
dp[lp] += 1
while y % lp == 0:
y /= lp
highest = 0
for x in dp:
highest = max(highest, dp[x])
if highest == 0:
highest = -1
else:
highest = n - highest
print highest
| 1537540500 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds | ["10\n1 2 3", "99\n2 1", "-9\n3 5 6 1 9 4 10 7 8 2"] | 5ebae703049e9ab4547df87861034176 | null | Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...There are two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Initially, an $$$ans$$$ is equal to $$$0$$$ and the following operation is defined: Choose position $$$i$$$ ($$$1 \le i \le n$$$); Add $$$a_i$$$ to $$$ans$$$; If $$$b_i \neq -1$$$ then add $$$a_i$$$ to $$$a_{b_i}$$$. What is the maximum $$$ans$$$ you can get by performing the operation on each $$$i$$$ ($$$1 \le i \le n$$$) exactly once?Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them. | In the first line, print the maximum $$$ans$$$ you can get. In the second line, print the order of operations: $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$). The $$$p_i$$$ is the position which should be chosen at the $$$i$$$-th step. If there are multiple orders, print any of them. | The first line contains the integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$−10^6 \le a_i \le 10^6$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$ or $$$b_i = -1$$$). Additional constraint: it's guaranteed that for any $$$i$$$ ($$$1 \le i \le n$$$) the sequence $$$b_i, b_{b_i}, b_{b_{b_i}}, \ldots$$$ is not cyclic, in other words it will always end with $$$-1$$$. | standard output | standard input | PyPy 3 | Python | 2,000 | train_039.jsonl | d4a99228d2d306cb7e9777c1de2019dd | 256 megabytes | ["3\n1 2 3\n2 3 -1", "2\n-1 100\n2 -1", "10\n-10 -1 2 2 5 -2 -3 -4 2 -6\n-1 -1 2 2 -1 5 5 7 7 9"] | PASSED | import sys;input=sys.stdin.readline
N, = map(int, input().split())
X = [0]+list(map(int, input().split()))
Y = [0]+list(map(int, input().split()))
st = []
G = [set() for _ in range(N+1)]
for i in range(1, N+1):
if Y[i] < 0:
st.append(i)
else:
G[Y[i]].add(i)
ato = []
R = []
W = [0]*(N+1)
for s in st:
stack = [s]
vs_dfs = list()
while stack:
v = stack.pop()
vs_dfs.append(v)
for u in G[v]:
# vs.add(u)
stack.append(u)
for v in vs_dfs[::-1]:
for u in G[v]:
X[v] += max(0, X[u])
if X[v] < 0:
ato.append(v)
else:
R.append(v)
ato = ato[::-1]
print(sum(X))
print(*(R+ato))
| 1596119700 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["2 1\n3 1 2\n1 6 5 8 3 2 4 7"] | 0903a40d72c19a9d1cc1147d01ea94a7 | NoteIn the first testcase, there exists only one permutation $$$q$$$ such that each liked song is rating higher than each disliked song: song $$$1$$$ gets rating $$$2$$$ and song $$$2$$$ gets rating $$$1$$$. $$$\sum\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2$$$.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to $$$p$$$. Its cost is $$$0$$$. | Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended $$$n$$$ songs, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th song had its predicted rating equal to $$$p_i$$$, where $$$1 \le p_i \le n$$$ and every integer from $$$1$$$ to $$$n$$$ appears exactly once. In other words, $$$p$$$ is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $$$s$$$, such that $$$s_i=0$$$ means that he disliked the $$$i$$$-th song, and $$$s_i=1$$$ means that he liked it.Now the service has to re-evaluate the song ratings in such a way that: the new ratings $$$q_1, q_2, \dots, q_n$$$ still form a permutation ($$$1 \le q_i \le n$$$; each integer from $$$1$$$ to $$$n$$$ appears exactly once); every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $$$i, j$$$ such that $$$s_i=1$$$ and $$$s_j=0$$$, $$$q_i>q_j$$$ should hold). Among all valid permutations $$$q$$$ find the one that has the smallest value of $$$\sum\limits_{i=1}^n |p_i-q_i|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$.Print the permutation $$$q_1, q_2, \dots, q_n$$$. If there are multiple answers, you can print any of them. | For each testcase, print a permutation $$$q$$$ — the re-evaluated ratings of the songs. If there are multiple answers such that $$$\sum\limits_{i=1}^n |p_i-q_i|$$$ is minimum possible, you can print any of them. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of songs. The second line of each testcase contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the permutation of the predicted ratings. The third line contains a single string $$$s$$$, consisting of $$$n$$$ characters. Each character is either a $$$0$$$ or a $$$1$$$. $$$0$$$ means that Monocarp disliked the song, and $$$1$$$ means that he liked it. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,000 | train_085.jsonl | 654feabfa49f056eedf2d0f1a93f911a | 256 megabytes | ["3\n2\n1 2\n10\n3\n3 1 2\n111\n8\n2 3 1 8 5 4 7 6\n01110001"] | PASSED | t= int(input())
for i in range(t):
n= int(input())
p= [int(x) for x in input().split()]
s= [int(x) for x in input()]
l= sorted([[s[i], p[i], i] for i in range(n)])
q= [0] * n
for i in range(n):
q[l[i][2]] = i+1
print(*q)
| 1640615700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6.00000000", "6.50000000"] | 822e8f394a59329fa05c96d7fb35797e | NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5 | Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities. | Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You 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 three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate. | standard output | standard input | Python 3 | Python | 1,100 | train_016.jsonl | e1b7cfed7e781d598b5f66b0a56bf9ed | 256 megabytes | ["2 1 1\n1 5", "4 2 1\n1 4 2 3"] | PASSED | i = lambda: map(int, input().split())
n, x, y = i()
a = sorted(i())[::-1]
if x > y:
x, y = y, x
print(sum(a[:x])/x + sum(a[x:][:y])/y)
| 1480264500 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | 3fb70a77e4de4851ed93f988140df221 | null | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | standard output | standard input | Python 3 | Python | 2,000 | train_054.jsonl | 34ca44611c717c1b164a2ddb50108653 | 256 megabytes | ["ABACABA", "AAA"] | PASSED |
def z_advanced(s):
"""An advanced computation of Z-values of a string."""
Z = [0] * len(s)
Z[0] = len(s)
rt = 0
lt = 0
for k in range(1, len(s)):
if k > rt:
# If k is outside the current Z-box, do naive computation.
n = 0
while n + k < len(s) and s[n] == s[n + k]:
n += 1
Z[k] = n
if n > 0:
lt = k
rt = k + n - 1
else:
# If k is inside the current Z-box, consider two cases.
p = k - lt # Pair index.
right_part_len = rt - k + 1
if Z[p] < right_part_len:
Z[k] = Z[p]
else:
i = rt + 1
while i < len(s) and s[i] == s[i - k]:
i += 1
Z[k] = i - k
lt = k
rt = i - 1
return Z
def kmptab(s):
tab = [0]*len(s)
i = 1
j = 0
while i < len(s):
if s[i] == s[j]:
tab[i] = j + 1
i += 1
j += 1
else:
if j != 0:
j = tab[j-1]
else:
i += 1
return tab
if __name__ == '__main__':
s = input()
tab = kmptab(s)
my_set = set()
i = len(s)
while i != 0:
my_set.add(i)
i = tab[i-1]
V = []
dict = {}
for i in my_set:
V.append(i)
dict[i] = 0
Z = z_advanced(s)
v = []
V.sort()
my_tab = [0]*(len(s)+1)
# print(Z)
for i in Z:
my_tab[i] += 1
somme = 0
# print(my_tab)
for i in range(len(my_tab)-1, -1, -1):
my_tab[i] += somme
somme = my_tab[i]
# print(my_tab)
for i in dict:
dict[i] = my_tab[i]
v.append((dict[i], i))
v.sort(key=lambda tup: tup[1])
print(len(v))
for i in v:
print(str(i[1]) + " " + str(i[0]))
| 1400167800 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["YES\n1 0\n2 3\n4 1", "NO"] | 5c026adda2ae3d7b707d5054bd84db3f | NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below: In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$. | Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them. | If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower). | The single line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1\le n, m \le 10^9$$$, $$$2 \le k \le 10^9$$$). | standard output | standard input | PyPy 3 | Python | 1,800 | train_005.jsonl | 3ab5974739b59a2f7707451462505fae | 256 megabytes | ["4 3 3", "4 4 7"] | PASSED | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,m,k=map(int,input().split())
g=math.gcd(n*m,k)
d=(n*m)//g
f=k//g
#print(d,f)
if d%f!=0 and f!=2:
print("NO")
else:
j=1
l=1
copy1,copy2=n,m
ch=1
if k%2==0:
k//=2
ch=0
while k%2==0:
k//=2
if n%2==0:
n//=2
else:
m//=2
for i in range (3,int(math.sqrt(k))+1,2):
while k%i==0:
k//=i
if n%i==0:
n//=i
else:
m//=i
if k>2:
if n%k==0:
n//=k
else:
m//=k
if ch==1:
if n*2<=copy1:
n*=2
else:
m*=2
print("YES")
print("0 0")
print(0,m)
print(n,0) | 1537707900 | [
"number theory",
"geometry"
] | [
0,
1,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["-2", "10"] | a12103bd632fa73a7faab71df3fd0164 | NoteNote that the answer to the problem can be negative.The GCD(x1, x2, ..., xk) is the maximum positive integer that divides each xi. | You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum , where function f(s) is determined as follows: f(1) = 0; Let's assume that p is the minimum prime divisor of s. If p is a good prime, then , otherwise . You are allowed to perform an arbitrary (probably zero) number of operations to improve array a. The operation of improvement is the following sequence of actions: Choose some number r (1 ≤ r ≤ n) and calculate the value g = GCD(a[1], a[2], ..., a[r]). Apply the assignments: , , ..., . What is the maximum beauty of the array you can get? | Print a single integer — the answer to the problem. | The first line contains two integers n and m (1 ≤ n, m ≤ 5000) showing how many numbers are in the array and how many bad prime numbers there are. The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — array a. The third line contains m space-separated integers b1, b2, ..., bm (2 ≤ b1 < b2 < ... < bm ≤ 109) — the set of bad prime numbers. | standard output | standard input | Python 2 | Python | 1,800 | train_040.jsonl | 360d4e4cbb892f4bfead7c8cae357d0d | 256 megabytes | ["5 2\n4 20 34 10 10\n2 5", "4 5\n2 4 8 16\n3 5 7 11 17"] | PASSED | import fractions
n, m = map(int, raw_input().split())
primes_cache = {}
primes = []
def lowest_prime_divisor(x, sorted_primes_to_check=primes, cache=primes_cache):
if x in cache:
return cache[x]
for i in sorted_primes_to_check:
if i * i > x:
cache[x] = x
return x
elif not x % i:
cache[x] = i
return i
cache[x] = x
return x
for i in range(2, 100000):
if lowest_prime_divisor(i, primes) == i:
primes.append(i)
def beauty(x, bad_primes):
if (x == 1):
return 0
else:
p = lowest_prime_divisor(x)
if p in bad_primes:
return beauty(x/p, b) - 1
else:
return beauty(x/p, b) + 1
a = map(int, raw_input().split())
b = set(map(int, raw_input().split()))
gcds = [None] * (n+20)
lastgcd = None
for i in range(n):
if i == 0:
gcds[i] = a[i]
else:
gcds[i] = fractions.gcd(gcds[i-1], a[i])
dividedBy = 1
for i in reversed(range(n)):
gcds[i] = gcds[i] / dividedBy
if beauty(gcds[i], b) < 0:
dividedBy *= gcds[i]
a[i] /= dividedBy
print sum(map(lambda x: beauty(x, b), a))
| 1394983800 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["2 4\n1 4\n3 4\n3 1\n3 2", "-1"] | 1a9968052a363f04380d1177c764717b | null | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct. | If Vladislav has made a mistake and such graph doesn't exist, print - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them. | The first line of the input contains two integers n and m () — the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero. | standard output | standard input | Python 3 | Python | 1,700 | train_056.jsonl | 9b5f207249c2428d5556fcf64cc48092 | 256 megabytes | ["4 5\n2 1\n3 1\n4 0\n1 1\n5 0", "3 3\n1 0\n2 1\n3 1"] | PASSED | import sys
from operator import itemgetter
lines = sys.stdin.readlines()
n, m = map(int, lines[0].split(' '))
def build_edge(i, row):
parts = row.split(' ')
return (int(parts[0]), int(parts[1]), i)
def edge_key(a):
return (a[0], -a[1])
edges = [build_edge(i, row) for i, row in enumerate(lines[1:])]
edges = sorted(edges, key=edge_key)
x, y = 1, 2
vertex = 1
color = [0 for x in range(n)]
color[0] = 1 # root of tree
ans = []
for weight, used, index in edges:
if used == 1:
color[vertex] = 1
ans.append((0, vertex, index))
vertex += 1
else:
if color[x] != 1 or color[y] != 1:
print(-1)
exit(0)
ans.append((x,y,index))
x += 1
if x == y:
x = 1
y += 1
ans = sorted(ans, key=itemgetter(2))
for edge in ans:
print("%s %s" % (edge[0]+1, edge[1]+1))
| 1449677100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["2", "3"] | 40a965a28e38bad3aff9c58bdeeeb8f6 | null | Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version. | Print one number – the brain latency. | The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b). | standard output | standard input | Python 3 | Python | 1,500 | train_004.jsonl | 5000894a71456b418e95fea3047708d8 | 256 megabytes | ["4 3\n1 2\n1 3\n1 4", "5 4\n1 2\n2 3\n3 4\n3 5"] | PASSED | # itne me hi thakk gaye?
def bfs(x, g):
n, q = len(g), [x]
dist = [0 if y == x else -1 for y in range(n)]
i = 0
while i < len(q):
v = q[i]
i += 1
for to in g[v]:
if dist[to] < 0:
dist[to] = dist[v] + 1
q.append(to)
return (q[-1], dist[q[-1]])
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(lambda x: int(x) - 1, input().split())
g[a].append(b)
g[b].append(a)
print(bfs(bfs(0, g)[0], g)[1]) | 1468137600 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["5\n1 2 4 3 0", "6\n3 9 2 9 8 0"] | 5a3bbc6668268dabb49316a1c8d4ea8c | NoteFor the first case, the prefix products of this sequence modulo m are [1, 2, 3, 4, 0].For the second case, the prefix products of this sequence modulo m are [3, 7, 4, 6, 8, 0]. | You are given an integer m, and a list of n distinct integers between 0 and m - 1.You would like to construct a sequence satisfying the properties: Each element is an integer between 0 and m - 1, inclusive. All prefix products of the sequence modulo m are distinct. No prefix product modulo m appears as an element of the input list. The length of the sequence is maximized. Construct any sequence satisfying the properties above. | On the first line, print the number k, denoting the length of your sequence. On the second line, print k space separated integers, denoting your sequence. | The first line of input contains two integers n and m (0 ≤ n < m ≤ 200 000) — the number of forbidden prefix products and the modulus. If n is non-zero, the next line of input contains n distinct integers between 0 and m - 1, the forbidden prefix products. If n is zero, this line doesn't exist. | standard output | standard input | PyPy 3 | Python | 2,300 | train_051.jsonl | 25d0761f13a23b6619cb8e739dd2595c | 256 megabytes | ["0 5", "3 10\n2 9 1"] | PASSED | import math
def gcdExtended(a, b):
# Base Case
if a == 0 :
return b, 0, 1
gcd, x1, y1 = gcdExtended(b%a, a)
# Update x and y using results of recursive
# call
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
def rev_elem(x, m):
return (gcdExtended(x, m)[1] % m + m) % m
n, m = map(int, input().split())
a = []
if n > 0:
a = [int(i) for i in input().split()]
banned = [False] * (m + 5)
for i in a:
banned[i] = True
cycle = [[] for i in range(m + 5)]
d, dp, p = [], [], []
for i in range(m):
cycle[math.gcd(m, i)].append(i)
cycle = [[i for i in j if not banned[i]] for j in cycle]
d = [i for i in range(1, m + 1) if m % i == 0]
dp = [len(cycle[i]) for i in d]
p = [-1 for i in d]
ans, lst = -1, -1
for i in range(len(d)):
if dp[i] > ans:
ans, lst = dp[i], i
for j in range(i + 1, len(d)):
if d[j] % d[i] != 0 or dp[j] > dp[i] + len(cycle[d[j]]):
continue
dp[j] = dp[i] + len(cycle[d[j]])
p[j] = i
print(ans)
pos, dpos, pref = [], [], []
cur = lst
while cur != -1:
dpos.append(d[cur])
cur = p[cur]
dpos.reverse()
for i in dpos:
pref += cycle[i]
cur = 1
for i in pref:
ad = 1
if math.gcd(i, m) != math.gcd(cur, m):
ad = ((cur * math.gcd(i, m) // math.gcd(cur, math.gcd(i, m))) // cur) % m
ncur = (cur * ad) % m
ad *= i // math.gcd(ncur, m) * (rev_elem(ncur // math.gcd(ncur, m), m // math.gcd(ncur, m)))
ad %= m
cur = (cur * ad) % m
pos.append(ad)
print(*pos) | 1492356900 | [
"number theory",
"math",
"graphs"
] | [
0,
0,
1,
1,
1,
0,
0,
0
] |
|
2 seconds | ["NO\nYES\nYES"] | 044c2a3bafe4f47036ee81f2e40f639a | NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$. | You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)? | For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$. | standard output | standard input | Python 3 | Python | 800 | train_106.jsonl | 6aec5e0fe0295869b8b1a0965ef998bb | 256 megabytes | ["3\n5 3\n2 3 2 5 4\n3 4\n2 4 4\n5 4\n2 1 5 3 6"] | PASSED | for t in range(int(input())):
n,d=map(int,input().split())
lst=sorted(map(int,input().split()))
print ("YES" if min(lst[0] + lst[1], lst[-1]) <=d else "NO")
| 1610634900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1 2 0", "43 42 41 1337 1336", "4 3 2 1 2"] | 48c8ce45ab38a382dc52db1e59be234f | null | You are given a directed acyclic graph (a directed graph that does not contain cycles) of $$$n$$$ vertices and $$$m$$$ arcs. The $$$i$$$-th arc leads from the vertex $$$x_i$$$ to the vertex $$$y_i$$$ and has the weight $$$w_i$$$.Your task is to select an integer $$$a_v$$$ for each vertex $$$v$$$, and then write a number $$$b_i$$$ on each arcs $$$i$$$ such that $$$b_i = a_{x_i} - a_{y_i}$$$. You must select the numbers so that: all $$$b_i$$$ are positive; the value of the expression $$$\sum \limits_{i = 1}^{m} w_i b_i$$$ is the lowest possible. It can be shown that for any directed acyclic graph with non-negative $$$w_i$$$, such a way to choose numbers exists. | Print $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_v \le 10^9$$$), which must be written on the vertices so that all $$$b_i$$$ are positive, and the value of the expression $$$\sum \limits_{i = 1}^{m} w_i b_i$$$ is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints $$$0 \le a_v \le 10^9$$$. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 18$$$; $$$0 \le m \le \dfrac{n(n - 1)}{2}$$$). Then $$$m$$$ lines follow, the $$$i$$$-th of them contains three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$1 \le w_i \le 10^5$$$, $$$x_i \ne y_i$$$) — the description of the $$$i$$$-th arc. It is guaranteed that the lines describe $$$m$$$ arcs of a directed acyclic graph without multiple arcs between the same pair of vertices. | standard output | standard input | PyPy 3 | Python | 2,600 | train_047.jsonl | c4e0a7fa0d9ff0c6153f616078f138bb | 1024 megabytes | ["3 2\n2 1 4\n1 3 2", "5 4\n1 2 1\n2 3 1\n1 3 6\n4 5 8", "5 5\n1 2 1\n2 3 1\n3 4 1\n1 5 1\n5 4 10"] | PASSED | from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
forward = [to, cap, cost, None]
backward = forward[3] = [fr, 0, -cost, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [None]*N
d0 = [INF]*N
dist = [INF]*N
while f:
dist[:] = d0
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
r0 = dist[v] + H[v]
for e in G[v]:
w, cap, cost, _ = e
if cap > 0 and r0 + cost - H[w] < dist[w]:
dist[w] = r = r0 + cost - H[w]
prv_v[w] = v; prv_e[w] = e
heappush(que, (r, w))
if dist[t] == INF:
return None
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, prv_e[v][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = prv_e[v]
e[1] -= d
e[3][1] += d
v = prv_v[v]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
n,m = map(int,input().split())
G = MinCostFlow(n+2)
coef = [0 for i in range(n)]
edge = []
for _ in range(m):
x,y,b = map(int,input().split())
G.add_edge(y,x,10**18,-1)
coef[x-1] += b
coef[y-1] -= b
edge.append((x,y))
s = 0
for i in range(n):
if coef[i]<0:
G.add_edge(0,i+1,-coef[i],0)
s -= coef[i]
elif coef[i]>0:
G.add_edge(i+1,n+1,coef[i],0)
#G.add_edge(0,n+1,10**18,0)
f = G.flow(0,n+1,s)
#print(-f)
Edge = [[] for i in range(n)]
use = [False]*m
uf = UnionFindVerSize(n)
for i in range(m):
u,v = edge[i]
for e in G.G[u]:
to = e[0]
if to==v and e[1]:
Edge[v-1].append((u-1,1))
Edge[u-1].append((v-1,-1))
use[i] = True
uf.unite(u-1,v-1)
edge = [(edge[i][0],edge[i][1]) for i in range(m) if not use[i]]
for u,v in edge:
if not uf.is_same_group(u-1,v-1):
Edge[v-1].append((u-1,1))
Edge[u-1].append((v-1,-1))
uf.unite(u-1,v-1)
used_1 = [False]*n
used_2 = [False]*n
lazy = [0 for i in range(n)]
a = [0 for i in range(n)]
def dfs(v,pv):
lazy[v] = min(lazy[v],a[v])
for nv,c in Edge[v]:
if not used_1[nv]:
used_1[nv] = True
a[nv] = a[v] + c
dfs(nv,v)
lazy[v] = min(lazy[v],lazy[nv])
def add(v,pv,ff):
a[v] += ff
for nv,c in Edge[v]:
if not used_2[nv]:
used_2[nv] = True
add(nv,v,ff)
for i in range(n):
if not used_1[i]:
used_1[i] = True
dfs(i,-1)
used_2[i] = True
add(i,-1,-lazy[i]+1)
#print(used_1)
#print(lazy)
print(*a)
| 1602407100 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n2\n-1\n1", "0\n1\n0\n-1", "-1\n-1\n-1", "-1"] | 883f728327aea19993089a65d452b79f | null | Why I have to finish so many assignments???Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment (lower value means more important) so he can decide which he needs to spend more time on.After a few days, Jamie finds out the list is too large that he can't even manage the list by himself! As you are a good friend of Jamie, help him write a program to support the following operations on the to-do list: set ai xi — Add assignment ai to the to-do list if it is not present, and set its priority to xi. If assignment ai is already in the to-do list, its priority is changed to xi. remove ai — Remove assignment ai from the to-do list if it is present in it. query ai — Output the number of assignments that are more important (have a smaller priority value) than assignment ai, so Jamie can decide a better schedule. Output - 1 if ai is not in the to-do list. undo di — Undo all changes that have been made in the previous di days (not including the day of this operation) At day 0, the to-do list is empty. In each of the following q days, Jamie will do exactly one out of the four operations. If the operation is a query, you should output the result of the query before proceeding to the next day, or poor Jamie cannot make appropriate decisions. | For each query operation, output a single integer — the number of assignments that have a priority lower than assignment ai, or - 1 if ai is not in the to-do list. | The first line consists of a single integer q (1 ≤ q ≤ 105) — the number of operations. The following q lines consists of the description of the operations. The i-th line consists of the operation that Jamie has done in the i-th day. The query has the following format: The first word in the line indicates the type of operation. It must be one of the following four: set, remove, query, undo. If it is a set operation, a string ai and an integer xi follows (1 ≤ xi ≤ 109). ai is the assignment that need to be set to priority xi. If it is a remove operation, a string ai follows. ai is the assignment that need to be removed. If it is a query operation, a string ai follows. ai is the assignment that needs to be queried. If it is a undo operation, an integer di follows (0 ≤ di < i). di is the number of days that changes needed to be undone. All assignment names ai only consists of lowercase English letters and have a length 1 ≤ |ai| ≤ 15. It is guaranteed that the last operation is a query operation. | standard output | standard input | PyPy 2 | Python | 2,200 | train_044.jsonl | 932ccde0446ccee0b75faadf77810094 | 512 megabytes | ["8\nset chemlabreport 1\nset physicsexercise 2\nset chinesemockexam 3\nquery physicsexercise\nquery chinesemockexam\nremove physicsexercise\nquery physicsexercise\nquery chinesemockexam", "8\nset physicsexercise 2\nset chinesemockexam 3\nset physicsexercise 1\nquery physicsexercise\nquery chinesemockexam\nundo 4\nquery physicsexercise\nquery chinesemockexam", "5\nquery economicsessay\nremove economicsessay\nquery economicsessay\nundo 2\nquery economicsessay", "5\nset economicsessay 1\nremove economicsessay\nundo 1\nundo 1\nquery economicsessay"] | PASSED | import sys, os, __pypy__
from collections import defaultdict
from cStringIO import StringIO
from io import IOBase
range = xrange
input = raw_input
L = []
R = []
A = [0]
__pypy__.resizelist_hint(L, 50*10**5)
__pypy__.resizelist_hint(R, 50*10**5)
__pypy__.resizelist_hint(A, 50*10**5)
def create():
L.append(-1)
R.append(-1)
A.append(0)
return len(L) - 1
def copy(ind):
L.append(L[ind])
R.append(R[ind])
A[-1] = A[ind]
A.append(0)
return len(L) - 1
def adder(i, n, ind, x):
ind0 = ind = copy(ind) if ind >= 0 else create()
while n != 1:
A[ind] += x
n = n >> 1
if i < n:
L[ind] = ind = copy(L[ind]) if L[ind] >= 0 else create()
else:
R[ind] = ind = copy(R[ind]) if R[ind] >= 0 else create()
i -= n
A[ind] += x
return ind0
def getter(l, r, n, ind):
ans = 0
while ind >= 0 and 0 < r and l < n:
if l <= 0 and r >= n:
ans += A[ind]
break
n = n >> 1
ans += getter(l - n, r - n, n, R[ind])
ind = L[ind]
return ans
def getteri(i, n, ind):
ans = 0
while ind >= 0:
if n == 1:
return A[ind]
n = n >> 1
if i < n:
ind = L[ind]
else:
i -= n
ind = R[ind]
return 0
mapper = {'set':0, 'remove':1, 'query':2, 'undo':3}
N = 1 << 30
M = 1 << 17
def main():
curbucket = -1
curprio = -1
Tbucket = [curbucket]
Tprio = [curprio]
identifier = defaultdict(lambda: len(identifier))
q = int(input())
for curd in range(q):
inp = sys.stdin.readline().split(); ii = 0
cas = mapper[inp[ii]]; ii += 1
if cas == 0:
aind = identifier[inp[ii]]; ii += 1
new_prio = int(inp[ii]); ii += 1
prio = getteri(aind, M, curprio)
curprio = adder(aind, M, curprio, new_prio - prio)
if prio:
curbucket = adder(prio, N, curbucket, -1)
if new_prio:
curbucket = adder(new_prio, N, curbucket, 1)
elif cas == 1:
aind = identifier[inp[ii]]; ii += 1
prio = getteri(aind, M, curprio)
if prio:
curbucket = adder(prio, N, curbucket, -1)
curprio = adder(aind, M, curprio, -prio)
elif cas == 2:
aind = identifier[inp[ii]]; ii += 1
prio = getteri(aind, M, curprio)
ans = getter(0, prio, N, curbucket) if prio else -1
os.write(1, str(ans) + '\n')
else: # cas == 3
d = int(inp[ii]); ii += 1
curbucket = Tbucket[curd - d]
curprio = Tprio[curd - d]
Tbucket.append(curbucket)
Tprio.append(curprio)
# region fastio
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| 1516372500 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds | ["500000.000000000000000000000000000000", "400.000000000000000000000000000000"] | 7de7e7983909d7a8f51fee4fa9ede838 | NoteIn the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000.In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. | n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed.You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed.The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. | Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if . | The first line contains two integers n and s (2 ≤ n ≤ 105, 2 ≤ s ≤ 106) — the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≤ vi < s, 1 ≤ ti ≤ 2) — the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. | standard output | standard input | Python 3 | Python | 2,500 | train_039.jsonl | a42d6d5c84b635e9620546ca9fdef8de | 256 megabytes | ["2 999\n400000 1 2\n500000 1 1", "2 1000\n400000 500 1\n600000 500 2"] | PASSED | import math
leftpeople = set()
rightpeople = set()
n, vl = map(int, input().split())
def leftinterval(x0, v0, t):
if x0 / v0 <= t:
return (0, 10**6)
if x0 / (vl + v0) > t:
return (-1, -2)
leftbound = x0
rightbound = (vl * vl - v0 * v0) * t + x0 * v0
rightbound /= vl
rightbound = int(rightbound)
if rightbound > 10**6:
rightbound = 10**6
return (leftbound, rightbound)
def rightinterval(x0, v0, t):
if (10**6 - x0) / v0 <= t:
return (0, 10**6)
if (10**6 - x0) / (v0 + vl) > t:
return (-1, -2)
rightbound = x0
leftbound = v0 * x0 + (10**6) * (vl - v0) - t * (vl * vl - v0 * v0)
leftbound /= vl
leftbound = math.ceil(leftbound)
if(leftbound < 0):
leftbound = 0
return (leftbound, rightbound)
def check(t):
events = []
for item in leftpeople:
temp = leftinterval(item[0], item[1], t)
if(temp[0] > temp[1]):
continue
events.append((temp[0], 0, 0))
events.append((temp[1], 1, 0))
if(temp[1] - temp[0] == 10**6):
break
for item in rightpeople:
temp = rightinterval(item[0], item[1], t)
if(temp[0] > temp[1]):
continue
events.append((temp[0], 0, 1))
events.append((temp[1], 1, 1))
if(temp[1] - temp[0] == 10**6):
break
events.sort()
opened = [0, 0]
for item in events:
color = item[2]
action = item[1]
if action == 0:
if opened[(color + 1) % 2] > 0:
return True
opened[color] += 1
else:
opened[color] -= 1
return False
for i in range(n):
a, b, c = map(int, input().split())
if c == 1:
leftpeople.add((a, b))
if c == 2:
rightpeople.add((a, b))
l = 0
r = 1e9
for i in range(50):
m = (l + r) / 2
if(check(m)):
r = m
else:
l = m
print(m)
| 1500906900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"] | 12218097cf5c826d83ab11e5b049999f | null | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. | If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). | The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. | standard output | standard input | Python 3 | Python | 1,600 | train_006.jsonl | 985dff6833c2e9ba3cd6fee94083193f | 256 megabytes | ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"] | PASSED | def go_through(given_char):
global order
global freq
global orders
if given_char in orders:
while orders[given_char]:
next_letter = orders[given_char].pop()
freq[next_letter] = freq[next_letter] - 1
go_through(next_letter)
if given_char not in order:
order.append(given_char)
num_names = int(input())
names = []
for _ in range(num_names):
curr_name = input()
names.append(curr_name)
prev_name = names[0]
possible = True
orders = {}
freq = {}
change_letters = set()
freq[prev_name[0]] = 0
for index in range(1, len(names)):
name = names[index]
char_index = 0
while char_index < len(name) and char_index < len(prev_name) and (name[char_index] == prev_name[char_index]):
# char at index match prev
# don't go over length of curr word
char_index += 1
# we have either surpassed one of words or found a non-matching character
if char_index < len(name) and char_index < len(prev_name):
# We haven't surpassed either word; found a non-matching character
previous_char = prev_name[char_index]
curr_char = name[char_index]
if previous_char in orders:
orders[previous_char].add(curr_char)
else:
orders[previous_char] = {curr_char}
if curr_char in freq:
freq[curr_char] = freq[curr_char] + 1
else:
freq[curr_char] = 1
change_letters.add(previous_char)
change_letters.add(curr_char)
prev_name = name
elif len(prev_name) > len(name):
# Previous longer and matched
possible = False
break
if not possible:
print("Impossible")
else:
order = []
dependent_chars = list(orders.keys())
for char in dependent_chars:
curr_freq = 0
if char in freq:
curr_freq = freq[char]
if curr_freq <= 0:
go_through(char)
if len(order) is not len(change_letters):
print("Impossible")
else:
order = list(reversed(order))
for char in range(ord('a'), ord('z') + 1):
character = chr(char)
if character not in order:
order.append(character)
for char in order:
print(char, end="")
| 1422894600 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["0", "2", "1"] | acd48e32c96a10cc0d4161225407bf67 | NoteFor each example you have a picture which illustrates it.The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.Test 1We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything. Test 2We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements. Test 3There are several possible solutions. One of them is illustrated below.Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions. | Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2). Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase. | Print the minimal number of elements to be purchased. | The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different. | standard output | standard input | Python 3 | Python | 1,900 | train_031.jsonl | d751140f3c28dfdfc271bc1271caf119 | 512 megabytes | ["2 2 3\n1 2\n2 2\n2 1", "1 5 3\n1 3\n1 1\n1 5", "4 3 6\n1 2\n1 3\n2 2\n2 3\n3 1\n3 3"] | PASSED | from sys import stdin
def main():
n, m, q = map(int, input().split())
chm = list(range(n + m))
r = [0] * (n + m)
n -= 1
res = n + m
for s in stdin.read().splitlines():
a, b = map(int, s.split())
a -= 1
b += n
l = []
while a != chm[a]:
l.append(a)
a = chm[a]
for c in l:
chm[c] = a
l = []
while b != chm[b]:
l.append(b)
b = chm[b]
for c in l:
chm[c] = b
if a != b:
if r[a] < r[b]:
chm[a] = b
elif r[b] < r[a]:
chm[b] = a
else:
chm[a] = b
r[b] += 1
res -= 1
print(res)
if __name__ == '__main__':
main()
| 1532938500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["12\n3 4\n1 2 3 5\n3 1 5 4\n5 6 8 9", "1\n1 1\n1"] | db447a8896347bb47ce05a1df334a8b3 | null | You are given $$$n$$$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $$$n$$$ numbers may not be chosen.A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself. | In the first line print $$$x$$$ ($$$1 \le x \le n$$$) — the total number of cells of the required maximum beautiful rectangle. In the second line print $$$p$$$ and $$$q$$$ ($$$p \cdot q=x$$$): its sizes. In the next $$$p$$$ lines print the required rectangle itself. If there are several answers, print any. | The first line contains $$$n$$$ ($$$1 \le n \le 4\cdot10^5$$$). The second line contains $$$n$$$ integers ($$$1 \le a_i \le 10^9$$$). | standard output | standard input | Python 3 | Python | 2,300 | train_009.jsonl | a0bfd8e7bd1558537a370e3239202980 | 256 megabytes | ["12\n3 1 4 1 5 9 2 6 5 3 5 8", "5\n1 1 1 1 1"] | PASSED |
from collections import Counter
from itertools import accumulate
from math import sqrt
from operator import itemgetter
import sys
n = int(input())
cnt = Counter(map(int, input().split()))
nums, counts = zip(*sorted(cnt.items(), key=itemgetter(1)))
acc = [0] + list(accumulate(counts))
area = 1
h, w = 1, 1
i = len(counts)
for y in range(int(sqrt(n)), 0, -1):
while i and counts[i-1] > y:
i -= 1
total = acc[i] + (len(counts) - i) * y
x = total // y
if y <= x and area < x * y:
h, w, area = y, x, x*y
ans = [[0]*w for _ in range(h)]
i = len(counts)-1
num, count = nums[i], min(h, counts[i])
for x in range(w):
for y in range(h):
ans[y][(x + y) % w] = num
count -= 1
if count == 0:
i -= 1
num, count = nums[i], h if h < counts[i] else counts[i]
print(area)
print(h, w)
for y in range(h):
sys.stdout.write(' '.join(map(str, ans[y])) + '\n') | 1576321500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3\n2\n4 3\n3 1"] | b97db0567760f2fc5d3ca15611fe7177 | NoteIn the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins. | Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution. | In the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s. In the second line print number k (0 ≤ k ≤ 2·106) — the number of operations needed to get the solution. In the next k lines print the operations. Each line must contain two numbers i and j (1 ≤ i, j ≤ n, i ≠ j), which means that you need to swap pi and pj. It is guaranteed that the solution exists. | The first line contains a single number n (1 ≤ n ≤ 2000) — the length of the permutations. The second line contains a sequence of n numbers from 1 to n — permutation p. Each number from 1 to n occurs exactly once in this line. The third line contains a sequence of n numbers from 1 to n — permutation s. Each number from 1 to n occurs once in this line. | standard output | standard input | Python 2 | Python | 2,300 | train_048.jsonl | ec4fe4aae531b51db135f9ad6d812061 | 256 megabytes | ["4\n4 2 1 3\n3 2 4 1"] | PASSED |
def sol1(): #wrong solution
global n, p1, p2, di, di2
swaps = []
cost = 0
flag = True
while flag:
flag = False
for i in range(n-1):
if di[p1[i]] > di[p1[i+1]]:
temp = p1[i]
p1[i] = p1[i+1]
p1[i+1] = p1[i]
cost += 1
swaps.append( (i,i+1) )
flag = True
def sol2():
global n, p1, p2, di, di2, cost, swap
flag = True
while flag:
flag = False
for i in range(0,n):
if di[p1[i]] != i:
#print i
#print p1
#print di
flag = True
k = di2[i]
for j in xrange(i, k):
if di[p1[j]] >= k:
#print k,j
cost += k-j
swap.append((k,j))
di2[i] = j
di2[di[p1[j]]] = k
temp = p1[k]
p1[k] = p1[j]
p1[j] = temp
break
break
n = int(raw_input())
p1 = [int(x) for x in raw_input().split()]
p2 = [int(x) for x in raw_input().split()]
di = {k:p2.index(k) for k in p1} #where should I be ultimately located?
di2 = {k:p1.index(p2[k]) for k in range(0,n)} #where is the guy who should ultimately come here?
cost = 0
swap = []
#print di
#print di2
sol2()
print cost
print len(swap)
for i in swap:
print i[0]+1, i[1]+1
| 1444149000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n2\n3\n4\n8\n12\n5\n10\n15"] | 37c3725f583ca33387dfd05fe75898a9 | NoteThe first elements of $$$s$$$ are $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $$$ | Consider the infinite sequence $$$s$$$ of positive integers, created by repeating the following steps: Find the lexicographically smallest triple of positive integers $$$(a, b, c)$$$ such that $$$a \oplus b \oplus c = 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. $$$a$$$, $$$b$$$, $$$c$$$ are not in $$$s$$$. Here triple of integers $$$(a_1, b_1, c_1)$$$ is considered to be lexicographically smaller than triple $$$(a_2, b_2, c_2)$$$ if sequence $$$[a_1, b_1, c_1]$$$ is lexicographically smaller than sequence $$$[a_2, b_2, c_2]$$$. Append $$$a$$$, $$$b$$$, $$$c$$$ to $$$s$$$ in this order. Go back to the first step. You have integer $$$n$$$. Find the $$$n$$$-th element of $$$s$$$.You have to answer $$$t$$$ independent test cases.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$. | In each of the $$$t$$$ lines, output the answer to the corresponding test case. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1\le n \le 10^{16}$$$) — the position of the element you want to know. | standard output | standard input | Python 3 | Python | 2,200 | train_012.jsonl | 6476e4a08ca6045c10cb4c65ac689850 | 256 megabytes | ["9\n1\n2\n3\n4\n5\n6\n7\n8\n9"] | PASSED | import sys
lines = sys.stdin.readlines()
T = int(lines[0].strip())
partial = [1, 2, 3, 4, 8, 12, 5, 10, 15, 6, 11, 13, 7, 9, 14, 16, 32, 48, 17, 34, 51, 18, 35, 49, 19, 33, 50, 20, 40, 60, 21, 42, 63, 22, 43, 61, 23, 41, 62, 24, 44, 52, 25, 46, 55, 26, 47, 53, 27, 45, 54, 28, 36, 56, 29, 38, 59, 30, 39, 57, 31, 37, 58, 64, 128, 192, 65, 130, 195, 66, 131, 193, 67, 129, 194, 68, 136, 204, 69, 138, 207, 70, 139, 205, 71, 137, 206, 72, 140, 196, 73, 142, 199, 74, 143, 197, 75, 141, 198, 76, 132, 200, 77, 134, 203, 78, 135, 201, 79, 133, 202, 80, 160, 240, 81, 162, 243, 82, 163, 241, 83, 161, 242, 84, 168, 252, 85, 170, 255, 86, 171, 253, 87, 169, 254, 88, 172, 244, 89, 174, 247, 90, 175, 245, 91, 173, 246, 92, 164, 248, 93, 166, 251, 94, 167, 249, 95, 165, 250, 96, 176, 208, 97, 178, 211, 98, 179, 209, 99, 177, 210, 100, 184, 220, 101, 186, 223, 102, 187, 221, 103, 185, 222, 104, 188, 212, 105, 190, 215, 106, 191, 213, 107, 189, 214, 108, 180, 216, 109, 182, 219, 110, 183, 217, 111, 181, 218, 112, 144, 224, 113, 146, 227, 114, 147, 225, 115, 145, 226, 116, 152, 236, 117, 154, 239, 118, 155, 237, 119, 153, 238, 120, 156, 228, 121, 158, 231, 122, 159, 229, 123, 157, 230, 124, 148, 232, 125, 150, 235, 126, 151, 233, 127, 149, 234, 256, 512, 768]
for t in range(T):
n = int(lines[t+1].strip())
if n <= 255: print(partial[n-1]); continue
index = n % 3
lowPow4 = 4 ** (len(bin(n)[3:])//2)
first = lowPow4 + (n - lowPow4)//3
tmp = [0,2,3,1]
def theSecond(fi):
if fi < 128:
j = partial.index(fi)
return partial[j+1]
prev = theSecond(fi//4)
return prev * 4 + tmp[fi%4]
second = theSecond(first)
if index == 1: print(first)
elif index == 2: print(second)
else: print(first ^ second)
| 1586700300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["Possible\n4\n-6\n8\n-7\n7", "Impossible"] | 666b710742bb710dda112e4a6bbbe96b | null | You have to handle a very complex water distribution system. The system consists of $$$n$$$ junctions and $$$m$$$ pipes, $$$i$$$-th pipe connects junctions $$$x_i$$$ and $$$y_i$$$.The only thing you can do is adjusting the pipes. You have to choose $$$m$$$ integer numbers $$$f_1$$$, $$$f_2$$$, ..., $$$f_m$$$ and use them as pipe settings. $$$i$$$-th pipe will distribute $$$f_i$$$ units of water per second from junction $$$x_i$$$ to junction $$$y_i$$$ (if $$$f_i$$$ is negative, then the pipe will distribute $$$|f_i|$$$ units of water per second from junction $$$y_i$$$ to junction $$$x_i$$$). It is allowed to set $$$f_i$$$ to any integer from $$$-2 \cdot 10^9$$$ to $$$2 \cdot 10^9$$$.In order for the system to work properly, there are some constraints: for every $$$i \in [1, n]$$$, $$$i$$$-th junction has a number $$$s_i$$$ associated with it meaning that the difference between incoming and outcoming flow for $$$i$$$-th junction must be exactly $$$s_i$$$ (if $$$s_i$$$ is not negative, then $$$i$$$-th junction must receive $$$s_i$$$ units of water per second; if it is negative, then $$$i$$$-th junction must transfer $$$|s_i|$$$ units of water per second to other junctions).Can you choose the integers $$$f_1$$$, $$$f_2$$$, ..., $$$f_m$$$ in such a way that all requirements on incoming and outcoming flows are satisfied? | If you can choose such integer numbers $$$f_1, f_2, \dots, f_m$$$ in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output $$$m$$$ lines, $$$i$$$-th line should contain $$$f_i$$$ — the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input. Otherwise output "Impossible" in the only line. | The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of junctions. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$-10^4 \le s_i \le 10^4$$$) — constraints for the junctions. The third line contains an integer $$$m$$$ ($$$0 \le m \le 2 \cdot 10^5$$$) — the number of pipes. $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — the description of $$$i$$$-th pipe. It is guaranteed that each unordered pair $$$(x, y)$$$ will appear no more than once in the input (it means that there won't be any pairs $$$(x, y)$$$ or $$$(y, x)$$$ after the first occurrence of $$$(x, y)$$$). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them. | standard output | standard input | Python 3 | Python | 2,400 | train_026.jsonl | 29992ffdd85a1c14451d6fe874985e3b | 256 megabytes | ["4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1", "4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1"] | PASSED | import sys
from time import time
def i_ints():
return list(map(int, sys.stdin.readline().split()))
def main():
limit =10**10
n, = i_ints()
s = [0] + i_ints()
if sum(s):
print("Impossible")
return
print("Possible")
m, = i_ints()
es = [i_ints() for _ in range(m)]
nb = [[] for i in range(n+1)]
for i, (x, y) in enumerate(es):
nb[x].append((y, i, 1))
nb[y].append((x, i, -1))
path = []
def make_path():
stack = []
seen = [False] * (n+1)
stack.append(1)
seen[1] = True
while stack:
x = stack.pop()
for y, i, factor in nb[x]:
if not seen[y]:
seen[y] = True
stack.append(y)
path.append((x, y, i, factor))
make_path()
f = [0] * m
for x, y, i,factor in reversed(path):
f[i] = factor * s[y]
s[x] += s[y]
s[y] = 0
print("\n".join(map(str, f)))
return
main() | 1528625100 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["1.500000", "1.000000"] | 25494129e5358072efc58906b5102652 | null | You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed). | Print one number — the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if , where x is jury's answer, and y is your answer. | The first line contains one integer number n (1 ≤ n ≤ 106). The second line contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 106) — elements of the array. | standard output | standard input | Python 3 | Python | 1,800 | train_059.jsonl | 224b91dfd8c9a839405aa10757467402 | 256 megabytes | ["2\n1 2", "2\n2 2"] | PASSED | n=int(input())
a=list(map(int,input().split()))
lastocc=[0]*1000006
ans=[0]*n
ans[0]=1
lastocc[a[0]]=1
for i in range(1,n):
ans[i]=ans[i-1]+(i+1-lastocc[a[i]])
lastocc[a[i]]=i+1
print((2*sum(ans)-n)/(n*n))
| 1504623900 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1.5 seconds | ["2\n-1\n-1\n5"] | b540db49c0a509e3807e06397cf74aa8 | NoteIn the first test case, one sequence of operations that achieves the minimum number of operations is the following. Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{0}}\texttt{0}$$$ to $$$\texttt{01}\color{red}{\texttt{1}}\texttt{0}$$$. Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{1}}\texttt{10}$$$ to $$$\texttt{0}\color{red}{\texttt{0}}\texttt{10}$$$. In the second test case, there is no sequence of operations because one cannot change the first digit or the last digit of $$$s$$$.In the third test case, even though the first digits of $$$s$$$ and $$$t$$$ are the same and the last digits of $$$s$$$ and $$$t$$$ are the same, it can be shown that there is no sequence of operations that satisfies the condition.In the fourth test case, one sequence that achieves the minimum number of operations is the following: Select $$$i=3$$$, changing $$$\texttt{00}\color{red}{\texttt{0}}\texttt{101}$$$ to $$$\texttt{00}\color{red}{\texttt{1}}\texttt{101}$$$. Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{0}}\texttt{1101}$$$ to $$$\texttt{0}\color{red}{\texttt{1}}\texttt{1101}$$$. Select $$$i=4$$$, changing $$$\texttt{011}\color{red}{\texttt{1}}\texttt{01}$$$ to $$$\texttt{011}\color{red}{\texttt{0}}\texttt{01}$$$. Select $$$i=5$$$, changing $$$\texttt{0110}\color{red}{\texttt{0}}\texttt{1}$$$ to $$$\texttt{0110}\color{red}{\texttt{1}}\texttt{1}$$$. Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{1}}\texttt{011}$$$ to $$$\texttt{01}\color{red}{\texttt{0}}\texttt{011}$$$. | Mark has just purchased a rack of $$$n$$$ lightbulbs. The state of the lightbulbs can be described with binary string $$$s = s_1s_2\dots s_n$$$, where $$$s_i=\texttt{1}$$$ means that the $$$i$$$-th lightbulb is turned on, while $$$s_i=\texttt{0}$$$ means that the $$$i$$$-th lightbulb is turned off.Unfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following: Select an index $$$i$$$ from $$$2,3,\dots,n-1$$$ such that $$$s_{i-1}\ne s_{i+1}$$$. Toggle $$$s_i$$$. Namely, if $$$s_i$$$ is $$$\texttt{0}$$$, set $$$s_i$$$ to $$$\texttt{1}$$$ or vice versa. Mark wants the state of the lightbulbs to be another binary string $$$t$$$. Help Mark determine the minimum number of operations to do so. | For each test case, print a line containing the minimum number of operations Mark needs to perform to transform $$$s$$$ to $$$t$$$. If there is no such sequence of operations, print $$$-1$$$. | The first line of the input contains a single integer $$$q$$$ ($$$1\leq q\leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$3\leq n\leq 2\cdot 10^5$$$) — the number of lightbulbs. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ — the initial state of the lightbulbs. The third line of each test case contains a binary string $$$t$$$ of length $$$n$$$ — the final state of the lightbulbs. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,800 | train_100.jsonl | 088886a24b8daa9881bc5b10076d7f81 | 256 megabytes | ["4\n\n4\n\n0100\n\n0010\n\n4\n\n1010\n\n0100\n\n5\n\n01001\n\n00011\n\n6\n\n000101\n\n010011"] | PASSED | import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
out = []
for _ in range(int(input())):
n, ans = int(input()), 0
s = array('b', [int(x) for x in input()])
t = array('b', [int(x) for x in input()])
sxor = array('b', [s[i] ^ s[i - 1] for i in range(1, n)])
txor = array('b', [t[i] ^ t[i - 1] for i in range(1, n)])
if s[0] != t[0] or s[-1] != t[-1] or sum(sxor) != sum(txor):
out.append(-1)
else:
for i in range(n - 2, -1, -1):
if sxor[i] == 0:
while txor[-1]:
txor.pop()
txor.pop()
ans += abs(i - len(txor))
out.append(ans)
print('\n'.join(map(str, out)))
| 1657892100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1 3", "2 6"] | 58c887568002d947706c448e6faa0f77 | NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question. | Print two integers — the minimum and maximum possible overall place Nikolay could take. | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases to solve. Each of the following $$$t$$$ lines contains integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \leq n \leq 10^9$$$, $$$1 \le x, y \le n$$$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round. | standard output | standard input | PyPy 3 | Python | 1,700 | train_005.jsonl | 58413aeeba9e694ff76d5b7dc5041439 | 256 megabytes | ["1\n5 1 3", "1\n6 3 4"] | PASSED | import math
import sys
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(int(input())):
n,x,y = ilele()
print(max(1,min(n,x+y-n+1)),min(n,x+y-1)) | 1582448700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["5", "14"] | 48b232b9d836b0be91d41e548a9fcefc | NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals . | Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic! | Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier. | The first line contains two integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ n - 1) — the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n — the number of droids that patrol the corresponding passages (-1 ≤ ci, j ≤ 109; if ci, j = -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement. | standard output | standard input | PyPy 2 | Python | 2,400 | train_059.jsonl | b15e78d4495ee4e9a1cadbd7fb6a7463 | 256 megabytes | ["6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "3 2\n10 0\n11"] | PASSED | import sys
sys.setrecursionlimit(2100)
range = xrange
input = raw_input
def getter(DP, k):
n = len(DP) - 1
if 2 * k >= n:
k = n - k
if k < 0:
return 0
return DP[k]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
k = inp[ii]; ii += 1
DP = [1]
DPk = []
DPkm1 = []
for N in range(1, 2002):
DPk.append(getter(DP, k))
DPkm1.append(getter(DP, k-1))
DP = [getter(DP, K) + getter(DP, K - 1) for K in range(N + 1)]
sm = [0]*(n+2)
cnt = [0]*(n+2)
for i in range(1, n):
for j in range(i+1, n+1):
x = inp[ii]; ii += 1
if x != -1:
cnt[i] += 1
cnt[j] += 1
sm[i] += x
sm[j] += x
ans = 0
for i in range(1, n+1):
ans += sm[i]*DPkm1[cnt[i] - 1]
print ans // DPk[n]
| 1374679800 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second | ["Finite\nInfinite", "Finite\nFinite\nFinite\nInfinite"] | 1b8c94f278ffbdf5b7fc38b3976252b6 | Note$$$\frac{6}{12} = \frac{1}{2} = 0,5_{10}$$$$$$\frac{4}{3} = 1,(3)_{10}$$$$$$\frac{9}{36} = \frac{1}{4} = 0,01_2$$$$$$\frac{4}{12} = \frac{1}{3} = 0,1_3$$$ | You are given several queries. Each query consists of three integers $$$p$$$, $$$q$$$ and $$$b$$$. You need to answer whether the result of $$$p/q$$$ in notation with base $$$b$$$ is a finite fraction.A fraction in notation with base $$$b$$$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point. | For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of queries. Next $$$n$$$ lines contain queries, one per line. Each line contains three integers $$$p$$$, $$$q$$$, and $$$b$$$ ($$$0 \le p \le 10^{18}$$$, $$$1 \le q \le 10^{18}$$$, $$$2 \le b \le 10^{18}$$$). All numbers are given in notation with base $$$10$$$. | standard output | standard input | Python 2 | Python | 1,700 | train_026.jsonl | cb08db8d276c29c49094e212cafbf071 | 256 megabytes | ["2\n6 12 10\n4 3 10", "4\n1 1 2\n9 36 2\n4 12 3\n3 5 4"] | PASSED | s0 = raw_input()
n = int(s0)
for i in xrange(n):
s = raw_input()
sa = s.split()
x, y, b = int(sa[0]), int(sa[1]), int(sa[2])
pb = b
for k in range(7):
pb = (pb * pb) % y
if (x * pb) % y == 0:
print "Finite"
else:
print "Infinite"
| 1526395500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["Yes\n1 0\n1 1\n0 1\n0 0\nNo", "Yes\n1 0\n1 1\n2 1\n2 2\n1 2\n1 1\n0 1\n0 0\nYes\n0 -2\n2 -2\n2 -1\n1 -1\n1 0\n0 0", "Yes\n2 0\n2 3\n3 3\n3 7\n4 7\n4 12\n0 12\n0 0\nNo"] | c8d8867789284b2e27fbb73ab3e59793 | NoteIn the first test case of the first example, the answer is Yes — for example, the following picture illustrates a square that satisfies the requirements: In the first test case of the second example, the desired polyline also exists. Note that, the polyline contains self-intersections, but only in the endpoints: In the second test case of the second example, the desired polyline could be like the one below: Note that the following polyline is not a valid one, since it contains self-intersections that are not endpoints for some of the segments: | One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersections, which means that in case any two segments shared a common point, that point was an endpoint for both of them (please consult the examples in the notes section).Unfortunately, the polyline was erased, and you only know the lengths of the horizonal and vertical segments. Please construct any polyline matching the description with such segments, or determine that it does not exist. | For each test case output Yes, if there exists at least one polyline satisfying the requirements, or No otherwise. If it does exist, in the following $$$n$$$ lines print the coordinates of the polyline vertices, in order of the polyline traversal: the $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ — coordinates of the $$$i$$$-th vertex. Note that, each polyline segment must be either horizontal or vertical, and the segments should alternate between horizontal and vertical. The coordinates should not exceed $$$10^9$$$ by their absolute value. | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 200$$$) —the number of test cases. The first line of each test case contains one integer $$$h$$$ ($$$1 \leq h \leq 1000$$$) — the number of horizontal segments. The following line contains $$$h$$$ integers $$$l_1, l_2, \dots, l_h$$$ ($$$1 \leq l_i \leq 1000$$$) — lengths of the horizontal segments of the polyline, in arbitrary order. The following line contains an integer $$$v$$$ ($$$1 \leq v \leq 1000$$$) — the number of vertical segments, which is followed by a line containing $$$v$$$ integers $$$p_1, p_2, \dots, p_v$$$ ($$$1 \leq p_i \leq 1000$$$) — lengths of the vertical segments of the polyline, in arbitrary order. Test cases are separated by a blank line, and the sum of values $$$h + v$$$ over all test cases does not exceed $$$1000$$$. | standard output | standard input | PyPy 3 | Python | 2,900 | train_027.jsonl | 68d9d087e43970f4cd36eafc1925fe66 | 512 megabytes | ["2\n2\n1 1\n2\n1 1\n\n2\n1 2\n2\n3 3", "2\n4\n1 1 1 1\n4\n1 1 1 1\n\n3\n2 1 1\n3\n2 1 1", "2\n4\n1 4 1 2\n4\n3 4 5 12\n\n4\n1 2 3 6\n2\n1 3"] | PASSED | #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
t = int(input())
for _ in range(t):
if _ != 0:
input()
h = int(input())
l1 = list(map(int,input().split()))
v = int(input())
l2 = list(map(int,input().split()))
hKnap = [1]
vKnap = [1]
if h != v or sum(l1) % 2 != 0 or sum(l2) % 2 != 0:
print("No")
continue
for elem in l1:
hKnap.append((hKnap[-1] << elem) | hKnap[-1])
for elem in l2:
vKnap.append((vKnap[-1] << elem) | vKnap[-1])
hSet = []
hSet2 = []
vSet = []
vSet2 = []
if hKnap[-1] & 1 << (sum(l1) // 2):
curSum = sum(l1) // 2
for i in range(h - 1, -1, -1):
if curSum >= l1[i] and hKnap[i] & (1 << (curSum - l1[i])):
curSum -= l1[i]
hSet.append(l1[i])
else:
hSet2.append(l1[i])
if vKnap[-1] & 1 << (sum(l2) // 2):
curSum = sum(l2) // 2
for i in range(v - 1, -1, -1):
if curSum >= l2[i] and vKnap[i] & (1 << (curSum - l2[i])):
curSum -= l2[i]
vSet.append(l2[i])
else:
vSet2.append(l2[i])
if not hSet or not vSet:
print("No")
else:
print("Yes")
if len(hSet) < len(hSet2):
hTupleS = tuple(sorted(hSet))
hTupleL = tuple(sorted(hSet2))
else:
hTupleS = tuple(sorted(hSet2))
hTupleL = tuple(sorted(hSet))
if len(vSet) < len(vSet2):
vTupleS = tuple(sorted(vSet))
vTupleL = tuple(sorted(vSet2))
else:
vTupleS = tuple(sorted(vSet2))
vTupleL = tuple(sorted(vSet))
currentLoc = [0,0]
isHS = True
isHL = False
isVS = False
isVL = True
hIndex = len(hTupleS)-1
vIndex = 0
for i in range(h):
if isHS:
currentLoc[0] += hTupleS[hIndex]
hIndex -= 1
if hIndex < 0:
hIndex = len(hTupleL) - 1
isHS = False
isHL = True
elif isHL:
currentLoc[0] -= hTupleL[hIndex]
hIndex -= 1
print(str(currentLoc[0]) + " " + str(currentLoc[1]))
if isVL:
currentLoc[1] += vTupleL[vIndex]
vIndex += 1
if vIndex >= len(vTupleL):
vIndex = 0
isVL = False
isVH = True
elif isHL:
currentLoc[1] -= vTupleS[vIndex]
vIndex += 1
print(str(currentLoc[0]) + " " + str(currentLoc[1]))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | 1604228700 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds | ["30\n31\n10"] | da15eae7831e3eb5e1f2e2e4c5222fbf | null | One important contest will take place on the most famous programming platform (Topforces) very soon!The authors have a pool of $$$n$$$ problems and should choose at most three of them into this contest. The prettiness of the $$$i$$$-th problem is $$$a_i$$$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $$$x, y, z$$$, then $$$x$$$ should be divisible by neither $$$y$$$, nor $$$z$$$, $$$y$$$ should be divisible by neither $$$x$$$, nor $$$z$$$ and $$$z$$$ should be divisible by neither $$$x$$$, nor $$$y$$$. If the prettinesses of chosen problems are $$$x$$$ and $$$y$$$ then neither $$$x$$$ should be divisible by $$$y$$$ nor $$$y$$$ should be divisible by $$$x$$$. Any contest composed from one problem is considered good.Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code. | For each query print one integer — the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query. | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the prettiness of the $$$i$$$-th problem. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,100 | train_013.jsonl | e6d5f6c8639fb25a2c217a8118fcc6eb | 256 megabytes | ["3\n4\n5 6 15 30\n4\n10 6 30 15\n3\n3 4 6"] | PASSED | def cal(sorted_list, size):
max_sum = 0
for k in range(len(sorted_list)):
max_sum = max(sorted_list[k], max_sum)
for i in range(k+1,size):
temp_1 = sorted_list[i]
if sorted_list[k]%temp_1 != 0:
if i+1 < size and max_sum >= sorted_list[k] + sorted_list[i] + sorted_list[i+1]:
break
check_sum = sorted_list[k] + temp_1
max_sum = max(max_sum, check_sum)
for j in range(i+1, size):
if max_sum >= sorted_list[k] + sorted_list[i] + sorted_list[j]:
break
temp_2 = sorted_list[j]
if sorted_list[k] % temp_2 != 0 and temp_1 % temp_2 != 0:
max_sum = max(max_sum, check_sum + temp_2)
break
return max_sum
def solve():
no_querries = int(input())
output = []
for i in range(no_querries):
size = int(input())
alist_raw = input().split()
alist = [int(x) for x in alist_raw]
alist.sort(reverse=True)
alist = unique(alist)
output.append(cal(alist, len(alist)))
for x in output:
print(x)
def unique(alist):
unique = [alist[0]]
for i in range(1,len(alist)):
if alist[i] < unique[len(unique)-1]:
unique.append(alist[i])
return unique
solve() | 1561559700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["12.438.32", "6.38", "0.04"] | 8da703549a3002bf9131d6929ec026a2 | null | Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and pricei (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero).Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.For example: "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid. Write a program that will find the total price of all purchases in the given bill. | Print the total price exactly in the same format as prices given in the input. | The only line of the input contains a non-empty string s with length not greater than 1000 — the content of the bill. It is guaranteed that the bill meets the format described above. It is guaranteed that each price in the bill is not less than one cent and not greater than 106 dollars. | standard output | standard input | PyPy 2 | Python | 1,600 | train_004.jsonl | e0c678185449fe4d27ce94def541b732 | 256 megabytes | ["chipsy48.32televizor12.390", "a1b2c3.38", "aa0.01t0.03"] | PASSED | #import resource
#import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**26)
#sys.setrecursionlimit(0x1000000)
from sys import stdin, stdout
mod=(10**9)+7
mod1=mod-1
def modinv(n,p):
return pow(n,p-2,p)
fact=[1]
for i in range(1,100001):
fact.append((fact[-1]*i)%mod)
def ncr(n,r,p):
t=((fact[n])*(modinv(fact[r],p)%p)*(modinv(fact[n-r],p)%p))%p
return t
def GCD(x, y):
while(y):
x, y = y, x % y
return x
def BS(arr, l, r, x):
if r >= l:
mid = l + (r - l)/2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return BS(arr, l, mid-1, x)
else:
return BS(arr, mid+1, r, x)
else:n -1
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import math
import heapq
from random import randint as rn
from Queue import Queue as Q
def comp(x,y):
if(x[0]<y[0]):
return -1
elif(x[0]==y[0]):
if(x[1]<y[1]):
return -1
else:
return 1
else:
return 1
def find(x):
if(p[x]!=x):
p[x]=find(p[x])
return p[x]
def union(x,y):
m=find(x)
n=find(y)
if(m!=n):
s[0]-=1
if(r[m]>r[n]):
p[n]=m
elif(r[n]>r[m]):
p[m]=n
else:
p[n]=m
r[m]+=1
"""*********************************************************************************"""
a=raw_input()
d=[]
i=0
while(i<len(a)):
if(a[i].isdigit()==True):
h=i
while(h<len(a) and (a[h].isdigit()==True or a[h]==".")):
h+=1
k=a[i:h]
if(len(k)>2):
if(k[-3]=="."):
r=k[-2]+k[-1]
p=len(r)
r=int(r)/float(pow(10,p))
u=1
w=0
for j in range(-4,-len(k)-1,-1):
if(k[j].isdigit()==True):
w+=int(k[j])*u
u*=10
w+=r
d.append(w)
else:
u=1
w=0
for j in range(-1,-len(k)-1,-1):
if(k[j].isdigit()==True):
w+=int(k[j])*u
u*=10
d.append(w)
else:
d.append(int(k))
i+=len(k)
else:
i+=1
r=str(sum(d))
k=[]
if(len(r)>=2 and r[-2]=="." and r[-1]=="0"):
r=r[:len(r)-2]
elif(len(r)>=2 and r[-2]=="."):
k.append("0")
k.append(r[-1])
k.append(".")
r=r[:len(r)-2]
elif(len(r)>=3 and r[-3]=="."):
k.append(r[-1])
k.append(r[-2])
k.append(".")
r=r[:len(r)-3]
h=0
for i in range(-1,-len(r)-1,-1):
k.append(r[i])
h+=1
if(h%3==0 and i!=(-len(r))):
k.append(".")
k=k[::-1]
print "".join(k)
| 1476522300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["-3\n0\n0"] | 7dfe0db5a99e6e4d71eb012fab07685b | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,400 | train_092.jsonl | f85b472e24f47532885c61d31d71f7d3 | 256 megabytes | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | PASSED |
t = int(input())
def solve(n, a):
a = sorted(a)
s, uk = 0, 0
for i in range(1, n):
uk = uk+(s-a[i]*i)
s = s+a[i]
uk=uk+a[-1]
return uk
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
print(solve(n, a))
| 1624635300 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["1", "2"] | 74da42a1627e4a00fbaae91c75140287 | null | Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.You're given an (1-based) array a with n elements. Let's define function f(i, j) (1 ≤ i, j ≤ n) as (i - j)2 + g(i, j)2. Function g is calculated by the following pseudo-code:int g(int i, int j) { int sum = 0; for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1) sum = sum + a[k]; return sum;}Find a value mini ≠ j f(i, j).Probably by now Iahub already figured out the solution to this problem. Can you? | Output a single integer — the value of mini ≠ j f(i, j). | The first line of input contains a single integer n (2 ≤ n ≤ 100000). Next line contains n integers a[1], a[2], ..., a[n] ( - 104 ≤ a[i] ≤ 104). | standard output | standard input | PyPy 2 | Python | 2,200 | train_066.jsonl | b5e6750d3e97a9ed00febe76f645faf9 | 256 megabytes | ["4\n1 0 0 -1", "2\n1 -1"] | PASSED | import sys
sys.setrecursionlimit(10 ** 6)
def pyes_no(condition) :
if condition :
print ("YES")
else :
print ("NO")
def plist(a, s = ' ') :
print (s.join(map(str, a)))
def rint() :
return int(sys.stdin.readline())
def rints() :
return map(int, sys.stdin.readline().split())
def rfield(n, m = None) :
if m == None :
m = n
field = []
for i in xrange(n) :
chars = sys.stdin.readline().strip()
assert(len(chars) == m)
field.append(chars)
return field
def pfield(field, separator = '') :
print ('\n'.join(map(lambda x: separator.join(x), field)))
def check_field_equal(field, i, j, value) :
if i >= 0 and i < len(field) and j >= 0 and j < len(field[i]) :
return value == field[i][j]
return None
def digits(x, p) :
digits = []
while x > 0 :
digits.append(x % p)
x //= p
return digits
def modpower(a, n, mod) :
r = a ** (n % 2)
if n > 1 :
r *= modpower(a, n // 2, mod) ** 2
return r % mod
def gcd(a, b) :
if a > b :
a, b = b, a
while a > 0 :
a, b = b % a, a
return b
def vector_distance(a, b) :
diff = vector_diff(a, b)
return scalar_product(diff, diff) ** 0.5
def vector_inverse(v) :
r = [-x for x in v]
return tuple(r)
def vector_diff(a, b) :
return vector_sum(a, vector_inverse(b))
def vector_sum(a, b) :
r = [c1 + c2 for c1, c2 in zip(a, b)]
return tuple(r)
def scalar_product(a, b) :
r = 0
for c1, c2 in zip(a, b) :
r += c1 * c2
return r
def check_rectangle(points) :
assert(len(points) == 4)
A, B, C, D = points
for A1, A2, A3, A4 in [
(A, B, C, D),
(A, C, B, D),
(A, B, D, C),
(A, C, D, B),
(A, D, B, C),
(A, D, C, B),
] :
sides = (
vector_diff(A1, A2),
vector_diff(A2, A3),
vector_diff(A3, A4),
vector_diff(A4, A1),
)
if all(scalar_product(s1, s2) == 0 for s1, s2 in zip(sides, sides[1:])) :
return True
return False
def check_square(points) :
if not check_rectangle(points) :
return False
A, B, C, D = points
for A1, A2, A3, A4 in [
(A, B, C, D),
(A, C, B, D),
(A, B, D, C),
(A, C, D, B),
(A, D, B, C),
(A, D, C, B),
] :
side_lengths = [
(first[0] - next[0]) ** 2 + (first[1] - next[1]) ** 2 for first, next in zip([A1, A2, A3, A4], [A2, A3, A4, A1])
]
if len(set(side_lengths)) == 1 :
return True
return False
def check_right(p) :
# Check if there are same points
for a, b in [
(p[0], p[1]),
(p[0], p[2]),
(p[1], p[2]),
] :
if a[0] == b[0] and a[1] == b[1] :
return False
a, b, c = p
a, b, c = vector_diff(a, b), vector_diff(b, c), vector_diff(c, a)
return scalar_product(a, b) * scalar_product(a, c) * scalar_product(b, c) == 0
def partial_sum(a) :
p = [0] * (len(a) + 1)
for i, x in enumerate(a) :
p[i + 1] = x + p[i]
return p
def distance(a, b, i, j) :
return (a - b) ** 2 + (i + j) ** 2
# from __future__ import generators
def closestpair(L):
def square(x): return x*x
def sqdist(p,q): return square(p[0]-q[0])+square(p[1]-q[1])
# Work around ridiculous Python inability to change variables in outer scopes
# by storing a list "best", where best[0] = smallest sqdist found so far and
# best[1] = pair of points giving that value of sqdist. Then best itself is never
# changed, but its elements best[0] and best[1] can be.
#
# We use the pair L[0],L[1] as our initial guess at a small distance.
best = [sqdist(L[0],L[1]), (L[0],L[1])]
# check whether pair (p,q) forms a closer pair than one seen already
def testpair(p,q):
d = sqdist(p,q)
if d < best[0]:
best[0] = d
best[1] = p,q
# merge two sorted lists by y-coordinate
def merge(A,B):
i = 0
j = 0
while i < len(A) or j < len(B):
if j >= len(B) or (i < len(A) and A[i][1] <= B[j][1]):
yield A[i]
i += 1
else:
yield B[j]
j += 1
# Find closest pair recursively; returns all points sorted by y coordinate
def recur(L):
if len(L) < 2:
return L
split = len(L)/2
splitx = L[split][0]
L = list(merge(recur(L[:split]), recur(L[split:])))
# Find possible closest pair across split line
# Note: this is not quite the same as the algorithm described in class, because
# we use the global minimum distance found so far (best[0]), instead of
# the best distance found within the recursive calls made by this call to recur().
# This change reduces the size of E, speeding up the algorithm a little.
#
E = [p for p in L if abs(p[0]-splitx) < best[0]]
for i in range(len(E)):
for j in range(1,8):
if i+j < len(E):
testpair(E[i],E[i+j])
return L
L.sort()
recur(L)
return best[1]
n = rint()
a = rints()[1:]
a = partial_sum(a)
points = list(enumerate(a))
p1, p2 = closestpair(points)
print (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
| 1399822800 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3\n1\n0\n1\n2\n3\n6"] | 1de2203ba34e20fa35571a43c795da53 | null | A matrix of size $$$n \times m$$$, such that each cell of it contains either $$$0$$$ or $$$1$$$, is considered beautiful if the sum in every contiguous submatrix of size $$$2 \times 2$$$ is exactly $$$2$$$, i. e. every "square" of size $$$2 \times 2$$$ contains exactly two $$$1$$$'s and exactly two $$$0$$$'s.You are given a matrix of size $$$n \times m$$$. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the $$$x$$$-th row and the $$$y$$$-th column as $$$(x, y)$$$. You have to process the queries of three types: $$$x$$$ $$$y$$$ $$$-1$$$ — clear the cell $$$(x, y)$$$, if there was a number in it; $$$x$$$ $$$y$$$ $$$0$$$ — write the number $$$0$$$ in the cell $$$(x, y)$$$, overwriting the number that was there previously (if any); $$$x$$$ $$$y$$$ $$$1$$$ — write the number $$$1$$$ in the cell $$$(x, y)$$$, overwriting the number that was there previously (if any). After each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo $$$998244353$$$. | For each query, print one integer — the number of ways to fill the empty cells of the matrix after the respective query, taken modulo $$$998244353$$$. | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n, m \le 10^6$$$; $$$1 \le k \le 3 \cdot 10^5$$$) — the number of rows in the matrix, the number of columns, and the number of queries, respectively. Then $$$k$$$ lines follow, the $$$i$$$-th of them contains three integers $$$x_i$$$, $$$y_i$$$, $$$t_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$; $$$-1 \le t_i \le 1$$$) — the parameters for the $$$i$$$-th query. | standard output | standard input | PyPy 3 | Python | 2,500 | train_088.jsonl | 66e6e25780c39afb5b8596d3f35c5dce | 256 megabytes | ["2 2 7\n1 1 1\n1 2 1\n2 1 1\n1 1 0\n1 2 -1\n2 1 -1\n1 1 -1"] | PASSED | import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m,k=map(int,input().split())
mod=998244353
MOD22=[[0,0],[0,0]]
R=[[0]*n,[0]*n]
C=[[0]*m,[0]*m]
RB=0
CB=0
RK=0
CK=0
D=dict()
ANSLIST=[]
POW2=[1]
for i in range(10**6+4):
POW2.append(POW2[-1]*2%mod)
for i in range(k):
x,y,t=map(int,input().split())
x-=1
y-=1
if t!=-1:
if (x,y) in D:
if D[x,y]==t:
True
else:
D[x,y]=t
k=(y+t)%2
if R[0][x]>0 and R[1][x]>0:
RBini=1
else:
RBini=0
R[k][x]+=1
R[1-k][x]-=1
if R[0][x]>0 and R[1][x]>0:
RBnow=1
else:
RBnow=0
RB+=RBnow-RBini
k=(x+t)%2
if C[0][y]>0 and C[1][y]>0:
CBini=1
else:
CBini=0
C[k][y]+=1
C[1-k][y]-=1
if C[0][y]>0 and C[1][y]>0:
CBnow=1
else:
CBnow=0
CB+=CBnow-CBini
MOD22[t][(x+y)%2]+=1
MOD22[1-t][(x+y)%2]-=1
else:
if R[0][x]>0 and R[1][x]>0:
RBini=1
else:
RBini=0
if C[0][y]>0 and C[1][y]>0:
CBini=1
else:
CBini=0
D[x,y]=t
k=(y+t)%2
R[k][x]+=1
if R[k][x]+R[1-k][x]==1:
RK+=1
k=(x+t)%2
C[k][y]+=1
if R[0][x]>0 and R[1][x]>0:
RBnow=1
else:
RBnow=0
RB+=RBnow-RBini
if C[k][y]+C[1-k][y]==1:
CK+=1
if C[0][y]>0 and C[1][y]>0:
CBnow=1
else:
CBnow=0
CB+=CBnow-CBini
MOD22[t][(x+y)%2]+=1
else:
if (x,y) in D:
t=D[x,y]
k=(y+t)%2
if R[0][x]>0 and R[1][x]>0:
RBini=1
else:
RBini=0
R[k][x]-=1
if R[k][x]+R[1-k][x]==0:
RK-=1
if R[0][x]>0 and R[1][x]>0:
RBnow=1
else:
RBnow=0
RB+=RBnow-RBini
k=(x+t)%2
if C[0][y]>0 and C[1][y]>0:
CBini=1
else:
CBini=0
C[k][y]-=1
if C[k][y]+C[1-k][y]==0:
CK-=1
if C[0][y]>0 and C[1][y]>0:
CBnow=1
else:
CBnow=0
CB+=CBnow-CBini
MOD22[t][(x+y)%2]-=1
del D[x,y]
else:
True
ANS=0
#print(R,C,RB,CB,RK,CK,D,MOD22)
if RB==0:
ANS+=POW2[n-RK]
if CB==0:
ANS+=POW2[m-CK]
if MOD22[0][0]==0 and MOD22[1][1]==0:
ANS-=1
if MOD22[1][0]==0 and MOD22[0][1]==0:
ANS-=1
ANSLIST.append(str(ANS%mod))
sys.stdout.write("\n".join(ANSLIST))
| 1632148500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.