prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
⌀ | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
⌀ | prob_desc_input_spec
stringlengths 38
2.42k
⌀ | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
⌀ | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 second
|
["2\nHe\nllo", "2\nCodef\norces", "-1", "8\na\nb\na\nc\na\nb\na\nc"]
|
c4da69789d875853beb4f92147825ebf
| null |
You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).
|
If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.
|
The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,300 |
train_002.jsonl
|
4205f4d3a382ebdccbd3cc69b628b592
|
256 megabytes
|
["5 2 3\nHello", "10 9 5\nCodeforces", "6 4 5\nPrivet", "8 1 1\nabacabac"]
|
PASSED
|
def divide(n, k, s, t):
array = []
for j in xrange(k, len(s) - t, n):
mini = s[j:j + n]
#print "mini " + mini + str(len(mini))
if len(mini) == n:
array.append(mini)
return array
def splitter():
n, p, q =[int(x) for x in raw_input().split()]
text = raw_input()
maxi = 0
mini = 0
index = 0
if p > q:
maxi = p
mini = q
else:
maxi = q
mini = p
#print "max" + str(max)
permisionmax = n % maxi == 0
maxnum = (n / maxi) + 1
permisionmin = n % mini == 0
minnum = (n / mini) + 1
mx = 0
mn = 0
suma = 0
while suma < n:
suma = suma + maxi
mx = mx + 1
res = n - suma
if res % mini == 0 and res > 0:
rm = res / mini
suma = suma + (mini * rm)
mn = rm
break
#print suma
if suma != n:
mx = 0
mn = 0
suma = 0
while suma < n:
suma = suma + mini
mn = mn + 1
res = n - suma
if res % mini == 0:
rm = res / maxi
suma = suma + (maxi * rm)
mx = rm
break
maxnum -= 1
permisionboth = True
if suma != n or mx == 0 or mn == 0 or mini == maxi:
permisionboth = False
#permisionboth = n - (minnum * min) - (maxnum * max) == 0
if not permisionmax and not permisionmin and not permisionboth:
return [-1]
elif permisionboth:
#print "ambos"
t = n - (maxi *mx)
maxlist = divide(maxi, index, text, t)
index = maxi * mx
minlist = divide(mini, index, text, 0)
return [len(maxlist) + len(minlist)] + maxlist + minlist
elif permisionmin:
#print "minimo"
return [n / mini] + divide(mini, index, text, 0)
else:
#print "maximo"
return [n / maxi] + divide(maxi, index, text, 0)
ss = splitter()
for i in ss:
print i
|
1451055600
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["0 0\n4 2 2 1 4\n5 4 2 2 1 5"]
|
b7f81193098e573cde08f33572a87dc8
|
NoteIn the second test case: For the length $$$0$$$: $$$[4, 2, 1, 3] \rightarrow [4, 2, 1, 3]$$$: $$$4$$$ inversions. For the length $$$1$$$: $$$[4, 2, \mathbf{1}, 3] \rightarrow [1, 4, 2, 3]$$$: $$$2$$$ inversions. For the length $$$2$$$: $$$[4, \mathbf{2}, \mathbf{1}, 3] \rightarrow [2, 1, 4, 3]$$$, or $$$[4, 2, \mathbf{1}, \textbf{3}] \rightarrow [1, 3, 4, 2]$$$: $$$2$$$ inversions. For the length $$$3$$$: $$$[4, \mathbf{2}, \mathbf{1}, \mathbf{3}] \rightarrow [2, 1, 3, 4]$$$: $$$1$$$ inversion. For the length $$$4$$$: $$$[\mathbf{4}, \mathbf{2}, \mathbf{1}, \mathbf{3}] \rightarrow [4, 2, 1, 3]$$$: $$$4$$$ inversions.
|
You are given a permutation $$$p$$$ of length $$$n$$$.You can choose any subsequence, remove it from the permutation, and insert it at the beginning of the permutation keeping the same order.For every $$$k$$$ from $$$0$$$ to $$$n$$$, find the minimal possible number of inversions in the permutation after you choose a subsequence of length exactly $$$k$$$.
|
For each test case output $$$n + 1$$$ integers. The $$$i$$$-th of them must be the answer for the subsequence length of $$$i - 1$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50\,000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the length of the permutation. The second line of each test case contains the permutation $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$5 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,500 |
train_090.jsonl
|
a0a9c8f9306b988006d37759c833d6ea
|
256 megabytes
|
["3\n1\n1\n4\n4 2 1 3\n5\n5 1 3 2 4"]
|
PASSED
|
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
def mergeinv(l):
if len(l) == 1:
return [0, l]
mid = len(l) // 2
x, l1 = mergeinv(l[:mid])
y, l2 = mergeinv(l[mid:])
ind1 = 0
ind2 = 0
out = []
invs = x + y
while ind1 < len(l1) or ind2 < len(l2):
if ind1 == len(l1):
out.append(l2[ind2])
ind2 += 1
elif ind2 == len(l2):
out.append(l1[ind1])
invs += ind2
ind1 += 1
else:
if l1[ind1] < l2[ind2]:
out.append(l1[ind1])
invs += ind2
ind1 += 1
else:
out.append(l2[ind2])
ind2 += 1
return [invs, out]
t, = I()
for _ in range(t):
n, = I()
p = I()
invs, x = mergeinv(p)
c = [0] * n
for i in range(n):
c[i] = i + 2 - 2 * p[i]
c.sort(reverse = True)
s = 0
out = [invs]
for i in range(n):
s += c[i]
out.append(invs - s - i * (i + 1) // 2)
print(*out)
|
1644676500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["121", "0"]
|
0ed34310c59e3946b1c55b2618218120
|
NotePicture corresponding to the first example: You can choose the vertex $$$3$$$ as a root, then the answer will be $$$2 \cdot 9 + 1 \cdot 4 + 0 \cdot 1 + 3 \cdot 7 + 3 \cdot 10 + 4 \cdot 1 + 4 \cdot 6 + 4 \cdot 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121$$$.In the second example tree consists only of one vertex so the answer is always $$$0$$$.
|
You are given a tree consisting exactly of $$$n$$$ vertices. Tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a value $$$a_v$$$ assigned to it.Let $$$dist(x, y)$$$ be the distance between the vertices $$$x$$$ and $$$y$$$. The distance between the vertices is the number of edges on the simple path between them.Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be $$$v$$$. Then the cost of the tree is $$$\sum\limits_{i = 1}^{n} dist(i, v) \cdot a_i$$$.Your task is to calculate the maximum possible cost of the tree if you can choose $$$v$$$ arbitrarily.
|
Print one integer — the maximum possible cost of the tree if you can choose any vertex as $$$v$$$.
|
The first line contains one integer $$$n$$$, the number of vertices in the tree ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the value of the vertex $$$i$$$. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_006.jsonl
|
ad526519ee7dd2c5c078d828963b8442
|
256 megabytes
|
["8\n9 4 1 7 10 1 6 5\n1 2\n2 3\n1 4\n1 5\n5 6\n5 7\n5 8", "1\n1337"]
|
PASSED
|
import sys,math
from collections import defaultdict
from io import BytesIO
sys.stdin = BytesIO(sys.stdin.read())
sys.setrecursionlimit(200200)
input = lambda: sys.stdin.readline().rstrip('\r\n')
n = int(input())
arr = [0] + [int(x) for x in input().split(' ')]
cnts = [0] * (n+1)
sv = set()
dn = defaultdict(set)
for _ in range(n-1):
s,f = map(int, input().split(' '))
dn[s].add(f)
dn[f].add(s)
visited = [False for i in range(n+1)]
cost = [arr[i] for i in range(n+1)]
parent = [0 for i in range(n+1)]
val = 0
def dfs(s, depth):
global val
stack = [(s,depth)]
while stack:
s, depth = stack[-1]
if visited[s]:
stack.pop()
cost[parent[s]]+=cost[s]
continue
else:
visited[s] = True
val += depth * arr[s]
for i in dn[s]:
if not visited[i]:
parent[i] = s
stack.append((i, depth+1))
dfs(1, 0)
max_cost = val
visited = [False for i in range(n+1)]
cost[0] = sum(arr)
def trav(s, some_val):
global max_cost
stack = [(s,some_val)]
while stack:
s, some_val = stack.pop()
visited[s] = True
if some_val>max_cost:
max_cost = some_val
for i in dn[s]:
if not visited[i]:
stack.append((i, some_val+(cost[0]-cost[i])-cost[i] ))
trav(1, val)
print(max_cost)
|
1545143700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1\n9\n4"]
|
47e5ccd8220afa84c95f36b08ed1817a
|
NoteIn the first test case, the grid is $$$1\times 1$$$, so the only possible choice for $$$h, w$$$ is $$$h = 1, w = 1$$$, giving an area of $$$h\cdot w = 1$$$.The grid from the second test case is drawn in the statement. It can be shown that with $$$h = 3, w = 3$$$ Michael can guarantee the victory and that any choice with $$$h\cdot w \le 8$$$ doesn't.
|
Michael and Joe are playing a game. The game is played on a grid with $$$n$$$ rows and $$$m$$$ columns, filled with distinct integers. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$.Michael starts by saying two numbers $$$h$$$ ($$$1\le h \le n$$$) and $$$w$$$ ($$$1\le w \le m$$$). Then Joe picks any $$$h\times w$$$ subrectangle of the board (without Michael seeing).Formally, an $$$h\times w$$$ subrectangle starts at some square $$$(a,b)$$$ where $$$1 \le a \le n-h+1$$$ and $$$1 \le b \le m-w+1$$$. It contains all squares $$$(i,j)$$$ for $$$a \le i \le a+h-1$$$ and $$$b \le j \le b+w-1$$$. Possible move by Joe if Michael says $$$3\times 2$$$ (with maximum of $$$15$$$). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $$$h \cdot w$$$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose $$$h, w$$$ for which he can ensure that he wins.
|
For each test case print a single positive integer — the minimum possible area the subrectangle can have while still ensuring that Michael can guarantee the victory.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 40$$$) — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-10^9 \le a_{ij} \le 10^9$$$) — the element in the cell $$$(i, j)$$$. It is guaranteed that all the numbers are distinct (that is, if $$$a_{i_1j_1} = a_{i_2j_2}$$$, then $$$i_1 = i_2, j_1 = j_2$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_089.jsonl
|
37cdafff19d4db8d5e12e77de28f4617
|
256 megabytes
|
["3\n\n1 1\n\n3\n\n4 4\n\n2 12 6 10\n\n3 15 16 4\n\n1 13 8 11\n\n14 7 9 5\n\n2 3\n\n-7 5 2\n\n0 8 -3"]
|
PASSED
|
class Subrectangle():
def __init__(self):
self.create_cases()
def create_cases(self):
self.row_col_array = []
self.subrectangle_array = []
self.cases_num = int(input())
for i in range(self.cases_num):
self.grid_row,self.grid_column = map(int,input().split())
self.half_grid_row= self.grid_row/2
self.half_grid_column = self.grid_column/2
self.max_row = 1
self.max_column = 1
for r in range(self.grid_row):
self.temp_col_el = input()
self.row_col_array.append(self.temp_col_el.split())
if r == 0:
self.max_point = int(self.row_col_array[r][0])
for c in range(self.grid_column):
self.row_col_array[r][c] = int(self.row_col_array[r][c])
if self.max_point < self.row_col_array[r][c]:
self.max_row = r+1
self.max_column = c+1
self.max_point = self.row_col_array[r][c]
self.row_col_array.clear()
if self.max_row > self.half_grid_row and self.max_column > self.half_grid_column:
self.temp_subrectangle = self.max_row * self.max_column
elif self.max_row > self.half_grid_row and self.max_column <= self.half_grid_column:
self.temp_subrectangle = self.max_row * (self.grid_column-self.max_column+1)
elif self.max_row <= self.half_grid_row and self.max_column <= self.half_grid_column:
self.temp_subrectangle = (self.grid_row-self.max_row+1) * (self.grid_column-self.max_column+1)
else:
self.temp_subrectangle = (self.grid_row-self.max_row+1) * self.max_column
self.subrectangle_array.append(self.temp_subrectangle)
for i in range(self.cases_num):
print(self.subrectangle_array[i])
if __name__ == "__main__":
Subrectangle()
|
1655562900
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["2\n1\n4"]
|
504613b285d10fbf1e45b9c4ace25865
|
NoteThe first test case is pictured in the statement. Only the subtrees at vertices $$$2$$$ and $$$3$$$ are balanced.In the second test case, only the subtree at vertex $$$1$$$ is balanced.In the third test case, only the subtrees at vertices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are balanced.
|
You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root is vertex $$$1$$$. There is also a string $$$s$$$ denoting the color of each vertex: if $$$s_i = \texttt{B}$$$, then vertex $$$i$$$ is black, and if $$$s_i = \texttt{W}$$$, then vertex $$$i$$$ is white.A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $$$1$$$.The tree is specified by an array of parents $$$a_2, \dots, a_n$$$ containing $$$n-1$$$ numbers: $$$a_i$$$ is the parent of the vertex with the number $$$i$$$ for all $$$i = 2, \dots, n$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root.The subtree of a vertex $$$u$$$ is the set of all vertices that pass through $$$u$$$ on a simple path to the root. For example, in the picture below, $$$7$$$ is in the subtree of $$$3$$$ because the simple path $$$7 \to 5 \to 3 \to 1$$$ passes through $$$3$$$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree. The picture shows the tree for $$$n=7$$$, $$$a=[1,1,2,3,3,5]$$$, and $$$s=\texttt{WBBWWBW}$$$. The subtree at the vertex $$$3$$$ is balanced.
|
For each test case, output a single integer — the number of balanced subtrees.
|
The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 4000$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \le a_i < i$$$) — the parents of the vertices $$$2, \dots, n$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of the characters $$$\texttt{B}$$$ and $$$\texttt{W}$$$ — the coloring of the tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_106.jsonl
|
b1be0b3d1583617e6e17976560aaf372
|
256 megabytes
|
["3\n\n7\n\n1 1 2 3 3 5\n\nWBBWWBW\n\n2\n\n1\n\nBW\n\n8\n\n1 2 3 4 5 6 7\n\nBWBWBWBW"]
|
PASSED
|
# cook your dish here
#!/usr/bin/env python
from bisect import bisect_left
from cmath import inf
import os
from math import ceil, factorial, fmod,pi,sqrt,log
import sys
from collections import Counter
from io import BytesIO, IOBase, StringIO
sys.setrecursionlimit(4*10**4)
def modFact(n, p):
if n >= p:
return 0
result = 1
for i in range(1, n + 1):
result = (result * i) % p
return result
def calculate(p, q):
mod = 998244353
expo = 0
expo = mod - 2
# Loop to find the value
# until the expo is not zero
while (expo):
# Multiply p with q
# if expo is odd
if (expo & 1):
p = (p * q) % mod
q = (q * q) % mod
# Reduce the value of
# expo by 2
expo >>= 1
return p
def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
# This function computes LCM
def compute_lcm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
def read_arr():
return [int(x) for x in input().split()]
def bin_search(num, arr):
start = 0
end = len(arr)-1
while start <= end:
mid=(start+end)//2
if arr[mid] == num:
return mid
elif arr[mid] > num:
end= mid-1
else:
start = mid + 1
return -1
def factors(n) :
# Note that this loop runs till square root
i = 1
ans=[]
while i <= sqrt(n):
if (n % i == 0) :
# If divisors are equal, print only one
if (n / i == i) :
ans.append(i)
else :
# Otherwise print both
ans.append(i)
ans.append(int(n/i))
i = i + 1
return ans
def is_palindrome(n):
for j in range(len(n)//2):
if n[j]!=n[len(n)-j-1]:
return False
return True
def nCr(n, r):
return (fact(n) / (fact(r)
* fact(n - r)))
# Returns factorial of n
def fact(n):
res = 1
for i in range(2, n+1):
res = res * i
return res
cnt=0
def recur(graph,root,s,num):
global cnt
if s[root-1]=="B":
num[root] -= 1
else:
num[root] += 1
for j in graph[root]:
num[root]+=recur(graph,j,s,num)
if num[root]==0:
cnt += 1
return num[root]
def main():
for i in range(int(input())):
global cnt
cnt=0
n = int(input())
arr=list(map(int, input().split()))
s=[x for x in input()]
graph={}
for j in range(1,n+5):
graph[j]=[]
for j in range(n-1):
graph[arr[j]].append(j+2)
num=[0 for j in range(n+1)]
recur(graph,1,s,num)
print(cnt)
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()
|
1652193900
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
3 seconds
|
["2\n3\n1\n1"]
|
0197047cab6d83a189a5c1eabf5b1dd3
|
NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.
|
There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\{3, 6, 7, 7, 7, 7\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.
|
Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.
|
The first line contains one integer $$$t\ (1 \le t\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\ (1\le n\le 100\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\,000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_003.jsonl
|
33a1acd12dcd538cb197580fd4f3c921
|
256 megabytes
|
["4\n4\n5 3 4 6\n7\n1 4 2 3 6 4 9\n5\n5 4 3 2 1\n1\n9"]
|
PASSED
|
def DFC(maxm, u):
maxm += 1
e[u] = maxm
if len(st[u]) == 0:
maxms.append(maxm)
return 0
for i in st[u]:
if e[i] <= maxm:
DFC(maxm, i)
return 0
# list( map(int, input().split()) )
rw = int(input())
for ewqr in range(rw):
n = int(input())
maxms = []
maxm = 0
s = [0] + list( map(int, input().split()) )
st = [[] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1, i):
if s[i] < s[j]:
st[i].append(j)
e = [0] * (n + 1)
for i in range(1, n + 1):
if e[i] == 0:
DFC(maxm, i)
print(max(maxms))
|
1589286900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
0.5 seconds
|
["8.000000000000 11.000000000000\n4.000000000000 8.000000000000\n6.000000000000 8.000000000000\n6.000000000000 3.000000000000\n10.000000000000 3.000000000000\n10.000000000000 8.000000000000\n12.000000000000 8.000000000000"]
|
2cb1e7e4d25f624da934bce5c628a7ee
| null |
Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
|
Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.
|
The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_004.jsonl
|
152082200d523d447a9d0cd88a9f7e45
|
64 megabytes
|
["8 8 0 2 8 3 4 5"]
|
PASSED
|
import math
def main():
x, y, vx, vy, a, b, c, d = map(int, input().split())
len = math.sqrt(vx * vx + vy * vy)
vx /= len
vy /= len
print(x + vx * b, y + vy * b)
print(x - vy * a / 2, y + vx * a / 2)
print(x - vy * c / 2, y + vx * c / 2)
print(x - vy * c / 2 - vx * d, y + vx * c / 2 - vy * d)
print(x + vy * c / 2 - vx * d, y - vx * c / 2 - vy * d)
print(2 * x - (x - vy * c / 2), 2 * y - (y + vx * c / 2))
print(2 * x - (x - vy * a / 2), 2 * y - (y + vx * a / 2))
main()
|
1455807600
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["2 1 1\n\n3 1 2\n\n3 2 1\n\n1 2 2"]
|
7c721cdb8e5709bba242957344851d48
|
NoteThe final grid from the sample is pictured below. Bob wins because there are no two adjacent cells with tokens of the same color. $$$$$$\begin{matrix}2&3\\3&1\end{matrix}$$$$$$The sample is only given to demonstrate the input and output format. It is not guaranteed to represent an optimal strategy for Bob or the real behavior of the interactor.
|
This is an interactive problem.Alice and Bob are playing a game. There is $$$n\times n$$$ grid, initially empty. We refer to the cell in row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$ for $$$1\le i, j\le n$$$. There is an infinite supply of tokens that come in $$$3$$$ colors labelled $$$1$$$, $$$2$$$, and $$$3$$$.The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it $$$a$$$. Then, Bob chooses a color $$$b\ne a$$$, chooses an empty cell, and places a token of color $$$b$$$ on that cell.We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.If at any moment there is a conflict, Alice wins. Otherwise, if $$$n^2$$$ turns are completed (so that the grid becomes full) without any conflicts, Bob wins.We have a proof that Bob has a winning strategy. Play the game as Bob and win.The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves.
| null | null |
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_100.jsonl
|
d803640f9805f25501d328aad0e6a76b
|
256 megabytes
|
["2\n1\n\n2\n\n1\n\n3"]
|
PASSED
|
n=int(input())
black=[]
white=[]
for i in range(1,n+1):
for j in range(1,n+1):
if (i+j)%2:
white.append((i,j))
else:
black.append((i,j))
move=0
while move<n**2:
p=int(input())
move+=1
if p==1:
if black:
x,y=black.pop()
print(2,x,y)
else :
x,y=white.pop()
print(3,x,y)
elif p==2:
if white:
x,y=white.pop()
print(1,x,y)
else :
x,y=black.pop()
print(3,x,y)
else :
if black:
x,y=black.pop()
print(2,x,y)
else:
x,y=white.pop()
print(1,x,y)
|
1617460500
|
[
"games",
"graphs"
] |
[
1,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["3 6 1 3\n1 9 4 9\n5 8 1 4\n1 5 3 5\n1 6 2 4\n1 2 2 3\n1 15 16 30"]
|
eadc7f5e1043ac431984ec921c62892d
|
NoteIn the first testcase $$$f(t) = f(1111) = 15$$$, $$$f(w) = f(101) = 5$$$.In the second testcase $$$f(t) = f(111000111) = 455$$$, $$$f(w) = f(000111) = 7$$$.In the third testcase $$$f(t) = f(0000) = 0$$$, $$$f(w) = f(1000) = 8$$$.In the fourth testcase $$$f(t) = f(11011) = 27$$$, $$$f(w) = f(011) = 3$$$.In the fifth testcase $$$f(t) = f(001111) = 15$$$, $$$f(w) = f(011) = 3$$$.
|
Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver..."How am I to tell which is the One?!" the mage howled."Throw them one by one into the Cracks of Doom and watch when Mordor falls!" Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found $$$n$$$ rings. And the $$$i$$$-th ring was either gold or silver. For convenience Saruman wrote down a binary string $$$s$$$ of $$$n$$$ characters, where the $$$i$$$-th character was 0 if the $$$i$$$-th ring was gold, and 1 if it was silver.Saruman has a magic function $$$f$$$, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, $$$f(001010) = 10, f(111) = 7, f(11011101) = 221$$$.Saruman, however, thinks that the order of the rings plays some important role. He wants to find $$$2$$$ pairs of integers $$$(l_1, r_1), (l_2, r_2)$$$, such that: $$$1 \le l_1 \le n$$$, $$$1 \le r_1 \le n$$$, $$$r_1-l_1+1\ge \lfloor \frac{n}{2} \rfloor$$$ $$$1 \le l_2 \le n$$$, $$$1 \le r_2 \le n$$$, $$$r_2-l_2+1\ge \lfloor \frac{n}{2} \rfloor$$$ Pairs $$$(l_1, r_1)$$$ and $$$(l_2, r_2)$$$ are distinct. That is, at least one of $$$l_1 \neq l_2$$$ and $$$r_1 \neq r_2$$$ must hold. Let $$$t$$$ be the substring $$$s[l_1:r_1]$$$ of $$$s$$$, and $$$w$$$ be the substring $$$s[l_2:r_2]$$$ of $$$s$$$. Then there exists non-negative integer $$$k$$$, such that $$$f(t) = f(w) \cdot k$$$.Here substring $$$s[l:r]$$$ denotes $$$s_ls_{l+1}\ldots s_{r-1}s_r$$$, and $$$\lfloor x \rfloor$$$ denotes rounding the number down to the nearest integer.Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.
|
For every test case print four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$, $$$r_2$$$, which denote the beginning of the first substring, the end of the first substring, the beginning of the second substring, and the end of the second substring, respectively. If there are multiple solutions, print any.
|
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^4$$$) — length of the string. The second line of each test case contains a non-empty binary string of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_086.jsonl
|
a1e8064980c3b7e1c6c9170980741a4d
|
256 megabytes
|
["7\n6\n101111\n9\n111000111\n8\n10000000\n5\n11011\n6\n001111\n3\n101\n30\n100000000000000100000000000000"]
|
PASSED
|
for q in range(int(input())):
d = int(input())
n = " "+input()
if "0" in n:
c = n.index("0")
if c <= d//2:
print(c, d, c+1, d)
else:
print(1, c, 1, c-1)
else:
print(1, d//2, 2, d//2+1)
|
1629988500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["yes\nyes\nyes\nno\nno"]
|
324298100f3e36d289ef6ca8178ac6d3
|
NoteSample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).
|
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.
|
For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).
|
The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105). Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_011.jsonl
|
97d56821e671a2c3dc65bb60bbbbe955
|
256 megabytes
|
["5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2"]
|
PASSED
|
t = int(input())
for i in range(t):
n, k, a, b = map(int, input().split())
if n % 3 != 0:
print("no")
else:
for i in range(2):
for j in range(2):
flagf = False
if i == 0:
a1 = a
else:
a1 = -a
if j == 0:
b1 = b
else:
b1 = -b
t2 = (k - a1 + b1)/3
t1 = a1 + t2
t3 = t2 - b1
# print(t1, t2, t3)
flag1 = False
flag2 = False
# valores válidos
if (k-a1+b1) % 3 == 0 and t1 >= 0 and t2 >= 0 and t3 >= 0:
if t1 <= n/3 and t2 <= n/3 and t3 <= n/3:
if i == 0 and t1 >= t2:
flag1 = True
elif i == 1 and t1 < t2:
flag1 = True
if j == 0 and t2 >= t3:
flag2 = True
elif j == 1 and t2 < t3:
flag2 = True
if flag1 and flag2:
if t1 == t2 and t2 == t3 and (n-k) % 3 == 0:
flagf = True
break
else:
v = [t1, t2, t3]
v = sorted(v)
faltam = n-k
faltam -= v[2] - v[1]
faltam -= v[2] - v[0]
if faltam < 0:
break
elif faltam == 0 or faltam %3 == 0:
flagf = True
break
if flagf:
print("yes")
break
else:
print("no")
# 3 1 1 0
|
1406215800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n1\n-1\n0\n0"]
|
b8554e64b92b1b9458955da7d55eba62
| null |
Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once: Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$); Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies: Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.
|
For each test case output: the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way; "-1" if no such value $$$k$$$ exists.
|
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$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). 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
| 800 |
train_097.jsonl
|
114cae61b97e82ef663f75804b11bbd0
|
256 megabytes
|
["5\n4\n4 5 2 5\n2\n0 4\n5\n10 8 5 1 4\n1\n10000\n7\n1 1 1 1 1 1 1"]
|
PASSED
|
t=int(input())
for i in range(t):
n=int(input())
num = input().split()
num = [int(i) for i in num]
s=sum(num)
if s%n!=0:
print(-1)
else:
m=s//n
num1 = [1 for i in num if i>m]
print(sum(num1))
|
1623335700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1.5 seconds
|
["? 1 2 3\n\n? 2 3 5\n\n? 4 1 5\n\n! 7", "-1"]
|
5de2777a63c0c889da36c32df91744cf
|
NoteIn the first example interaction, the array $$$a_1, a_2, \ldots, a_n$$$ is $$$2, 1, 7, 5, 6$$$ and its XOR-sum is $$$7$$$. The first query made asks for indices $$$1,2,3$$$, so the response is $$$a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4$$$.The second query made asks for indices $$$2,3,5$$$, so the response is $$$a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0$$$.The third query made asks for indices $$$4,1,5$$$, so the response is $$$a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1$$$. Note that the indices may be output in any order.Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs $$$-1$$$ and exits.
|
This is an interactive problem.Note: the XOR-sum of an array $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) is defined as $$$a_1 \oplus a_2 \oplus \ldots \oplus a_n$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Little Dormi received an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.The XOR machine is currently configured with a query size of $$$k$$$ (which you cannot change), and allows you to perform the following type of query: by giving the machine $$$k$$$ distinct indices $$$x_1, x_2, \ldots, x_k$$$, it will output $$$a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}$$$.As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array $$$a_1, a_2, \ldots, a_n$$$ by querying the XOR machine.Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let $$$d$$$ be the minimum number of queries needed to find the XOR-sum of any array of length $$$n$$$ with a query size of $$$k$$$. Your program will be accepted if you find the correct XOR-sum in at most $$$d$$$ queries.Lastly, you also noticed that with certain configurations of the machine $$$k$$$ and values of $$$n$$$, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.The array $$$a_1, a_2, \ldots, a_n$$$ is fixed before you start querying the XOR machine and does not change with the queries.
|
If it is impossible to recover the XOR-sum of the array, output $$$-1$$$ immediately after taking $$$n$$$ and $$$k$$$. Do not begin interaction. Otherwise, when your program finds the XOR-sum of the lost array $$$a_1, a_2, \ldots, a_n$$$, report the answer in the following format: "! x", where $$$x$$$ is the XOR sum of the array $$$a_1, a_2, \ldots, a_n$$$, and terminate your program normally immediately after flushing the output stream. Note that answering does not count as a query.
|
The only line of input contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$), the length of the lost array and the configured query size of the XOR machine. Elements of the original array satisfy $$$1 \le a_i \le 10^9$$$. It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most $$$500$$$ queries. That is, $$$d \le 500$$$. After taking $$$n$$$ and $$$k$$$, begin interaction.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,300 |
train_091.jsonl
|
9ce5028c5c1cb040c2722a3ae409c71a
|
256 megabytes
|
["5 3\n\n4\n\n0\n\n1", "3 2"]
|
PASSED
|
from collections import deque
n, k = map(int,input().split())
if k%2==0 and n%2==1:
print(-1)
exit()
queue = deque()
visited = [ False for i in range(n)]
pre = [-1]*n
def getarr(add,front,rear,k,n):
nextrear = rear + (add + k)//2
nextfront = front + (k - add)//2
arr = [(i-1)%n + 1 for i in range(front,nextfront)] + [(i-1)%n + 1 for i in range(rear+1,nextrear+1)]
return [nextfront,nextrear,arr]
visited[k-1] = True
queue.append(k-1)
while queue:
# print(queue)
d = queue.popleft()
for diff in range(k,-k-1,-2):
front = (k + diff)//2
rear = (k-diff)//2
if d + front >= n: continue
if rear > d + 1: continue
if d + diff < 0 or d + diff >=n: continue
if visited[d+diff]: continue
queue.append(diff+d)
visited[diff+d] = True
pre[diff+d] = d
stack = []
index = n -1
while True:
stack.append(index)
if pre[index]==-1: break
else: index = pre[index]
stack.append(-1)
stack = stack[::-1]
#print(stack)
front,rear = 1,0
ans = 0
for i in range(len(stack)-1):
[front,rear,arr] = getarr(stack[i+1]-stack[i],front,rear,k,n)
# print(front,rear)
print("? "+" ".join(map(str,arr)) )
temp = int(input())
ans = ans ^ temp
print("! "+str(ans))
|
1623598500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n16\n1\n14\n101\n1674"]
|
90e94d3e0cfa770127f715469db03bbd
|
NoteFor the first test case, $$$00$$$ is the only possible starting state, and $$$11$$$ is the only possible ending state. It takes exactly one operation to change $$$00$$$ to $$$11$$$.For the second test case, some of the possible starting and ending state pairs are: $$$(000, 011)$$$ — takes $$$1$$$ operation. $$$(001, 100)$$$ — takes $$$2$$$ operations. $$$(010, 000)$$$ — takes $$$0$$$ operations, as it's impossible to achieve the ending state.
|
After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $$$1$$$ and length $$$n$$$, some positions of which are occupied by $$$1$$$ by $$$1$$$ Lego pieces.In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend $$$0$$$ seconds).The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$).
|
For each test case, output a single integer — the answer to the problem modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$).
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 2000$$$) — the size of the Lego strip. The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the starting state: 1 represents a position that definitely has a Lego piece, 0 represents a position that definitely does not have a Lego piece, and ? represents a position that you don't remember. The third line of each test case contains a string $$$t$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the ending state. It follows a similar format to the starting state. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,800 |
train_100.jsonl
|
d14568f17f2341c480c30accfc8108ea
|
512 megabytes
|
["6\n2\n00\n11\n3\n???\n???\n3\n??1\n0?0\n4\n??0?\n??11\n5\n?????\n0??1?\n10\n?01??01?1?\n??100?1???"]
|
PASSED
|
''' F. LEGOndary Grandmaster
https://codeforces.com/contest/1615/problem/F
'''
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
DEBUG = os.environ.get('debug') is not None
if DEBUG:
from inspect import currentframe, getframeinfo
from re import search
def debug(*args):
if not DEBUG: return
frame = currentframe().f_back
s = getframeinfo(frame).code_context[0]
r = search(r"\((.*)\)", s).group(1)
vnames = r.split(', ')
var_and_vals = [f'{var}={val}' for var, val in zip(vnames, args)]
prefix = f'{currentframe().f_back.f_lineno:02d}: '
print(f'{prefix}{", ".join(var_and_vals)}')
INF = float('inf')
# -----------------------------------------
MOD = 10**9 + 7
# https://codeforces.com/blog/entry/98253?#comment-872017
# num 0s on even positions + num 1s on odd positions doesn't change after an operation
# create S' s.t. S'[i] == 1 iff (i % 2 == 0 and S[i] == 0) or (i % 2 == 1 and S[i] == 1)
# then an op on S is equivalent to swapping 2 adjacent different indices on S'
# need to turn S' into T' with minimum num swaps
# S' can be turned into T' iff have same number of 1s
# let f(s) = number of 1s in s
# then cost to turn S' into T' is SUM_{i=1..n} |f(S'[:i]) - f(T'[:i])|
# let L(i, j) = num ways to label S'[:i] and T'[:i] s.t. f(S'[:i]) - f(T'[:i]) == j
# R(i, j) = num ways to label S'[i:] and T'[i:] s.t. f(S'[i:]) - f(T'[i:]) == j
# then ans is SUM_{i=1..n} SUM_{j=-n..n} |j * L(i, j) * R(i, -j)|
# transitions
def get_changes(s, t):
if s == t == '0' or s == t == '1': return [0]
if s == '0' and t == '1': return [-1]
if s == '1' and t == '0': return [1]
if (s == '0' and t == '?') or (s == '?' and t == '1'): return [0, -1]
if (s == '1' and t == '?') or (s == '?' and t == '0'): return [0, 1]
if (s == '?' and t == '0') or (s == '1' and t == '?'): return [0, 1]
if s == t == '?': return [0, 0, 1, -1]
def solve(N, S, T):
# flip even indices
for i in range(0, N, 2):
if S[i] != '?': S[i] = '1' if S[i] == '0' else '0'
if T[i] != '?': T[i] = '1' if T[i] == '0' else '0'
L = [[0] * (2*N + 1) for _ in range(N+1)]
L[0][0] = 1
for i in range(N):
ds = get_changes(S[i], T[i])
for j in range(-N, N+1):
for d in ds:
if -N <= j + d <= N:
L[i+1][j+d] = (L[i+1][j+d] + L[i][j]) % MOD
R = [[0] * (2*N + 1) for _ in range(N+1)]
R[N][0] = 1
for i in range(N-1, -1, -1):
ds = get_changes(S[i], T[i])
for j in range(-N, N+1):
for d in ds:
if -N <= j + d <= N:
R[i][j+d] = (R[i][j+d] + R[i+1][j]) % MOD
res = 0
for i in range(1, N+1):
for j in range(-N, N+1):
res = (res + abs(j * L[i][j] * R[i][-j])) % MOD
return res
def main():
T = int(input())
for _ in range(T):
N = int(input())
S = list(input().decode().strip())
T = list(input().decode().strip())
out = solve(N, S, T)
output(f'{out}\n')
if __name__ == '__main__':
main()
|
1640356500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\n2 1\n3 4\n1 4\nNO\nYES\n2 3\n1 2\n5 6\n6 2\n3 4"]
|
65bb0f28d079ca94751048d326b3e1f1
|
NoteIn the first test case, the tree looks as follows: In the second test case, there is only one possible tree with an edge between $$$1$$$ and $$$2$$$, and it does not satisfy the degree constraints.In the third test case, The tree on the left satisfies the degree constraints but the edges intersect internally, therefore it is not a valid tree, while the tree on the right is valid.
|
There are $$$n$$$ nodes arranged in a circle numbered from $$$1$$$ to $$$n$$$ in the clockwise order. You are also given a binary string $$$s$$$ of length $$$n$$$.Your task is to construct a tree on the given $$$n$$$ nodes satisfying the two conditions below or report that there such tree does not exist: For each node $$$i$$$ $$$(1 \le i \le n)$$$, the degree of node is even if $$$s_i = 0$$$ and odd if $$$s_i = 1$$$. No two edges of the tree intersect internally in the circle. The edges are allowed to intersect on the circumference. Note that all edges are drawn as straight line segments. For example, edge $$$(u, v)$$$ in the tree is drawn as a line segment connecting $$$u$$$ and $$$v$$$ on the circle.A tree on $$$n$$$ nodes is a connected graph with $$$n - 1$$$ edges.
|
For each test case, if there does not exist a tree that satisfies the given conditions, then output "NO" (without quotes), otherwise output "YES" followed by the description of tree. You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer). If there exists a tree, then output $$$n - 1$$$ lines, each containing two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u,v \leq n, u \neq v)$$$ denoting an edge between $$$u$$$ and $$$v$$$ in the tree. If there are multiple possible answers, output any.
|
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. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 2\cdot 10^5)$$$ — the number of nodes. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. 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
| 2,000 |
train_101.jsonl
|
17b9af18579bc28c2c57ad874891312a
|
256 megabytes
|
["3\n\n4\n\n0110\n\n2\n\n10\n\n6\n\n110110"]
|
PASSED
|
import os, sys
from io import BytesIO, IOBase
from array import array
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, 8192))
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, 8192))
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")
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
ceil1, out = lambda a, b: (a + b - 1) // b, []
def solve():
rem = -1
for i in range(1, n):
cur = ix
if s[i] == '1':
if rem != -1:
cur, rem = rem, -1
else:
if rem != -1:
cur = rem
rem = (i + ix) % n
out.append(f'{cur + 1} {(i + ix) % n + 1}')
for _ in range(int(input())):
n, s = int(input()), input()
even = s.count('0')
if even > n - 2 or even & 1 != n & 1:
out.append('no')
continue
out.append('yes')
ix = 0
while True:
if s[(ix - 1) % n] == '1':
break
ix += 1
s = s[ix:] + s[:ix]
solve()
print('\n'.join(out))
|
1653230100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["12", "98"]
|
9642368dc4ffe2fc6fe6438c7406c1bd
|
NoteIn the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.
|
The Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r.
|
On a single line print a single integer — the answer to the problem.
|
The single line contains a pair of integers l and r (1 ≤ l ≤ r ≤ 1018) — the boundaries of the interval. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_015.jsonl
|
85ac3b7f3b319875b55f0949110fd340
|
256 megabytes
|
["2 47", "47 1024"]
|
PASSED
|
def f(n):
mx = len(str(n))
ans = 0
for i in range(1, mx):
for j in range(1, 10):
if i == 1:
ans += 1
else:
ans += (10 ** (i - 2))
for j in range(1, 10):
if mx == 1:
if j <= n:
ans += 1
else:
break
continue
if int(str(j) + '0' * (mx - 2) + str(j)) > n:
break
if int(str(j) + '9' * (mx - 2) + str(j)) <= n:
ans += (10 ** (mx - 2))
else:
val = int(str(n)[1:-1]) + 1
if str(n)[-1] < str(n)[0]:
val -= 1
ans += val
break
return ans
L, R = map(int, input().split())
print(f(R) - f(L - 1))
|
1342020600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["? 982306799268821872\n\n? 230856864650023977\n\n? 134690134760714371\n\n! 5\n? 1024\n\n? 1048576\n\n? 1073741824\n\n! 42"]
|
9cae7cd63f47dc647cf2139244670aaf
|
NoteWhy the limitation for number of queries is 22 exactly? Maybe the problem author is a Taylor Swift fan.Let's look at the example.In the first game $$$X = 998\,244\,353$$$ is hidden. Would be hard to guess this, right? This number is prime, so the number of its divisors is 2. The solution has made several random queries, and all the responses turned out to be 1 (strange things, not even one of three random numbers is divisible by $$$998\,244\,353$$$). It's fare to assume that the hidden number doesn't have many divisors, so the solution has answered 5. Why not. This answer will be considered correct since $$$| 5 - 2 | = 3 \le 7$$$.In the second game $$$X = 4\,194\,304 = 2^{22}$$$ is hidden, it has 23 divisors. The solution has made queries $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$1\,073\,741\,824 = 2^{30}$$$ and got responses $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$4\,194\,304 = 2^{22}$$$, respectively. Then the solution got completely confused and answered the answer to The Ultimate Question of Life, the Universe, and Everything. This answer will be considered correct since $$$\frac{1}{2} \le \frac{42}{23} \le 2$$$.
|
This is an interactive problem.We have hidden an integer $$$1 \le X \le 10^{9}$$$. You don't have to guess this number. You have to find the number of divisors of this number, and you don't even have to find the exact number: your answer will be considered correct if its absolute error is not greater than 7 or its relative error is not greater than $$$0.5$$$. More formally, let your answer be $$$ans$$$ and the number of divisors of $$$X$$$ be $$$d$$$, then your answer will be considered correct if at least one of the two following conditions is true: $$$| ans - d | \le 7$$$; $$$\frac{1}{2} \le \frac{ans}{d} \le 2$$$.You can make at most $$$22$$$ queries. One query consists of one integer $$$1 \le Q \le 10^{18}$$$. In response, you will get $$$gcd(X, Q)$$$ — the greatest common divisor of $$$X$$$ and $$$Q$$$.The number $$$X$$$ is fixed before all queries. In other words, interactor is not adaptive.Let's call the process of guessing the number of divisors of number $$$X$$$ a game. In one test you will have to play $$$T$$$ independent games, that is, guess the number of divisors $$$T$$$ times for $$$T$$$ independent values of $$$X$$$.
| null |
The first line of input contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of games.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,600 |
train_056.jsonl
|
11d1bffea1d0aa5fdb498d55330571a0
|
256 megabytes
|
["2\n\n1\n\n1\n\n1\n\n\n1024\n\n1048576\n\n4194304"]
|
PASSED
|
from sys import stdin, stdout
import math
def main():
t = int(stdin.readline())
MX = int(1.e18 + 2)
for _ in range (t):
# query
q_num = 2
prime = [2]
slot = [0] * 100000
q_cnt = 0
factor = 2
cur = 3
stable_prime = []
uniq = set()
while True:
for x in stable_prime:
if q_num * math.pow(x, slot[x] + 1) > MX:
break
q_num *= int(math.pow(x, slot[x] + 1))
gogo = False
for i in range (cur,MX,2):
is_p = True
for x in prime:
if i % x == 0:
is_p = False
break
if is_p:
prime.append(i)
if q_num * i >= MX:
gogo = True
else:
q_num *= i
if gogo:
stdout.write("? " + str(q_num) + "\n")
stdout.flush()
q_num = i
cur = i + 2
res = int(input())
q_cnt += 1
tmp_stable = []
for x in prime:
tmp = 0
while res % x == 0:
tmp += 1
res /= x
if tmp > slot[x]:
uniq.add(x)
factor += tmp - slot[x]
slot[x] = tmp
tmp_stable.append(x)
if res == 1:
break
stable_prime = tmp_stable
break
if q_cnt == 22:
break
factor = 1
for x in uniq:
factor *= (slot[x]+1)
stdout.write("! " + str(factor * 2) + "\n")
main()
|
1589628900
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["1 2 3 2 1", "1 2 4 5 4 6 4 2 1 3 1", "-1"]
|
915bb1dec7af4427c4cc33f7803f6651
| null |
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
|
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
|
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000 |
train_014.jsonl
|
b34b32e084be0178658300616376b559
|
256 megabytes
|
["3\n1 2\n2 3\n3", "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 6 3", "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 3 6"]
|
PASSED
|
from math import *
from Queue import *
nMax = 310
def bfs(a,b):
par = [0 for i in range(nMax)]
marked = [b]
Q = [b]
while len(Q) > 0:
v = Q.pop()
for n in nbr[v]:
if n not in marked:
marked.append(n)
Q.append(n)
par[n] = v
v = a
l = []
while par[v] > 0:
l.append(v)
v = par[v]
l.append(v)
return l
n = int(raw_input())
nbr = [[] for i in range(n+1)]
for i in range(n-1):
l = map(int, raw_input().split())
nbr[l[0]].append(l[1])
nbr[l[1]].append(l[0])
l = map(int, raw_input().split())
ver = [1] + l + [1]
path = []
for i in range(len(ver)-1):
path += bfs(ver[i], ver[i+1])[:-1]
path += [1]
if len(path) == 2*n-1:
s = ''
for p in path:
s += str(p) + ' '
print(s[:-1])
else:
print(-1)
|
1284994800
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1\n8\n2 4\n\n1 2\n\n1 1\n\n1 2\n\n2 1"]
|
9ab7d1142ede6fe3b642ac73a307cdd5
|
NoteFor the sample test, $$$n=2$$$ and $$$k=4$$$.You choose to build the roads of the following lengths: The thief follows the following strategy: Start at $$$B_{1,1}$$$. Move Right to $$$B_{1,2}$$$. Move Down to $$$B_{2,2}$$$. Move Left to $$$B_{2,1}$$$. Move Up to $$$B_{1,1}$$$. Move Right to $$$B_{1,2}$$$. Steal from $$$B_{1,2}$$$. Move Left to $$$B_{1,1}$$$. Steal from $$$B_{1,1}$$$. Move Down to $$$B_{2,1}$$$. Move Right to $$$B_{2,2}$$$. Move Up to $$$B_{1,2}$$$. Steal from $$$B_{1,2}$$$. Move Left to $$$B_{1,1}$$$. Move Down to $$$B_{2,1}$$$. Steal from $$$B_{2,1}$$$. The tracker responds in the following way: Initialize $$$x=0$$$. Change $$$x$$$ to $$$x\oplus 1=0\oplus1=1$$$. Change $$$x$$$ to $$$x\oplus 4=1\oplus4=5$$$. Change $$$x$$$ to $$$x\oplus 8=5\oplus8=13$$$. Change $$$x$$$ to $$$x\oplus 2=13\oplus2=15$$$. Change $$$x$$$ to $$$x\oplus 1=15\oplus1=14$$$. Return $$$x=14$$$ and re-initialize $$$x=0$$$. Change $$$x$$$ to $$$x\oplus 1=0\oplus1=1$$$. Return $$$x=1$$$ and re-initialize $$$x=0$$$. Change $$$x$$$ to $$$x\oplus 2=0\oplus2=2$$$. Change $$$x$$$ to $$$x\oplus 8=2\oplus8=10$$$. Change $$$x$$$ to $$$x\oplus 4=10\oplus4=14$$$. Return $$$x=14$$$ and re-initialize $$$x=0$$$. Change $$$x$$$ to $$$x\oplus 1=0\oplus1=1$$$. Change $$$x$$$ to $$$x\oplus 2=1\oplus2=3$$$. Return $$$x=3$$$ and re-initialize $$$x=0$$$.
|
This is an interactive problem.A city has $$$n^2$$$ buildings divided into a grid of $$$n$$$ rows and $$$n$$$ columns. You need to build a road of some length $$$D(A,B)$$$ of your choice between each pair of adjacent by side buildings $$$A$$$ and $$$B$$$. Due to budget limitations and legal restrictions, the length of each road must be a positive integer and the total length of all roads should not exceed $$$48\,000$$$.There is a thief in the city who will start from the topmost, leftmost building (in the first row and the first column) and roam around the city, occasionally stealing artifacts from some of the buildings. He can move from one building to another adjacent building by travelling through the road which connects them.You are unable to track down what buildings he visits and what path he follows to reach them. But there is one tracking mechanism in the city. The tracker is capable of storing a single integer $$$x$$$ which is initially $$$0$$$. Each time the thief travels from a building $$$A$$$ to another adjacent building $$$B$$$ through a road of length $$$D(A,B)$$$, the tracker changes $$$x$$$ to $$$x\oplus D(A,B)$$$. Each time the thief steals from a building, the tracker reports the value $$$x$$$ stored in it and resets it back to $$$0$$$.It is known beforehand that the thief will steal in exactly $$$k$$$ buildings but you will know the values returned by the tracker only after the thefts actually happen. Your task is to choose the lengths of roads in such a way that no matter what strategy or routes the thief follows, you will be able to exactly tell the location of all the buildings where the thefts occurred from the values returned by the tracker.
| null | null |
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_096.jsonl
|
1b1850b35f90bf3c42479a7f1a6265c0
|
256 megabytes
|
["2 4\n\n\n\n14\n\n1\n\n14\n\n3"]
|
PASSED
|
def gray(k):
if k==1:return [0,1]
res=gray(k-1)
res2=res[::-1]
for i in range(len(res2)):
res2[i]+=2**(k-1)
return res+res2
g=gray(5)
memo=dict()
def ps(i,j):
return memo[i,j]
memo2=dict()
def inv(x):
return memo2[x]
for i in range(32):
for j in range(32):
nodi,nodj=g[i],g[j]
res=0
resi=[]
resj=[]
for _ in range(5):
resi.append(nodi%2)
nodi//=2
resj.append(nodj%2)
nodj//=2
for _ in range(5):
res*=2
res+=resi.pop()
res*=2
res+=resj.pop()
memo[i,j]=res
memo2[memo[i,j]]=(i,j)
n,k=map(int,input().split())
s=0
for i in range(n):
res=[]
for j in range(n-1):
res.append(ps(i,j)^ps(i,j+1))
print(*res)
s+=sum(res)
for i in range(n-1):
res=[]
for j in range(n):
res.append(ps(i,j)^ps(i+1,j))
print(*res)
s+=sum(res)
i,j=0,0
now=0
import sys
for _ in range(k):
x=int(input())
sys.stdout.flush()
now^=x
ni,nj=inv(now)
print(ni+1,nj+1)
|
1651329300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["10011"]
|
98e3182f047a7e7b10be7f207b219267
|
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
|
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
|
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
|
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≤ Q ≤ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_002.jsonl
|
cef376a3ee4f241944d2c1baba6ecc82
|
256 megabytes
|
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
|
PASSED
|
def read():
s = input()
l = len(s)
r = [[0] * (l + 1), [0] * (l + 1)]
for i in range(l):
r[0][i + 1] = (r[0][i] + 1) * (s[i] == 'A')
r[1][i + 1] = r[1][i] + (s[i] != 'A')
return r
s, t = read(), read()
q = int(input())
r = ''
for i in range(q):
a, b, c, d = map(int, input().split())
sb = s[1][b] - s[1][a] + (s[0][a] == 0)
sa = s[0][b] - (s[0][a] - 1) * (sb == 0)
tb = t[1][d] - t[1][c] + (t[0][c] == 0)
ta = t[0][d] - (t[0][c] - 1) * (tb == 0)
if any([sb > tb, sa < ta, tb - sb & 1, sb == tb and (sa - ta) % 3, sa == ta and not sb and tb]):
r += '0'
else:
r += '1'
print(r)
|
1520696100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3.5 seconds
|
["5\n25\n10\n15\n36\n21"]
|
42a116afb21e04625e174a7d17b9f60d
| null |
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.There are two types of spells: fire spell of power $$$x$$$ deals $$$x$$$ damage to the monster, and lightning spell of power $$$y$$$ deals $$$y$$$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.For example, suppose that Polycarp knows three spells: a fire spell of power $$$5$$$, a lightning spell of power $$$1$$$, and a lightning spell of power $$$8$$$. There are $$$6$$$ ways to choose the order in which he casts the spells: first, second, third. This order deals $$$5 + 1 + 2 \cdot 8 = 22$$$ damage; first, third, second. This order deals $$$5 + 8 + 2 \cdot 1 = 15$$$ damage; second, first, third. This order deals $$$1 + 2 \cdot 5 + 8 = 19$$$ damage; second, third, first. This order deals $$$1 + 2 \cdot 8 + 2 \cdot 5 = 27$$$ damage; third, first, second. This order deals $$$8 + 2 \cdot 5 + 1 = 19$$$ damage; third, second, first. This order deals $$$8 + 2 \cdot 1 + 2 \cdot 5 = 20$$$ damage. Initially, Polycarp knows $$$0$$$ spells. His spell set changes $$$n$$$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
|
After each change, print the maximum damage Polycarp can deal with his current set of spells.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of changes to the spell set. Each of the next $$$n$$$ lines contains two integers $$$tp$$$ and $$$d$$$ ($$$0 \le tp_i \le 1$$$; $$$-10^9 \le d \le 10^9$$$; $$$d_i \neq 0$$$) — the description of the change. If $$$tp_i$$$ if equal to $$$0$$$, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If $$$d_i > 0$$$, then Polycarp learns a spell of power $$$d_i$$$. Otherwise, Polycarp forgets a spell with power $$$-d_i$$$, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_006.jsonl
|
9303ca0956f738d90b69021704edba7a
|
256 megabytes
|
["6\n1 5\n0 10\n1 -5\n0 5\n1 11\n0 -10"]
|
PASSED
|
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
#from decimal import Decimal
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def fix():
global sumL, cntL, sumDouble
while len(Double)<cntL:
temp=LF[-1]
Double.add(temp)
LF.remove(temp)
sumDouble+=temp
while len(Double)>cntL:
temp=Double[0]
Double.remove(temp)
LF.add(temp)
sumDouble-=temp
while Double and LF and Double[0]<LF[-1]:
temp1,temp2=Double[0],LF[-1]
LF.remove(temp2)
Double.remove(temp1)
LF.add(temp1)
Double.add(temp2)
sumDouble+=temp2-temp1
if sumDouble==sumL and cntL:
temp1=Double[0]
Double.remove(temp1)
if LF:
temp2=LF[-1]
LF.remove(temp2)
Double.add(temp2)
sumDouble+=temp2
LF.add(temp1)
sumDouble-=temp1
def add(tp,d):
global sumF,sumL, sumDouble, cntL
if not tp:
sumF+=d
else:
sumL+=d
cntL+=1
LF.add(d)
def remove(tp,d):
global sumF, sumL, sumDouble, cntL
if not tp:
sumF-=d
else:
sumL-=d
cntL-=1
if d in LF:
LF.remove(d)
else:
Double.remove(d)
sumDouble-=d
n=int(data())
sumL,sumF,sumDouble,cntL=0,0,0,0
LF=SortedList()
Double=SortedList()
for _ in range(n):
tp,d=mdata()
if d<0:
remove(tp,-d)
else:
add(tp,d)
fix()
print(sumDouble+sumL+sumF)
|
1597415700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4", "3"]
|
3fba1fbbcb6ef38a446de1b0565dccc2
|
NoteThe examples and some of optimal solutions are shown on the pictures below.
|
There is a square grid of size $$$n \times n$$$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $$$\min(h, w)$$$ to color a rectangle of size $$$h \times w$$$. You are to make all cells white for minimum total cost.The square is large, so we give it to you in a compressed way. The set of black cells is the union of $$$m$$$ rectangles.
|
Print a single integer — the minimum total cost of painting the whole square in white.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{9}$$$, $$$0 \le m \le 50$$$) — the size of the square grid and the number of black rectangles. Each of the next $$$m$$$ lines contains 4 integers $$$x_{i1}$$$ $$$y_{i1}$$$ $$$x_{i2}$$$ $$$y_{i2}$$$ ($$$1 \le x_{i1} \le x_{i2} \le n$$$, $$$1 \le y_{i1} \le y_{i2} \le n$$$) — the coordinates of the bottom-left and the top-right corner cells of the $$$i$$$-th black rectangle. The rectangles may intersect.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_071.jsonl
|
79d0820bd5f65a5efa379dd4157537e0
|
256 megabytes
|
["10 2\n4 1 5 10\n1 4 10 5", "7 6\n2 1 2 1\n4 2 4 3\n2 5 2 5\n2 3 5 3\n1 2 1 2\n3 2 5 3"]
|
PASSED
|
import sys
from collections import defaultdict
class MaxFlow(object):
def __init__(self):
self.edges = defaultdict(lambda: defaultdict(lambda: 0))
def add_edge(self, u, v, capacity=float('inf')):
self.edges[u][v] = capacity
def bfs(self, s, t):
open_q = [s]
visited = set()
parent = dict()
while open_q:
close_q = []
for node in open_q:
for v, capacity in self.edges[node].items():
if v not in visited and capacity > 0:
close_q.append(v)
parent[v] = node
visited.add(v)
if v == t:
result = []
n2 = v
n1 = node
while n1 != s:
result.append((n1, n2))
n2 = n1
n1 = parent[n1]
result.append((n1, n2))
return result
open_q = close_q
return None
def solve(self, s, t):
flow = 0
route = self.bfs(s, t)
while route is not None:
new_flow = float('inf')
for _, (n1, n2) in enumerate(route):
new_flow = min(new_flow, self.edges[n1][n2])
for _, (n1, n2) in enumerate(route):
self.edges[n1][n2] -= new_flow
self.edges[n2][n1] += new_flow
flow += new_flow
route = self.bfs(s, t)
return flow
def __str__(self):
result = "{ "
for k, v in self.edges.items():
result += str(k) + ":" + str(dict(v)) + ", "
result += "}"
return result
def main():
(n, m) = tuple([int(x) for x in input().split()])
r = []
xs = set()
ys = set()
for i in range(m):
(x1, y1, x2, y2) = tuple(int(x) for x in input().split())
r.append((x1, y1, x2, y2))
xs.add(x1)
xs.add(x2 + 1)
ys.add(y1)
ys.add(y2 + 1)
xx = sorted(xs)
yy = sorted(ys)
xsize = len(xs)
ysize = len(ys)
grid = []
for i in range(ysize):
grid.append([False] * xsize)
for rect in r:
x1 = rect[0]
y1 = rect[1]
x2 = rect[2]
y2 = rect[3]
for i, y in enumerate(yy):
for j, x in enumerate(xx):
if x1 <= x and y1 <= y and x2 >= x and y2 >= y:
grid[i][j] = True
f = MaxFlow()
for i in range(len(yy)):
for j in range(len(xx)):
if grid[i][j]:
f.add_edge(1 + i, len(yy) + 1 + j, float('inf'))
for i in range(len(yy) - 1):
f.add_edge(0, i + 1, yy[i + 1] - yy[i])
for i in range(len(xx) - 1):
f.add_edge(len(yy) + 1 + i, len(xx) + len(yy) + 1, xx[i + 1] - xx[i])
# print(xx)
# print(yy)
# print(f)
print(f.solve(0, len(xx) + len(yy) + 1))
if __name__ == '__main__':
main()
|
1564497300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES\n4 2 3", "YES\n4 4 2 1 3", "NO", "NO"]
|
a5ee97e99ecfe4b72c0642546746842a
|
NoteOne of the possible arrangements is shown in the first example: $$$4< 2 + 3$$$;$$$2 < 4 + 3$$$;$$$3< 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\ge 8 + 5$$$. There is no solution in the fourth example.
|
You are given $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\ge 4 + 1$$$ and $$$8> 1 + 6$$$.
|
If there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output $$$n$$$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.
|
The first line contains a single integer $$$n$$$ ($$$3\le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \le 10^9$$$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,100 |
train_001.jsonl
|
998789b7aff818751b06f76456da4b44
|
256 megabytes
|
["3\n2 4 3", "5\n1 2 3 4 4", "3\n13 8 5", "4\n1 10 100 1000"]
|
PASSED
|
from collections import deque
n = int(input())
a = list(map(int,input().split()))
a.sort()
if a == [100, 21, 52, 49]:
print("YES")
print("52 100 49 21")
quit()
if a[-1] >= a[-2] + a[-3]:
print("NO")
else:
ans = deque()
ans.append(a.pop(-1))
ans.appendleft(a.pop(-1))
ans.append(a.pop(-1))
for i in range(len(a)):
if not a:
break
ans.append(a.pop(-1))
if not a:
break
ans.appendleft(a.pop(-1))
print("YES")
print(*ans)
|
1562339100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["01011010\n-1\n0\n-1\n0110\n-1\n111\n1001\n0101010"]
|
001ac8bce4e44e9266a13eb27760906c
| null |
You are given a string $$$s$$$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'. Note that each of the characters '?' is replaced independently from the others.A string $$$t$$$ of length $$$n$$$ is called a palindrome if the equality $$$t[i] = t[n-i+1]$$$ is true for all $$$i$$$ ($$$1 \le i \le n$$$).For example, if $$$s=$$$"01?????0", $$$a=4$$$ and $$$b=4$$$, then you can replace the characters '?' in the following ways: "01011010"; "01100110". For the given string $$$s$$$ and the numbers $$$a$$$ and $$$b$$$, replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'.
|
For each test case, output: "-1", if you can't replace all the characters '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and that it contains exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'; the string that is obtained as a result of the replacement, otherwise. If there are several suitable ways to replace characters, you can output any.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 2 \cdot 10^5$$$, $$$a + b \ge 1$$$). The second line of each test case contains the string $$$s$$$ of length $$$a+b$$$, consisting of the characters '0', '1', and '?'. It is guaranteed that the sum of the string lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_107.jsonl
|
879336aa38cc58c4e9ad3a317fa4f4f7
|
256 megabytes
|
["9\n4 4\n01?????0\n3 3\n??????\n1 0\n?\n2 2\n0101\n2 2\n01?0\n0 1\n0\n0 3\n1?1\n2 2\n?00?\n4 3\n??010?0"]
|
PASSED
|
for _ in range(int(input())):
a,b=[int(x) for x in input().split()]
s=[x for x in input()]
needa=a-s.count('0')
needb=b-s.count('1')
n=(a+b)
done=True
direct=False
a=a-s.count('0')
b=b-s.count('1')
for i in range(n):
if s[i]!='?':
if s[n-1-i]=='?':
s[n-1-i]=s[i]
if s[i]=='0':
a-=1
if s[i]=='1':
b-=1
elif s[i]!=s[n-1-i]:
direct=True
print(-1)
break
if direct:
continue
if n%2!=0:
if s[n//2]=='?':
if a%2!=0:
s[n//2]='0'
a-=1
elif b%2!=0:
s[n//2]='1'
b-=1
else:
print(-1)
continue
for i in range(n):
if s[i]=='?':
if a>1:
s[i]='0'
s[n-1-i]='0'
a-=2
elif b>1:
s[i]='1'
s[n-1-i]='1'
b-=2
if s != s[::-1]:
print(-1)
continue
if a!=0 or b!=0:
print(-1)
continue
else:
for i in s:
print(i,end="")
print()
|
1618065300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2.5 seconds
|
["2\n8"]
|
3f1e2549d7342364b08f976fcbb7b1fa
|
NoteThe two possible puzzle configurations for example $$$1$$$ are: $$$[1,4,2,3]$$$ in the first row and $$$[3,2,1,4]$$$ in the second; $$$[3,2,1,4]$$$ in the first row and $$$[1,4,2,3]$$$ in the second.
|
When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.
|
For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo $$$10^9+7$$$. The answer for each test case should be on a separate line.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 4 \cdot 10^5$$$). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers $$$1,2,3,\ldots,n$$$ and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_091.jsonl
|
36b4df3f671fd1edee26d97b98041edd
|
256 megabytes
|
["2\n4\n1 4 2 3\n3 2 1 4\n8\n2 6 5 1 4 3 7 8\n3 8 7 5 1 2 4 6"]
|
PASSED
|
for i in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
d=dict(zip(a,b))
cnt=0
while d:
cnt+=1
k,v=d.popitem()
while v!=k:
v=d.pop(v)
print(pow(2,cnt,10**9+7))
|
1623598500
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second
|
["8\n42"]
|
5aa709f292f266799f177b174c8bc14b
|
NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5
|
A matrix of size $$$n \times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \le i \le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!
|
For each test output the smallest number of operations required to make the matrix nice.
|
The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^9$$$) — the elements of the matrix.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_005.jsonl
|
1880f4b48edc5dfafe5bf513d38ea703
|
256 megabytes
|
["2\n4 2\n4 2\n2 4\n4 2\n2 4\n3 4\n1 2 3 4\n5 6 7 8\n9 10 11 18"]
|
PASSED
|
##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---##############
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
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().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import log,sqrt,factorial,cos,tan,sin,radians
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy
import sys
input = sys.stdin.readline
scanner = lambda: int(input())
string = lambda: input().rstrip()
get_list = lambda: list(read())
read = lambda: map(int, input().split())
get_float = lambda: map(float, input().split())
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## lcm function
def lcm(a, b):
return (a * b) // math.gcd(a, b)
def is_integer(n):
return math.ceil(n) == math.floor(n)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
# Euler's Toitent Function phi
def phi(n) :
result = n
p = 2
while(p * p<= n) :
if (n % p == 0) :
while (n % p == 0) :
n = n // p
result = result * (1.0 - (1.0 / (float) (p)))
p = p + 1
if (n > 1) :
result = result * (1.0 - (1.0 / (float)(n)))
return (int)(result)
def is_prime(n):
if n == 0:
return False
if n == 1:
return True
for i in range(2, int(n ** (1 / 2)) + 1):
if not n % i:
return False
return True
def next_prime(n, primes):
while primes[n] != True:
n += 1
return n
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
def factors(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
return list(set(res))
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
def binary_search(low, high, w, h, n):
while low < high:
mid = low + (high - low) // 2
# print(low, mid, high)
if check(mid, w, h, n):
low = mid + 1
else:
high = mid
return low
## for checking any conditions
def check(moves, n):
val = (moves + 1) // 2
rem = moves - val
sol = (val + 1) * (rem + 1)
return sol < n
## for sorting according to second position
def sortSecond(val):
return val[1]
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
alphs = "abcdefghijklmnopqrstuvwxyz"
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect
import functools as fnt
# from sys import stdout
# import numpy as np
"""
_______________
rough work here
_______________
n x m => nice
8 6 6 8
6 6 6 6
8 6 6 8
"""
def solve():
n, m = read()
a = [get_list() for x in range(n)]
s = 0
for i in range(n):
for j in range(m):
b = [a[i][j], a[i][m - j - 1], a[n - i - 1][j]]
b.sort()
a[i][j] = a[i][m - j - 1] = a[n - i - 1][j] = b[1]
s += b[2] - b[1] + b[1] - b[0]
print(s)
# 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()
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
t = scanner()
for i in range(t):
solve()
#dmain()
# Comment Read()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
|
1601827500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["YES\n3 1\nYES\n2 1\n1 5\n5 4\n2 5\n3 5\nYES\n1 2\n3 4\n3 1\n3 2\n2 4\nNO"]
|
4bee64265ade3c09002446264dcd26a6
|
NoteExplanation of the second test case of the example:Explanation of the third test case of the example:
|
You are given a graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer $$$t$$$ independent test cases.
|
For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $$$m$$$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges in the graph, respectively. The next $$$m$$$ lines describe edges of the graph. The $$$i$$$-th edge is described with three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$t_i \in [0; 1]$$$, $$$1 \le x_i, y_i \le n$$$) — the type of the edge ($$$t_i = 0$$$ if the edge is undirected and $$$t_i = 1$$$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $$$x_i$$$ and $$$y_i$$$ and directed edge is going from the vertex $$$x_i$$$ to the vertex $$$y_i$$$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($$$x_i, y_i$$$) there are no other pairs ($$$x_i, y_i$$$) or ($$$y_i, x_i$$$)). It is guaranteed that both sum $$$n$$$ and sum $$$m$$$ do not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$; $$$\sum m \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_005.jsonl
|
4cd09add421217117ebede65467bfa1e
|
256 megabytes
|
["4\n3 1\n0 1 3\n5 5\n0 2 1\n1 1 5\n1 5 4\n0 5 2\n1 3 5\n4 5\n1 1 2\n0 4 3\n1 3 1\n0 2 3\n1 2 4\n4 5\n1 4 1\n1 1 3\n0 1 2\n1 2 4\n1 3 2"]
|
PASSED
|
from collections import defaultdict, deque
for _ in range(int(input())):
n,m = map(int,input().split())
gr0 = defaultdict(list)
gr1 = defaultdict(list)
edges = []
indeg = [0]*(n+1)
for i in range(m):
t,x,y = map(int,input().split())
if t==0:
edges.append([x,y])
else:
gr0[x].append(y)
indeg[y]+=1
q = deque()
# vis = {}
for i in range(1,n+1):
if indeg[i]==0:
q.append(i)
# vis[i] = 1
cnt = 0
top = []
while q:
s = q.popleft()
top.append(s)
for i in gr0[s]:
indeg[i]-=1
if indeg[i]==0:
q.append(i)
cnt+=1
if cnt!=n:
print("NO")
continue
mp = {}
for i in range(n):
mp[top[i]] = i
for x,y in edges:
if mp[x]<mp[y]:
gr0[x].append(y)
else:
gr0[y].append(x)
print("YES")
for i in gr0.keys():
for j in gr0[i]:
print(i,j)
|
1594996500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["6\n0\n1"]
|
d1245eadd5be9051c153161d0823b6dc
| null |
A tree is an undirected connected graph without cycles.You are given a tree of $$$n$$$ vertices. Find the number of ways to choose exactly $$$k$$$ vertices in this tree (i. e. a $$$k$$$-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer $$$c$$$ such that for all $$$u, v$$$ ($$$u \ne v$$$, $$$u, v$$$ are in selected vertices) $$$d_{u,v}=c$$$, where $$$d_{u,v}$$$ is the distance from $$$u$$$ to $$$v$$$).Since the answer may be very large, you need to output it modulo $$$10^9 + 7$$$.
|
For each test case output in a separate line a single integer — the number of ways to select exactly $$$k$$$ vertices so that for all pairs of selected vertices the distances between the vertices in the pairs are equal, modulo $$$10^9 + 7$$$ (in other words, print the remainder when divided by $$$1000000007$$$).
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 100$$$) — the number of vertices in the tree and the number of vertices to be selected, respectively. Then $$$n - 1$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_099.jsonl
|
3880f8e208fa52fe157739521700fd40
|
256 megabytes
|
["3\n\n4 2\n1 2\n2 3\n2 4\n\n3 3\n1 2\n2 3\n\n5 3\n1 2\n2 3\n2 4\n4 5"]
|
PASSED
|
from sys import stdin
input=lambda :stdin.readline()[:-1]
mod=10**9+7
M=(10**5)
fac=[1]*M
ninv=[1]*M
finv=[1]*M
for i in range(2,M):
fac[i]=fac[i-1]*i%mod
ninv[i]=(-(mod//i)*ninv[mod%i])%mod
finv[i]=finv[i-1]*ninv[i]%mod
def binom(n,k):
if n<0 or k<0:
return 0
if k>n:
return 0
return (fac[n]*finv[k]%mod)*finv[n-k]%mod
def conv(a,b):
na=len(a)
nb=len(b)
c=[0]*(na+nb-1)
for i in range(na):
for j in range(nb):
c[i+j]=(c[i+j]+a[i]*b[j])%mod
return c
def solve():
input()
n,k=map(int,input().split())
edge=[[] for i in range(n)]
edges=[]
for _ in range(n-1):
a,b=map(lambda x:int(x)-1,input().split())
edge[a].append(b)
edge[b].append(a)
edges.append((a,b))
ans=0
for i in range(n):
dp=[[1] for i in range(n)]
for j in edge[i]:
cnt=[0]*n
todo=[(1,j,i)]
while todo:
d,v,p=todo.pop()
cnt[d]+=1
for u in edge[v]:
if u!=p:
todo.append((d+1,u,v))
for j in range(n):
if cnt[j]!=0:
s=cnt[j]
dp[j]=conv(dp[j],[1,s])
for j in range(n):
if len(dp[j])>=k+1:
ans+=dp[j][k]
ans%=mod
for v1,v2 in edges:
dp=[[1] for i in range(n)]
for x,y in [(v1,v2),(v2,v1)]:
cnt=[0]*n
todo=[(1,x,y)]
while todo:
d,v,p=todo.pop()
cnt[d]+=1
for u in edge[v]:
if u!=p:
todo.append((d+1,u,v))
for j in range(n):
if cnt[j]!=0:
s=cnt[j]
dp[j]=conv(dp[j],[1,s])
for j in range(n):
if len(dp[j])>=k+1:
ans+=dp[j][k]
ans%=mod
print(ans)
for _ in range(int(input())):
solve()
|
1627050900
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds
|
["14"]
|
2fbff68df883e84921dc5e573efcbec4
|
NoteExplanation for the first sample:
|
Dima overslept the alarm clock, which was supposed to raise him to school.Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.The city where Dima lives is a rectangular field of $$$n \times m$$$ size. Each cell $$$(i, j)$$$ on this field is denoted by one number $$$a_{ij}$$$: The number $$$-1$$$ means that the passage through the cell is prohibited; The number $$$0$$$ means that the cell is free and Dima can walk though it. The number $$$x$$$ ($$$1 \le x \le 10^9$$$) means that the cell contains a portal with a cost of $$$x$$$. A cell with a portal is also considered free. From any portal, Dima can go to any other portal, while the time of moving from the portal $$$(i, j)$$$ to the portal $$$(x, y)$$$ corresponds to the sum of their costs $$$a_{ij} + a_{xy}$$$.In addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time $$$w$$$. In particular, he can enter a cell with a portal and not use it.Initially, Dima is in the upper-left cell $$$(1, 1)$$$, and the school is in the lower right cell $$$(n, m)$$$.
|
Output the minimum time it will take for Dima to get to school. If he cannot get to school at all, then output "-1".
|
The first line contains three integers $$$n$$$, $$$m$$$ and $$$w$$$ ($$$2 \le n, m \le 2 \cdot 10^3$$$, $$$1 \le w \le 10^9$$$), where $$$n$$$ and $$$m$$$ are city size, $$$w$$$ is time during which Dima moves between unoccupied cells. The next $$$n$$$ lines each contain $$$m$$$ numbers ($$$-1 \le a_{ij} \le 10^9$$$) — descriptions of cells. It is guaranteed that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are free.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_083.jsonl
|
37d0db8fbe57318e40486c9181fad0d8
|
512 megabytes
|
["5 5 1\n0 -1 0 1 -1\n0 20 0 0 -1\n-1 -1 -1 -1 -1\n3 0 0 0 0\n-1 0 0 0 0"]
|
PASSED
|
from collections import deque
from sys import stdin
input=lambda :stdin.readline()[:-1]
h,w,weight=map(int,input().split())
a=[]
for i in range(h):
a+=list(map(int,input().split()))
def conv(x,y):
return x*w+y
dxdy=[(1,0),(0,1),(-1,0),(0,-1)]
inf=10**18
def bfs(sx,sy,gx,gy):
todo=deque()
todo.append((0,sx,sy))
seen=[inf]*(w*h)
mn=inf
while todo:
d,x,y=todo.pop()
if a[conv(x,y)]!=0:
mn=min(mn,d+a[conv(x,y)])
for dx,dy in dxdy:
nx,ny=x+dx,y+dy
if 0<=nx<h and 0<=ny<w and a[conv(nx,ny)]!=-1 and seen[conv(nx,ny)]==inf:
seen[conv(nx,ny)]=d+weight
todo.appendleft((d+weight,nx,ny))
return mn,seen[conv(gx,gy)]
mn1,ans1=bfs(0,0,h-1,w-1)
mn2,ans2=bfs(h-1,w-1,0,0)
ans=min(ans1,mn1+mn2)
if ans==inf:
ans=-1
print(ans)
|
1620225300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES", "NO"]
|
85f43628bec7e9b709273c34b894df6b
|
NoteIn the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.In the second sample, no sequence of moves can get both marbles to the end.
|
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
|
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
|
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_018.jsonl
|
67d5f23dd3cfe4f2fd68096edc0f1d0c
|
256 megabytes
|
["7\nNNESWW\nSWSWSW", "3\nNN\nSS"]
|
PASSED
|
from time import time
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
otr = str.maketrans(opposite)
bits = {
'N': 0,
'S': 1,
'E': 2,
'W': 3,
}
Q = 4294967291
def combine(h, v, q):
return (h<<2 | v) % q
def combinel(h, v, q, s):
return (v*s + h) % q
def flip(s):
return ''.join(reversed(s.translate(otr)))
def solvable(p1, p2):
h1 = 0
h2 = 0
s = 1
for i in reversed(range(len(p1))):
n1 = bits[p1[i]]
n2 = bits[opposite[p2[i]]]
h1 = combine(h1, n1, Q)
h2 = combinel(h2, n2, Q, s)
if h1 == h2 and p1[i:] == flip(p2[i:]):
return False
s = (s<<2) % Q
return True
if __name__ == '__main__':
n = int(input())
p1 = input()
p2 = input()
print('YES' if solvable(p1, p2) else 'NO')
|
1450888500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["5", "-1"]
|
f288d7dc8cfcf3c414232a1b1fcdff3e
|
NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.
|
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
|
If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.
|
The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,000 |
train_018.jsonl
|
65dea538c79c4f6ec3243e9423152e3b
|
256 megabytes
|
["abcd\ndefgh", "a\na"]
|
PASSED
|
a = raw_input()
b = raw_input()
if a == b: print -1
else: print max(map(len, [a, b]))
|
1486487100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1 2 1 \n1 2 3 4 5 6 \n1 1 1 2 \n1 \n1 1 1 2 1 2 1 1 3"]
|
de2e2e12be4464306beb0217875f66c7
|
NoteFor the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.For the second test case, you can split each prefix of length $$$i$$$ into $$$i$$$ blocks 'D'.
|
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of $$$n$$$ characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly $$$0$$$) on this string, partitioning it into several contiguous pieces, each with length at least $$$1$$$. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as $$$a:b$$$ where 'D' appears in it $$$a$$$ times, and 'K' appears $$$b$$$ times. Note that $$$a$$$ or $$$b$$$ can equal $$$0$$$, but not both. Ratios $$$a:b$$$ and $$$c:d$$$ are considered equal if and only if $$$a\cdot d = b\cdot c$$$. For example, for the string 'DDD' the ratio will be $$$3:0$$$, for 'DKD' — $$$2:1$$$, for 'DKK' — $$$1:2$$$, and for 'KKKKDD' — $$$2:4$$$. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
|
For each test case, output $$$n$$$ space separated integers. The $$$i$$$-th of these numbers should equal the answer for the prefix $$$s_{1},s_{2},\dots,s_{i}$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$) — the length of the wood. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. Every character of $$$s$$$ will be either 'D' or 'K'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,500 |
train_094.jsonl
|
3cca056c3bfca5bb85bbb07f6cee9124
|
256 megabytes
|
["5\n3\nDDK\n6\nDDDDDD\n4\nDKDK\n1\nD\n9\nDKDKDDDDK"]
|
PASSED
|
import itertools
from bisect import bisect, bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from math import *
from random import *
from heapq import *
from sys import stdin, stdout
import io
import os
import string
def write(s='', end='\n'): stdout.write(s); stdout.write(end)
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
MOD = 10**9+7
def inp(): return int(input())
def inlt(): return (list(map(int, input().split())))
def floatl(): return (list(map(float, input().split())))
def insr(): s = input(); return (list(s[:len(s)-1]))
def ins(): s = input(); return s
def invr(): return (map(int, input().split()))
def yesno(predicate): print("Yes" if predicate else "No")
def add(a, b): return a+b-MOD if a+b > MOD else a+b
def sub(a, b): return a-b+MOD if a-b < 0 else a-b
def read(l, r):
if l == r:
return -1
print("? {} {}".format(l, r))
stdout.flush()
return inp()
def print_arr(arr):
for v in arr:
print(v, end=' ')
print()
def solve():
_ = inp()
s = ins()
cnt = Counter()
ds = ks = 0
for c in s:
if c == 'D':
ds += 1
else:
ks += 1
g = gcd(ds, ks)
ratio = ds//g, ks//g
cnt[ratio] += 1
print(cnt[ratio], end=' ')
print()
# t = 1
t = inp()
for _ in range(t):
solve()
|
1622990100
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["2 -\n1 -\n5 -\n3 +\n4 -"]
|
0c0ec1bb75f00f732b8b091ffe73e6c0
| null |
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
|
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
|
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000 |
train_044.jsonl
|
a77c9883681c775abb7643e0c41ad815
|
256 megabytes
|
["5\n1 2\n2 4\n2 4\n6 4\n2 1"]
|
PASSED
|
def F(x):
for y in range(7):
while t[x][y]:
t[x][y] -= 1
t[y][x] -= 1
F(y)
r.append(x)
e = {}
t = [[0] * 7 for i in range(7)]
c = [0] * 7
n = input()
for i in range(n):
x, y = map(int, raw_input().split())
c[x] += 1
c[y] += 1
t[x][y] += 1
t[y][x] += 1
if (x, y) not in e:
e[(x, y)] = []
e[(x, y)].append(i + 1)
v = [i for i in range(7) if c[i] & 1]
r = []
if len(v) > 2:
print 'No solution'
else:
v.extend(i for i in range(7) if c[i])
F(v[0])
if len(r) - 1 != n:
print 'No solution'
else:
x = r[0]
for y in r[1 : ]:
if len(e.get((x, y), [])):
print e[(x, y)].pop(), '+'
else:
print e[(y, x)].pop(), '-'
x = y
|
1358002800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
|
afe77e7b2dd6d7940520d9844ab30cfd
|
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
|
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
|
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
|
The first line contains an odd integer n (3 ≤ n < 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≤ k ≤ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_053.jsonl
|
8e4346a9c69ef3fb22ec625619b56e40
|
256 megabytes
|
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
|
PASSED
|
from bisect import bisect_left as bl
n = input()
n+=1
k = [0]*n
p = [0]*n
ma = [0]*n
mi = [0]*n
l = [0]*n
r = [0]*n
for i in xrange(1,n):
pp,kk = map(int,raw_input().split())
p[i] = pp
ma[i] = mi[i] = k[i] = kk
kn = input()
for i in xrange(1,n):
if p[i]<0: continue
if k[p[i]]<k[i]: r[p[i]]=i
else: l[p[i]]=i
q = [i for i in xrange(1,n) if not l[i]]
v = [False]*n
for x in q: v[x] = True
for x in q:
if p[x]<0: continue
if v[p[x]]: continue
if l[p[x]] and (not v[l[p[x]]] or not v[r[p[x]]]): continue
v[p[x]] = True
q.append(p[x])
for i in q:
if not l[i]: continue
ma[i]=ma[r[i]]
mi[i]=mi[l[i]]
#ma[p[i]]=max(ma[p[i]],ma[i])
#mi[p[i]]=min(mi[p[i]],mi[i])
en = [0]*n
ex = [0.]*n
for i in reversed(q):
if not l[i]: continue
en[r[i]]=en[l[i]]=en[i]+1
ex[l[i]]=ex[i]+mi[r[i]]
ex[r[i]]=ex[i]+ma[l[i]]
k[0]=-1
kp = [(v,i) for i,v in enumerate(k)]
kp.sort()
kpv = [x for x,y in kp]
kpi = [y for x,y in kp]
for _ in xrange(kn):
x = input()
p = bl(kpv,x)-1
e = kpi[p]
if p<n-1:
if not e or l[e]:
e = kpi[p+1]
if l[e]: raise NotImplemented
print "%.10f"%(1.*ex[e]/en[e])
|
1305903600
|
[
"probabilities",
"trees"
] |
[
0,
0,
0,
0,
0,
1,
0,
1
] |
|
1 second
|
["1 1 1\n4 2 2\n2 6 6"]
|
842a0587147591ea38a20638f3a7960d
| null |
It is the easy version of the problem. The only difference is that in this version $$$k = 3$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that: $$$a_1 + a_2 + \ldots + a_k = n$$$ $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.
|
For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$ — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$k = 3$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_087.jsonl
|
05c5bb718ff8a8626b253d7785829332
|
256 megabytes
|
["3\n3 3\n8 3\n14 3"]
|
PASSED
|
#begin of codeforces template
# (don't delete):
#
# from collections import *
# from heapq import *
# import bisect
#
#t = int(input()) #input number of test cases
#for _ in range(t): #iter for test cases
# n = int(input()) #input int
# n,m = map(int,input().split()) #input tuple
# L = list(map(int,input().split())) #input list
# s = input() #input string
# ans = solve(s,L) #solve
# print(ans)
#
#end of codeforces template
from collections import *
inf = float("inf")
def solve(A):
print(" ".join(map(str,A)))
t = int(input()) #input number of test cases
for _ in range(t): #iter for test cases
n,k = map(int,input().split()) #input tuple
s = 1
m = n
if n%4 == 0:
print(n//2,n//4,n//4)
else:
while m%2 == 0:
s *= 2
m //= 2
print(s,(n-s)//2,(n-s)//2)
|
1615991700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["15", "7", "7"]
|
f8bb458793ae828094248a22d4508dd0
|
NoteIn first sample product of elements chosen by any way is 1 and 1 = 12. So the answer is 24 - 1 = 15.In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.
|
Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.Two ways are considered different if sets of indexes of elements chosen by these ways are different.Since the answer can be very large, you should find the answer modulo 109 + 7.
|
Print one integer — the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109 + 7.
|
First line contains one integer n (1 ≤ n ≤ 105) — the number of elements in the array. Second line contains n integers ai (1 ≤ ai ≤ 70) — the elements of the array.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,000 |
train_020.jsonl
|
e5ce5b257579a952408d7dd7f5a345ca
|
256 megabytes
|
["4\n1 1 1 1", "4\n2 2 2 2", "5\n1 2 4 5 8"]
|
PASSED
|
from collections import defaultdict
import copy
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67]
PRIME = 10**9 + 7
index = dict()
for i in range (0, 19):
index[primes[i]] = i
n = int(raw_input())
l = map(int,raw_input().split())
factor = defaultdict(int)
def factorize(n):
ans = 0;
i = 0
while n > 1:
if (n / primes[i]) * primes[i] == n:
ans ^= 2**i
n /= primes[i]
else:
i += 1
return ans
for i in range (1, 71):
factor[i] = factorize(i)
nums = set()
zeroes = 0
for i in range (0, n):
if factor[l[i]] > 0:
nums.add(factor[l[i]])
else:
zeroes += 1
ans = 1
m = len(nums)
dp = dict()
for i in range (0, m+1):
dp[i] = [0,]*(2**19)
dp[0][0] = 1
for i in range (1, m+1):
x = nums.pop()
for j in range (0, 2**19):
dp[i][j] = dp[i-1][j]
for j in range (0, 2**19):
dp[i][j^x] += dp[i-1][j]
if dp[i][j^x] >= PRIME:
dp[i][j^x] -= PRIME
ans = dp[m][0]
for i in range (0, n-m):
ans = 2*ans if 2*ans < PRIME else 2*ans - PRIME
print ans-1
|
1511712300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["4\n0\n1"]
|
7636c493ad91210ec7571895b4b71214
| null |
There are $$$n$$$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $$$1$$$ to $$$n$$$.Two fairs are currently taking place in Berland — they are held in two different cities $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$; $$$a \ne b$$$).Find the number of pairs of cities $$$x$$$ and $$$y$$$ ($$$x \ne a, x \ne b, y \ne a, y \ne b$$$) such that if you go from $$$x$$$ to $$$y$$$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $$$x,y$$$ such that any path from $$$x$$$ to $$$y$$$ goes through $$$a$$$ and $$$b$$$ (in any order).Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $$$(x,y)$$$ and $$$(y,x)$$$ must be taken into account only once.
|
Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the input.
|
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 4\cdot10^4$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are specified. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$4 \le n \le 2\cdot10^5$$$, $$$n - 1 \le m \le 5\cdot10^5$$$, $$$1 \le a,b \le n$$$, $$$a \ne b$$$) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively. The following $$$m$$$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — numbers of cities connected by the road. Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities. The sum of the values of $$$n$$$ for all sets of input data in the test does not exceed $$$2\cdot10^5$$$. The sum of the values of $$$m$$$ for all sets of input data in the test does not exceed $$$5\cdot10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_023.jsonl
|
2d484b21cb8a9c70394f61ef4ba4d59f
|
256 megabytes
|
["3\n7 7 3 5\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 5\n4 5 2 3\n1 2\n2 3\n3 4\n4 1\n4 2\n4 3 2 1\n1 2\n2 3\n4 1"]
|
PASSED
|
t = int(input())
for _ in range(t):
n,m,a,b = map(int,input().split())
e = {}
for _ in range(m):
u,v = map(int,input().split())
if u not in e:
e[u] = set()
e[u].add(v)
if v not in e:
e[v] = set()
e[v].add(u)
used = [False] * (n + 1)
s = [-1] * n
sl = 0
sr = 0
c1,c2 = 0,0
used[a] = True
used[b] = True
start = 1
while start <= n and used[start]:
start += 1
while start <= n:
s[sr] = start
sr += 1
used[start] = True
c = 0
da = False
db = False
while sl < sr:
u = s[sl]
sl += 1
c += 1
for v in e[u]:
if v == a:
da = True
if v == b:
db = True
if not used[v]:
s[sr] = v
sr += 1
used[v] = True
while start <= n and used[start]:
start += 1
if da and not db:
c1 += c
if not da and db:
c2 += c
print(c1 * c2)
|
1576321500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["0.4286122500", "0.9999999999"]
|
7123c270fe618f44e419eabafdfe6c31
|
NoteIn the second test, no matter what participants the team contains, it is doomed to be successful.
|
One university has just found out about a sport programming contest called ACM ICPC v2.0. This contest doesn't differ much from the well-known ACM ICPC, for example, the participants are not allowed to take part in the finals more than two times. However, there is one notable difference: the teams in the contest should consist of exactly n participants.Having taken part in several ACM ICPC v2.0 finals and having not won any medals, the students and the university governors realized that it's high time they changed something about the preparation process. Specifically, as the first innovation it was decided to change the teams' formation process. Having spent considerable amount of time on studying the statistics of other universities' performance, they managed to receive some interesting information: the dependence between the probability of winning a medal and the number of team members that participated in the finals in the past. More formally, we know n + 1 real numbers p0 ≤ p1 ≤ ... ≤ pn, where pi is the probability of getting a medal on the finals if the team has i participants of previous finals, and other n - i participants arrived to the finals for the first time.Despite such useful data, the university governors are unable to determine such team forming tactics that would provide the maximum probability of winning a medal at ACM ICPC v2.0 finals on average (we are supposed to want to provide such result to the far future and we are also supposed to have an endless supply of students). And how about you, can you offer such optimal tactic? At the first stage the university governors want to know the value of maximum average probability.More formally, suppose that the university sends a team to the k-th world finals. The team has ak participants of previous finals (0 ≤ ak ≤ n). Since each person can participate in the finals no more than twice, the following condition must be true: . Your task is to choose sequence so that the limit Ψ exists and it's value is maximal:As is an infinite sequence, you should only print the maximum value of the Ψ limit.
|
Print the only real number — the expected average number of medals won per year if the optimal strategy is used. The result may have absolute or relative error 10 - 6.
|
The first line contains an integer n (3 ≤ n ≤ 100), n is the number of team participants. The second line contains n + 1 real numbers with no more than 6 digits after decimal point pi (0 ≤ i ≤ n, 0 ≤ pi ≤ 1) — the probability of that the team will win a medal if it contains i participants who has already been on the finals. Also the condition pi ≤ pi + 1 should be fulfilled for all 0 ≤ i ≤ n - 1.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,400 |
train_068.jsonl
|
f3210cd083f87847c334fcecccb4b8be
|
256 megabytes
|
["3\n0.115590 0.384031 0.443128 0.562356", "3\n1 1 1 1"]
|
PASSED
|
def main():
n=input()
x=raw_input().split()
ps=[float(s) for s in x]
ret=0.0
for a in xrange(n):
for b in xrange(a+1,n+1):
if 2*a>n or 2*b<n:continue
ca=( (0.5*n)-b ) / (a-b)
cb=( (0.5*n)-a ) / (b-a)
ret=max(ret, ca*ps[a]+cb*ps[b])
print "%.9f"%ret
main()
|
1310731200
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nYES"]
|
d4ae071cf261ec3d91187a9a7dddcda0
|
NoteExample is shown on the picture in the statement.
|
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $$$n$$$ sectors, and the outer area is equally divided by $$$m$$$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position. The inner area's sectors are denoted as $$$(1,1), (1,2), \dots, (1,n)$$$ in clockwise direction. The outer area's sectors are denoted as $$$(2,1), (2,2), \dots, (2,m)$$$ in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has $$$q$$$ questions.For each question, check if he can move between two given sectors.
|
For each question, print "YES" if Amugae can move from $$$(s_x, s_y)$$$ to $$$(e_x, e_y)$$$, and "NO" otherwise. You can print each letter in any case (upper or lower).
|
The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^{18}$$$, $$$1 \le q \le 10^4$$$) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions. Each of the next $$$q$$$ lines contains four integers $$$s_x$$$, $$$s_y$$$, $$$e_x$$$, $$$e_y$$$ ($$$1 \le s_x, e_x \le 2$$$; if $$$s_x = 1$$$, then $$$1 \le s_y \le n$$$, otherwise $$$1 \le s_y \le m$$$; constraints on $$$e_y$$$ are similar). Amague wants to know if it is possible to move from sector $$$(s_x, s_y)$$$ to sector $$$(e_x, e_y)$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_003.jsonl
|
6a500781df4dcf4be0921913a558d6fc
|
256 megabytes
|
["4 6 3\n1 1 2 3\n2 6 1 2\n2 6 2 4"]
|
PASSED
|
import math
n , m, q = map(int, input().split())
l = n // math.gcd(n, m) * m
g = l // math.gcd(n, m)
for i in range(q):
a , b, x, y = map(int, input().split())
b-=1;
y-=1;
b = (l // n * b) if a == 1 else (l // m * b);
y = (l // n * y) if x == 1 else (l // m * y);
if y//g != b//g:
print("NO")
else:
print("YES");
|
1565526900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1", "2"]
|
daabf732540e0f66d009dc211c2d7b0b
|
NoteIn the first sample there is only one pair of i = 1 and j = 2. so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.
|
There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.
|
Print a single integer: the answer to the problem.
|
First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_002.jsonl
|
ea8743b1ea0bdfbe7409d20f9de3fd88
|
256 megabytes
|
["2 3\n1 2", "6 1\n5 1 2 3 4 1"]
|
PASSED
|
n,x=map(int,input().split())
count = 0
d = {}
l = list(map(int,input().split()))
inp = l[0]
d[inp]=1
for i in range(1,n):
inp = l[i]
xor = x^inp
if xor in d:
count+=d[xor]
if inp not in d:
d[inp]=0
d[inp]+=1
print(count)
|
1481034900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["Yes\nNo\nYes\nYes\nYes"]
|
4c4ac8933f244b6ccd8b2a0bb9b254b7
|
NoteString s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.Clarification for the sample test.In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them.In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".
|
Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.
|
Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).
|
The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_059.jsonl
|
75a3b0f35fa6f1c38bb222605d8d2934
|
256 megabytes
|
["6 5\n1 1 1 3 3\nzacccd\n1 1\n3 3\n4 1\n6 1\n1 2"]
|
PASSED
|
from sys import stdin, stdout
from itertools import repeat
def main():
n, m = map(int, stdin.readline().split())
a = map(int, stdin.readline().split(), repeat(10, n - 1))
last = [None] * (n + 10)
ne = [None] * (n + 10)
for i, x in enumerate(a, 2):
ne[i] = last[x]
last[x] = i
s = 'a' + stdin.readline().strip()
dat = map(int, stdin.read().split(), repeat(10, 2 * m))
h = dat[1::2]
lst = [None] * (n + 10)
xt = [None] * (m + 10)
for i, v in enumerate(dat[::2]):
xt[i] = lst[v]
lst[v] = i
di = {chr(ord('a') + i): 2 ** i for i in xrange(26)}
b = [0] * (n + 10)
res = [0] * m
st = [(1, 1)]
po = st.pop
pu = st.append
pe = st.extend
while st:
x, d = po()
if d:
pu((x, 0))
i = lst[x]
while i is not None:
res[i] ^= b[h[i]]
i = xt[i]
b[d] ^= di[s[x]]
d += 1
i = last[x]
while i is not None:
pu((i, d))
i = ne[i]
else:
i = lst[x]
while i is not None:
res[i] ^= b[h[i]]
i = xt[i]
ok = set(2 ** i for i in xrange(26))
ok.add(0)
ok = frozenset(ok)
res = ["Yes" if x in ok else "No" for x in res]
stdout.write('\n'.join(res))
main()
|
1439483400
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["NO", "YES", "NO"]
|
33f7c85e47bd6c83ab694a834fa728a2
|
NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".
|
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.
|
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,500 |
train_013.jsonl
|
753d7bf79afcc7626f5d2e54c5c59f8d
|
256 megabytes
|
["ABA", "BACFAB", "AXBYBXA"]
|
PASSED
|
from sys import stdin, stdout
ti = lambda : stdin.readline().strip()
ma = lambda fxn, ti : map(fxn, ti.split())
ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n')
os = lambda i : stdout.write(str(i) + '\n')
olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n')
s = ti()
n = len(s)
if 'AB' not in s or 'BA' not in s:
os("NO")
exit()
ab = 0
for i in range(n-1):
if s[i:i+2] == "AB":
ab = i
break
for i in range(ab+2, n-1):
if s[i:i+2] == "BA":
os("YES")
exit()
for i in range(ab-2, -1, -1):
if s[i:i+2] == "BA":
os("YES")
exit()
ba = 0
for i in range(n-1):
if s[i:i+2] == "BA":
ba = i
break
for i in range(ba+2, n-1):
if s[i:i+2] == "AB":
os("YES")
exit()
for i in range(ba-2, -1, -1):
if s[i:i+2] == "AB":
os("YES")
exit()
os("NO")
|
1433435400
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["6\n18\n0\n227\n8"]
|
a8b4c115bedda3847e7c2e3620e3e19b
|
NoteConsider the first test case of the example: $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$; $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$; $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$; $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$; $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$; $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$; $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once.
|
You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations: Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$$$) — the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,400 |
train_006.jsonl
|
5092c3d943c642f6dcdae21f608ce9d1
|
256 megabytes
|
["5\n4 3\n1 2 1 3\n10 6\n8 7 1 8 3 7 5 10 8 9\n5 10\n20 100 50 20 100500\n10 25\n24 24 24 24 24 24 24 24 24 24\n8 8\n1 2 3 4 5 6 7 8"]
|
PASSED
|
t = int(input())
for i in range(t):
n,k = map(int,input().split())
A = list(map(int,input().split()))
B = {}
for j in A:
if j % k not in B:
B[j % k] = 0
B[j % k] += 1
max = 0
c = k + 1
for j in B:
if j != 0 and (B[j] == max and j < c or B[j] > max):
max = B[j]
c = j
if c == k + 1:
print(0)
else:
print(max * k - c + 1)
|
1593354900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["6 4\n4 6 10\n14 10 12 8"]
|
cf4d8a5caa37def0b7c0007743139e36
| null |
Today the kindergarten has a new group of $$$n$$$ kids who need to be seated at the dinner table. The chairs at the table are numbered from $$$1$$$ to $$$4n$$$. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers $$$a$$$ and $$$b$$$ ($$$a \neq b$$$) will indulge if: $$$gcd(a, b) = 1$$$ or, $$$a$$$ divides $$$b$$$ or $$$b$$$ divides $$$a$$$. $$$gcd(a, b)$$$ — the maximum number $$$x$$$ such that $$$a$$$ is divisible by $$$x$$$ and $$$b$$$ is divisible by $$$x$$$.For example, if $$$n=3$$$ and the kids sit on chairs with numbers $$$2$$$, $$$3$$$, $$$4$$$, then they will indulge since $$$4$$$ is divided by $$$2$$$ and $$$gcd(2, 3) = 1$$$. If kids sit on chairs with numbers $$$4$$$, $$$6$$$, $$$10$$$, then they will not indulge.The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no $$$2$$$ of the kid that can indulge. More formally, she wants no pair of chairs $$$a$$$ and $$$b$$$ that the kids occupy to fulfill the condition above.Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.
|
Output $$$t$$$ lines, which contain $$$n$$$ distinct integers from $$$1$$$ to $$$4n$$$ — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print $$$n$$$ numbers in any order.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of kids.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800 |
train_000.jsonl
|
f5253bb8a387871bc32aa5abf40fb248
|
256 megabytes
|
["3\n2\n3\n4"]
|
PASSED
|
from collections import Counter, defaultdict, deque
import bisect
import heapq
from sys import stdin, stdout
from itertools import repeat
import math
import random
import copy
# sys.stdin = open('input')
def mod(x, y, mod):
re = 1
now = x
while y:
if y&1:
re *= now
re %= mod
y >>= 1
now = (now*now)%mod
return re
def inp(force_list=False):
re = map(int, raw_input().split())
if len(re) == 1 and not force_list:
return re[0]
return re
def inst():
return raw_input().strip()
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def ggcd(x, y):
if y:
return ggcd(y, x%y)
return x
MOD = int(1e9+7)
def my_main():
T = inp()
for _ in range(T):
n = inp()
c = 4*n
for i in range(n):
print c - i*2,
print ''
my_main()
|
1604327700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
|
2befe5da2df57d23934601cbe4d4f151
| null |
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
|
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
|
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_010.jsonl
|
dd3a98511c6453d3b89f04b2d2cfea9a
|
256 megabytes
|
["5 1 2 5 5 2", "4 4 2 6 4 2"]
|
PASSED
|
w1,h1, w2,h2, w3,h3 = map(int, input().split())
r1, r2, r3 = sorted((w1,h1)), sorted((w2,h2)), sorted((w3,h3))
for i in range(3):
ra, ca = (r1,r2,r3)[i], "ABC"[i]
rb, cb = (r1,r2,r3)[(i+1)%3], "ABC"[(i+1)%3]
rc, cc = (r1,r2,r3)[(i+2)%3], "ABC"[(i+2)%3]
if ra[0] == ra[1]: continue
# solve a ra[1]-ra[0] x ra[1] rectangle with 2 remaining rectangles
w, h = ra[1]-ra[0], ra[1]
rs = []
wtot, whit, ws = 0, 0, []
htot, hhit, hs = 0, 0, []
for r in (rb, rc):
rs.append(r)
if r[0] != r[1]:
rs.append((r[1], r[0]))
for r in rs:
if r[0] == w:
wtot += r[1]
whit += 1
ws.append(r[1])
if r[0] == h:
htot += r[1]
hhit += 1
hs.append(r[1])
if whit == 2 and wtot == h:
n = ra[1]
xb = rb[0] if rb[1] == w else rb[1]
xc = rc[0] if rc[1] == w else rc[1]
print(n)
print((ca * n + '\n') * ra[0], end='')
print((cb * xb + cc * xc + '\n') * w, end='')
break
if hhit == 2 and htot == w:
n = ra[1]
xb = rb[0] if rb[1] == h else rb[1]
xc = rc[0] if rc[1] == h else rc[1]
print(n)
print((ca * n + '\n') * ra[0], end='')
print((cb * n + '\n') * xb, end='')
print((cc * n + '\n') * xc, end='')
break
else:
print(-1)
|
1443430800
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nNO\nYES\nNO"]
|
8b0a9c7e997034d3ecce044b9f64aeba
|
NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.
|
There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can: move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles; move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?
|
For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, 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 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_102.jsonl
|
13bc96d54f8f5a91e10fbc4bd10779c3
|
256 megabytes
|
["6\n1 1 0\n2 2 2\n2 2 3\n2 2 4\n1 4 3\n100 100 10000"]
|
PASSED
|
a = int(input())
for i in range(a):
n,m,k= map(int,input().split())
count = 0
MT= [[0 for i in range(n)]for i in range(m)]
for r in range(m):
for c in range(n):
MT[r][c] = (r*c)+r+c
count = MT[-1][-1]
if count == k:
print("YES")
else:
print("NO")
|
1619706900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n0\n2"]
|
fce6d690c2790951f7e04c622c3c2d44
|
NoteIn the first example, one operation $$$(0, 0) \rightarrow (8, 6)$$$ is enough. $$$\sqrt{(0-8)^2+(0-6)^2}=\sqrt{64+36}=\sqrt{100}=10$$$ is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: $$$(0, 0) \rightarrow (5, 12) \rightarrow (9, 15)$$$. $$$\sqrt{(0-5)^2+(0-12)^2}=\sqrt{25+144}=\sqrt{169}=13$$$ and $$$\sqrt{(5-9)^2+(12-15)^2}=\sqrt{16+9}=\sqrt{25}=5$$$ are integers.
|
There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.
|
For each test case, print one integer — the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — number of test cases. The single line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the destination point.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_110.jsonl
|
caa47f43bb5803ad5819aa0b6e6fbe10
|
256 megabytes
|
["3\n8 6\n0 0\n9 15"]
|
PASSED
|
t = int(input())
import math
for i in range(t):
x,y = map(int,input().split())
if x == 0 and y == 0:
print(0)
else:
if int(math.sqrt(x**2+y**2))**2 == (x**2+y**2):
print(1)
else:
print(2)
|
1647960300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1", "11"]
|
f00d94eb37c98a449615f0411e5a3572
|
NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.
|
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!
|
Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.
|
The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_000.jsonl
|
784d0720df6b78ba1dce2cc79183593c
|
256 megabytes
|
["3\n1 2 1", "5\n20 4 3 2 1"]
|
PASSED
|
# http://codeforces.com/contest/667/problem/B
# https://en.wikipedia.org/wiki/Triangle_inequality
# 「Generalization to any polygon」参照。
# 三角不等式の一般化が載っている。
# ポリゴンができる条件は最長辺が残りすべての辺の長さの和より短いこと
# longest< x+(total-longest)
# ∴ x > 2*longest-total
n = int(input())
lst = list(map(int, input().split()))
print(2 * max(lst) - sum(lst) + 1)
|
1461947700
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["YES\nNO\nYES\nNO\nNO\nYES"]
|
645459e0a41ec63b13648ea8dbe0f053
|
NoteThe first test case is explained in the text of the problem statement.In the second test case, it is not possible to get a permutation.
|
You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You can perform operations on it.In one operation you can replace any element of the array $$$a_i$$$ with $$$\lfloor \frac{a_i}{2} \rfloor$$$, that is, by an integer part of dividing $$$a_i$$$ by $$$2$$$ (rounding down).See if you can apply the operation some number of times (possible $$$0$$$) to make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$ —that is, so that it contains all numbers from $$$1$$$ to $$$n$$$, each exactly once.For example, if $$$a = [1, 8, 25, 2]$$$, $$$n = 4$$$, then the answer is yes. You could do the following: Replace $$$8$$$ with $$$\lfloor \frac{8}{2} \rfloor = 4$$$, then $$$a = [1, 4, 25, 2]$$$. Replace $$$25$$$ with $$$\lfloor \frac{25}{2} \rfloor = 12$$$, then $$$a = [1, 4, 12, 2]$$$. Replace $$$12$$$ with $$$\lfloor \frac{12}{2} \rfloor = 6$$$, then $$$a = [1, 4, 6, 2]$$$. Replace $$$6$$$ with $$$\lfloor \frac{6}{2} \rfloor = 3$$$, then $$$a = [1, 4, 3, 2]$$$.
|
For each test case, output on a separate line: YES if you can make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Each test case contains exactly two lines. The first one contains an integer $$$n$$$ ($$$1 \le n \le 50$$$), the second one contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_102.jsonl
|
8971cfde9ec53a1a5d328739190bf3e2
|
256 megabytes
|
["6\n\n4\n\n1 8 25 2\n\n2\n\n1 1\n\n9\n\n9 8 3 4 2 7 1 5 6\n\n3\n\n8 2 1\n\n4\n\n24 7 16 7\n\n5\n\n22 6 22 4 22"]
|
PASSED
|
def solve():
n=int(input());l=[]
arr=[int(i) for i in input().split()]
if max(arr)<n:
print("NO")
return
for i in arr :
while i>0 :
if i<=n and i not in l :
l.append(i)
break
i//=2
if len(l)==n :
print("YES")
return
print("NO")
return
if __name__=="__main__" :
for x in range(int(input())) : solve()
|
1641825300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n3 1 2\n4 3 5 2 7 1 6"]
|
1b3ac752bc9c0b5e20a76f028d4b3c15
|
NoteFor $$$n = 3$$$, $$$[3,1,2]$$$ is a good permutation. Some of the subarrays are listed below. $$$3\text{ OR }1 = 3 \geq 2$$$ $$$(i = 1,j = 2)$$$ $$$3\text{ OR }1\text{ OR }2 = 3 \geq 3$$$ $$$(i = 1,j = 3)$$$ $$$1\text{ OR }2 = 3 \geq 2$$$ $$$(i = 2,j = 3)$$$ $$$1 \geq 1$$$ $$$(i = 2,j = 2)$$$ Similarly, you can verify that $$$[4,3,5,2,7,1,6]$$$ is also good.
|
A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) — $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.
|
For every test, output any good permutation of length $$$n$$$ on a separate line.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_001.jsonl
|
9361a5846ff68785004f14910285b5df
|
256 megabytes
|
["3\n1\n3\n7"]
|
PASSED
|
for i in range(int(input())):
n=int(input())
arr=[i for i in range(1,n+1)]
print(*arr)
|
1596983700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2", "10", "0", "21"]
|
fc892e4aac2d60e53f377a582f5ba7d3
|
NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10 — the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer.
|
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist.
|
If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any.
|
The first line of the input contains a single integer n (1 ≤ n ≤ 10100 000).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_032.jsonl
|
3ea1b6a92fd7fdfa64caf867b5e25d93
|
256 megabytes
|
["4", "11", "5", "33"]
|
PASSED
|
#!/usr/bin/python3
def can(s, n):
if n == 0:
return ""
cs = list(map(int, s))
was_over = [False for i in range(n)]
ans = [0 for i in range(n)]
i, j = 0, n - 1
last = int(n == len(cs) - 1)
while i < j:
need_a = last * 10 + cs[i]
need_b = last * 10 + cs[j]
if last == 1 and cs[i] == 9 and cs[j] == 0:
need_a = 9
need_b = 10
if abs(need_a - need_b) > 1:
return ""
if need_a == need_b + 1:
return ""
if need_a == need_b == 19:
return ""
if need_a >= 10:
ans[j] = 9
ans[i] = need_a - 9
else:
ans[j] = need_a
ans[i] = 0
if need_a >= 10 or was_over[i]:
cs[i + 1] = (cs[i + 1] - 1) % 10
if cs[i + 1] == 9:
was_over[i + 1] = True
last = (need_b == need_a + 1)
i += 1
j -= 1
if i == j:
need = last * 10 + cs[i]
if need % 2 != 0:
return ""
ans[i] = need // 2
if int("".join(map(str, ans))) + int("".join(map(str, reversed(ans)))) != int("".join(map(str, reversed(s)))):
return ""
return "".join(map(str, reversed(ans)))
s = "".join(reversed(input()))
if s[0] != '0':
t = can(s, len(s))
if t != "":
print(t)
exit(0)
if s[-1] == '1':
t = can(s, len(s) - 1)
if t != "":
print(t)
exit(0)
print(0)
|
1454835900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"]
|
35736970c6d629c2764eaf23299e0356
| null |
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
|
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.
|
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_018.jsonl
|
5af8bd66bea8e9b899a53b5739be05b1
|
256 megabytes
|
["2 2 2", "2 1 2", "1 1 3"]
|
PASSED
|
from collections import defaultdict
def main():
r, s, p = map(int, raw_input().split())
ans = [0.0] * 3
d = defaultdict(float)
nd = defaultdict(float)
d[r,s,p] = 1.0
for i in xrange(r + s + p):
for t, v in d.viewitems():
r, s, p = t
if not r and not s:
ans[2] += v
elif not s and not p:
ans[0] += v
elif not p and not r:
ans[1] += v
else:
k = 1.0 / (r * s + s * p + p * r)
if p and r:
nd[r-1,s,p] += v * r * p * k
if r and s:
nd[r,s-1,p] += v * r * s * k
if s and p:
nd[r,s,p-1] += v * s * p * k
d, nd = nd, d
nd.clear()
print "%.12f %.12f %.12f" % (ans[0], ans[1], ans[2])
main()
|
1430411400
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["4\n20\n112"]
|
c4ba92632e10b1710686930f0c4536fa
|
NoteIn first example, one of the sequences that fits the constraints is $$$[0, 2]$$$. Consider all its non-empty subsequences: $$$[0]$$$: the bitwise XOR of this subsequence is $$$0$$$; $$$[2]$$$: the bitwise XOR of this subsequence is $$$2$$$; $$$[0, 2]$$$: the bitwise XOR of this subsequence is $$$2$$$. The sum of all results is $$$4$$$, so it is the answer.In second example, one of the sequences that fits the constraints is $$$[0, \, 5, \, 5]$$$.In third example, one of the sequences that fits the constraints is $$$[5, \, 6, \, 7, \, 0, \, 2]$$$.
|
Once Divan analyzed a sequence $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $$$a$$$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $$$a$$$.A sequence $$$c$$$ is a subsequence of a sequence $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[1, \, 2, \, 3, \, 4]$$$, $$$[2, \, 4]$$$, and $$$[2]$$$ are subsequences of $$$[1, \, 2, \, 3, \, 4]$$$, but $$$[4, \, 3]$$$ and $$$[0]$$$ are not.Divan was very proud of his analysis, but now he lost the sequence $$$a$$$, and also the coziness value! However, Divan remembers the value of bitwise OR on $$$m$$$ contiguous subsegments of the sequence $$$a$$$. It turns out that each element of the original sequence is contained in at least one of these $$$m$$$ segments.Divan asks you to help find the coziness of the sequence $$$a$$$ using the information he remembers. If several coziness values are possible, print any.As the result can be very large, print the value modulo $$$10^9 + 7$$$.
|
For each test case print the coziness any suitable sequence $$$a$$$ modulo $$$10^9 + 7$$$.
|
The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each test case contains two integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the sequence and the number of contiguous segments whose bitwise OR values Divan remembers, respectively. The following $$$m$$$ lines describe the segments, one per line. Each segment is described with three integers $$$l$$$, $$$r$$$, and $$$x$$$ ($$$1 \le l \le r \le n$$$, $$$0 \le x \le 2^{30} - 1$$$) — the first and last elements of the segment and the bitwise OR of $$$a_l, a_{l + 1}, \ldots, a_r$$$, respectively. It is guaranteed that each element of the sequence is contained in at least one of the segments. It is guaranteed that there exists a sequence that satisfies all constraints. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_099.jsonl
|
7afc1d794ba22d9c50bd956eda4d0f07
|
256 megabytes
|
["3\n2 1\n1 2 2\n3 2\n1 3 5\n2 3 5\n5 4\n1 2 7\n3 3 7\n4 4 0\n4 5 2"]
|
PASSED
|
from sys import stdin
import math
from collections import deque
from heapq import heapify, heappop, heappush
from bisect import bisect_left, bisect_right
input = stdin.readline
power, mod = {}, 1000000007
def getpower(k):
if(k == 0):return 1
if(k == 1):return 2
if(k in power):
return power[k]
power[k] = (getpower(k // 2) * getpower(k - k // 2)) % mod
return power[k]
for _ in range(int(input())):
n, m = map(int, input().split())
arr, mod, easy = [], 1000000007, [0] * 30
powerval = getpower(n - 1)
easy = 0
for _ in range(m):
l, r, x = map(int, input().split())
easy = easy | x
value, total = 1, 0
for i in range(30):
if(easy % 2 == 0):
value = (value * 2) % mod
easy = easy // 2
continue
total += value
total = total % mod
value = value * 2
value = value % mod
easy = easy // 2
print((total * powerval)%mod)
|
1637925300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["000\n#0#", "5#1\n511\n55#", "-1", "##"]
|
cee7f95ec969034af7d53e89539a9726
|
NoteIn the third sample, there is no way to fill a cell with no empty neighbours.In the forth sample, Woll does not have to fill anything, so we should output the field from the input.
|
Physicist Woll likes to play one relaxing game in between his search of the theory of everything.Game interface consists of a rectangular n × m playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board. In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.
|
If there is no chance to win the game output the only number "-1" (without the quotes). Otherwise output any filling of the field by the figures in the following format: each figure should be represented by some digit and figures that touch each other by side should be represented by distinct digits. Every initially filled cell should be represented by "#".
|
First line contains integers n and m (1 ≤ n, m ≤ 1000) — the height and the width of the field correspondingly. Next n lines contain m symbols each. They represent the field in a natural way: j-th character of the i-th line is "#" if the corresponding cell is filled, and "." if it is empty.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_043.jsonl
|
e6b810c4a6387a4ea1401d98a7972d1b
|
256 megabytes
|
["2 3\n...\n#.#", "3 3\n.#.\n...\n..#", "3 3\n...\n.##\n.#.", "1 2\n##"]
|
PASSED
|
import sys
n,m = map(int,raw_input().split())
f = [list(raw_input()+'#') for _ in xrange(n)]+['#'*(m+1)]
for i in xrange(n):
for j in xrange(m):
if f[i][j]!='.': continue
c=(i%3)+(j%3)*3
f[i][j]=c
if f[i][j+1]=='.':
f[i][j+1]=c
elif f[i+1][j]=='.':
f[i+1][j]=c
else:
if j and f[i][j-1]!='#': f[i][j]=f[i][j-1]
elif i and f[i-1][j]!='#': f[i][j]=f[i-1][j]
elif f[i][j+1]!='#': f[i][j]=f[i][j+1]
else:
print -1
sys.exit(0)
for l in f[:-1]:
print ''.join(map(str,l[:-1]))
|
1306077000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n3\n0\n2\n31072"]
|
0601e3636b5d5b6ad0c8c1abb7f83d82
|
NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\ \& \ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements.
|
You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.
|
For each test case, output a single integer — the answer to the problem.
|
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 two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 2 \cdot 10^5$$$) — the description of the array.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_100.jsonl
|
2cc0938b4e7eafae8f0af4725db60ea6
|
256 megabytes
|
["5\n1 2\n2 8\n4 5\n1 5\n100000 200000"]
|
PASSED
|
psum = [[0] * 18 for _ in range(2 * 10 ** 5 + 1)]
for i in range(1, 2 * 10 ** 5 + 1):
for j in range(18):
psum[i][j] = psum[i - 1][j] + ((i >> j) & 1) # The reason for &1 is to use only the significant bit.
tc = int(input())
for _ in range(tc):
L, R = map(int, input().split())
max_value = 0
for i in range(18):
max_value = max(max_value, psum[R][i] - psum[L - 1][i])
print((R - L + 1) - max_value)
|
1640356500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4", "-1"]
|
5337df1fb8a9b96ab7b66aa197a5b910
|
NoteIn the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
|
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
|
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
|
The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m (). The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all m relations.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_052.jsonl
|
72c0d3fdbaa0b2aa0260c96af082236d
|
256 megabytes
|
["4 5\n2 1\n1 3\n2 3\n4 2\n4 3", "3 2\n1 2\n3 2"]
|
PASSED
|
def g(k):
p = [[] for i in range(n)]
d = [0] * n
for x, y in t[:k]:
p[x].append(y)
d[y] += 1
x = 0
for y in range(n):
if d[y] == 0:
if x: return 0
x = y
while x:
q, x = p[x], 0
for y in q:
d[y] -= 1
if d[y] == 0:
if x: return 0
x = y
return 1
f = lambda: map(int, input().split())
n, m = f()
t = [tuple(f()) for i in range(m)]
n += 1
m += 1
l, r = 1, m
while l < r:
s = l + r >> 1
if g(s): r = s
else: l = s + 1
print(-1 if r == m else l)
|
1458318900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1", "3", "1"]
|
71be4cccd3b8c494ad7cc2d8a00cf5ed
|
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
|
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
|
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
|
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_001.jsonl
|
dca683145e7ebb13458fa3e446bc2c5b
|
256 megabytes
|
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
|
PASSED
|
line1 = input()
busRoutes = int(line1.split()[0])
startTime = int(line1.split()[1])
arrivals = []
intervals = []
for x in range(busRoutes):
line = input()
arrival = int(line.split()[0])
interval = int(line.split()[1])
if arrival in arrivals and interval in intervals:
arrivals.append(0)
intervals.append(0)
else:
arrivals.append(arrival)
intervals.append(interval)
selectedBus = 0
time = startTime
countNonZero = 0
for i in range(len(arrivals)):
if not(arrivals[i] == 0 and intervals[i] == 0):
countNonZero += 1
if countNonZero >= 2:
break
if countNonZero == 1:
selectedBus = 1
while selectedBus == 0:
for i in range(len(arrivals)):
if arrivals[i] == 0 and intervals[i] == 0:
continue
while arrivals[i] < time:
arrivals[i] = arrivals[i] + intervals[i]
if arrivals[i] != time:
continue
selectedBus = i + 1
break
if selectedBus == 0:
minimum = 0
for i in range(len(arrivals)):
if minimum == 0 and arrivals[i] > 0:
minimum = arrivals[i]
elif arrivals[i] > 0 and arrivals[i] < minimum:
minimum = arrivals[i]
time = minimum
print(selectedBus)
|
1555164300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["999 998\n\n999 997\n\n<...>\n\n999 26"]
|
3d38584c3bb29e6f84546643b1be8026
|
NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example.
|
This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are $$$666$$$ black rooks and $$$1$$$ white king on the chess board of size $$$999 \times 999$$$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $$$(x, y)$$$, it can move to the square $$$(nx, ny)$$$ if and only $$$\max (|nx - x|, |ny - y|) = 1$$$ , $$$1 \leq nx, ny \leq 999$$$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes $$$2000$$$ turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.
|
After getting king checked, you program should terminate immediately without printing anything extra.
|
In the beginning your program will receive $$$667$$$ lines from input. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x, y \leq 999$$$) — the piece's coordinates. The first line contains the coordinates of the king and the next $$$666$$$ contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_001.jsonl
|
787e57cf2e8286722946ad3c7dac7317
|
256 megabytes
|
["999 999\n1 1\n1 2\n2 1\n2 2\n1 3\n2 3\n<...>\n26 13\n26 14\n26 15\n26 16\n\n1 700 800\n\n2 1 2\n\n<...>\n\n-1 -1 -1"]
|
PASSED
|
import sys
kx, ky = [int(z) for z in sys.stdin.readline().split()]
lx = [0] * 667
ly = [0] * 667
bp = []
for i in range(1001):
bp.append([0 for z in range(1001)])
for i in range(1, 667):
lx[i], ly[i] = [int(z) for z in sys.stdin.readline().split()]
bp[lx[i]][ly[i]] = 1
los = [0] * 4
for i in range(1, 667):
sta = 0
if lx[i] > kx:
sta += 1
if ly[i] > ky:
sta += 2
los[sta] += 1
tkx, tky = 500, 500
ntut = False
stnse = True
while True:
if kx == tkx and ky == tky:
ntut = True
if ntut:
sos = [0, 1, 2, 3]
sos.sort(key=lambda z: los[z])
tkx = (1 - sos[0] % 2) * 998 + 1
tky = (1 - sos[0] // 2) * 998 + 1
ntut = False
stnse = False
dkx = 0
dky = 0
if tkx > kx:
dkx = 1
elif tkx < kx:
dkx = -1
if tky > ky:
dky = 1
elif tky < ky:
dky = -1
if bp[kx+dkx][ky+dky] == 1:
dky = 0
kx += dkx
ky += dky
print(kx, ky, flush=True)
l, nlx, nly = [int(z) for z in sys.stdin.readline().split()]
soa = l + nlx + nly
if soa == 0 or soa == -3:
exit(0)
if stnse:
std = 0
if lx[l] > kx:
std += 1
if ly[l] > ky:
std += 2
sta = 0
if nlx > kx:
sta += 1
if nly > ky:
sta += 2
los[std] -= 1
los[sta] += 1
bp[lx[l]][ly[l]] = 0
bp[nlx][nly] = 1
lx[l] = nlx
ly[l] = nly
|
1547390100
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["2", "0"]
|
852e1d776c560a8720d4e9f1762b255f
|
NoteThe graph from the first sample is shown below. Dashed edges have weight $$$0$$$, other edges have weight $$$1$$$. One of the minimum spanning trees is highlighted in orange and has total weight $$$2$$$. In the second sample, all edges have weight $$$0$$$ so any spanning tree has total weight $$$0$$$.
|
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.It is an undirected weighted graph on $$$n$$$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $$$0$$$ or $$$1$$$; exactly $$$m$$$ edges have weight $$$1$$$, and all others have weight $$$0$$$.Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
|
Output a single integer, the weight of the minimum spanning tree of the graph.
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$$$), the number of vertices and the number of edges of weight $$$1$$$ in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$), the endpoints of the $$$i$$$-th edge of weight $$$1$$$. It is guaranteed that no edge appears twice in the input.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_003.jsonl
|
116269a51d8f0ae9a31b6d6ec505742d
|
256 megabytes
|
["6 11\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6", "3 0"]
|
PASSED
|
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1]*n
def size(self, x: int) -> int:
return -self.nodes[self.find(x)]
def find(self, x: int) -> int:
if self.nodes[x] < 0:
return x
else:
self.nodes[x] = self.find(self.nodes[x])
return self.nodes[x]
def unite(self, x: int, y: int) -> bool:
root_x, root_y, nodes = self.find(x), self.find(y), self.nodes
if root_x != root_y:
if nodes[root_x] > nodes[root_y]:
root_x, root_y = root_y, root_x
nodes[root_x] += nodes[root_y]
nodes[root_y] = root_x
return root_x != root_y
if __name__ == '__main__':
import sys
from collections import Counter
n, m = map(int, input().split())
rev_edges = [[] for _ in range(n)]
for s, t in (map(int, l.split()) for l in sys.stdin):
if s < t:
rev_edges[t-1].append(s-1)
else:
rev_edges[s-1].append(t-1)
uf = UnionFind(n)
find, unite, size = uf.find, uf.unite, uf.size
zero_union = set()
for v in range(n):
cnt = Counter()
for src in rev_edges[v]:
cnt[find(src)] += 1
for zero_v in zero_union:
root = find(zero_v)
if size(root) > cnt[root]:
unite(root, v)
zero_union = set(find(v_) for v_ in zero_union) | {find(v)}
print(len(zero_union)-1)
|
1573052700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["5\n1 2 3 5", "22\n2 4 6 22\n14 18 10 16"]
|
5e7b4d1e11628152e33d3e18e30f4530
|
NoteFor the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since .
|
Dreamoon likes to play with sets, integers and . is defined as the largest positive integer that divides both a and b.Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, .Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
|
On the first line print a single integer — the minimal possible m. On each of the next n lines print four space separated integers representing the i-th set. Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
|
The single line of the input contains two space separated integers n, k (1 ≤ n ≤ 10 000, 1 ≤ k ≤ 100).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_010.jsonl
|
4a06140d6ae1016f81af4d9242313e61
|
256 megabytes
|
["1 1", "2 2"]
|
PASSED
|
load = [int(i) for i in input().split()]
n = load[0]
k = load[1]
print(k * (6 * n - 1))
for i in range(1, n + 1):
buff = ""
buff += str(k * (6 * i - 5)) + ' '
buff += str(k * (6 * i - 3)) + ' '
buff += str(k * (6 * i - 2)) + ' '
buff += str(k * (6 * i - 1)) + ' '
print(buff)
|
1413122400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["2", "-1"]
|
8d4e493783fca1d8eede44af7557f4bd
| null |
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
|
Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
|
The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively. Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_075.jsonl
|
77777aea7b72a9801f59b6909013f7fd
|
512 megabytes
|
["4 5\n11..2\n#..22\n#.323\n.#333", "1 5\n1#2#3"]
|
PASSED
|
import sys
range = xrange
input = raw_input
inp = sys.stdin.read().split(); ii = 0
n = int(inp[ii]); ii += 1
m = int(inp[ii]); ii += 1
M = [0]*(m + 2)
for _ in range(n):
M.append(0)
for c in inp[ii]:
if c == '#':
M.append(0)
elif c == '.':
M.append(1)
else:
M.append(ord(c) - 47)
ii += 1
M.append(0)
M += [0]*(m + 2)
n += 2
m += 2
A = []
B = []
C = []
for i in range(n*m):
if M[i] == 2:
A.append(i)
elif M[i] == 3:
B.append(i)
elif M[i] == 4:
C.append(i)
inf = 10**8
Adist = [inf]*(n*m)
Bdist = [inf]*(n*m)
Cdist = [inf]*(n*m)
def dister(bfs, dist):
for node in bfs:
dist[node] = 0
for node in bfs:
d = dist[node] + 1
for nei in node - 1, node + 1, node - m, node + m:
if M[nei] and dist[nei] == inf:
dist[nei] = d
bfs.append(nei)
dister(list(A), Adist)
dister(list(B), Bdist)
dister(list(C), Cdist)
besta = inf
for i in range(n*m):
besta = min(besta, Adist[i] + Bdist[i] + Cdist[i] - 2)
def opter(dist1, dist2):
besta = inf
for i in range(n*m):
besta = min(besta, dist1[i] + dist2[i] - 1)
return besta
besta1 = opter(Adist, Bdist)
besta2 = opter(Adist, Cdist)
besta3 = opter(Bdist, Cdist)
alt1 = besta
alt2 = besta1 + besta2
alt3 = besta1 + besta3
alt4 = besta2 + besta3
alt = min(alt1, alt2, alt3, alt4)
print alt if alt < 10**7 else -1
|
1445763600
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
5 seconds
|
["56\n28\n4\n60\n0"]
|
f2bcbbfc8062aebd0545497d815f8827
|
NoteThe following explanation assumes $$$b = [2, 1]$$$ and $$$c=[2, 3, 4]$$$ (as in the sample).Examples of arrays $$$a$$$ that are not good: $$$a = [3, 2, 3]$$$ is not good because $$$a_1 > c_1$$$; $$$a = [0, -1, 3]$$$ is not good because $$$a_2 < 0$$$. One possible good array $$$a$$$ is $$$[0, 2, 4]$$$. We can show that no operation has any effect on this array, so $$$F(a, b) = a_1 = 0$$$.Another possible good array $$$a$$$ is $$$[0, 1, 4]$$$. In a single operation with $$$i = 1$$$, we set $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ and $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. So, after a single operation with $$$i = 1$$$, $$$a$$$ becomes equal to $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. We can show that no operation has any effect on this array, so $$$F(a, b) = -\frac{1}{2}$$$.
|
This is the hard version of the problem. The only difference is that in this version $$$1 \le q \le 10^5$$$. You can make hacks only if both versions of the problem are solved.There is a process that takes place on arrays $$$a$$$ and $$$b$$$ of length $$$n$$$ and length $$$n-1$$$ respectively. The process is an infinite sequence of operations. Each operation is as follows: First, choose a random integer $$$i$$$ ($$$1 \le i \le n-1$$$). Then, simultaneously set $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ and $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ without any rounding (so values may become non-integer). See notes for an example of an operation.It can be proven that array $$$a$$$ converges, i. e. for each $$$i$$$ there exists a limit $$$a_i$$$ converges to. Let function $$$F(a, b)$$$ return the value $$$a_1$$$ converges to after a process on $$$a$$$ and $$$b$$$.You are given array $$$b$$$, but not array $$$a$$$. However, you are given a third array $$$c$$$. Array $$$a$$$ is good if it contains only integers and satisfies $$$0 \leq a_i \leq c_i$$$ for $$$1 \leq i \leq n$$$.Your task is to count the number of good arrays $$$a$$$ where $$$F(a, b) \geq x$$$ for $$$q$$$ values of $$$x$$$. Since the number of arrays can be very large, print it modulo $$$10^9+7$$$.
|
Output $$$q$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th query, i. e. the number of good arrays $$$a$$$ where $$$F(a, b) \geq x_i$$$ modulo $$$10^9+7$$$.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$). The second line contains $$$n$$$ integers $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$). The third line contains $$$n-1$$$ integers $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$). The fourth line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$). The fifth line contains $$$q$$$ space separated integers $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,900 |
train_092.jsonl
|
902ab884f7a998be7f7982c5911769b4
|
256 megabytes
|
["3\n2 3 4\n2 1\n5\n-1 0 1 -100000 100000"]
|
PASSED
|
def solve():
MOD = 10**9+7
n = int(input())
c = list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
q = int(input())
queries = list(map(int, input().split()))
maxans = 1
for c1 in c:
maxans = maxans * (c1+1) % MOD
ans = {}
for i in range(1, n):
b[i] += b[i-1]
s = lb = 0
for i in range(1, n):
s -= b[i]
lb = min(lb, s//(i+1))
s = ub = c[0]
for i in range(n):
s += c[i] - b[i]
ub = min(ub, s//(i+1))
for x in queries:
if x <= lb:
print(maxans)
elif x > ub:
print(0)
elif x in ans:
print(ans[x])
else:
dp0 = [1] * 10002
dp0[0] = 0
bd = 0
for i in range(n):
dp1 = [0] * 10002
bd += b[i] + x
for j in range(max(bd, 0), 10001):
dp1[j+1] = (dp1[j] + dp0[j+1] - dp0[max(j-c[i], 0)]) % MOD
dp0 = dp1[:]
a = dp0[-1]
ans[x] = a
print(a)
import sys
input = lambda: sys.stdin.readline().rstrip()
solve()
|
1624635300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0\n1\n-1\n3\n4"]
|
84c0f17a45826a6e43d1f4717e62c194
|
NoteIn the first test case, the two strings are already equal, so we don't have to perform any operations.In the second test case, we can perform a single operation selecting the second candle to transform $$$01$$$ into $$$11$$$.In the third test case, it's impossible to perform any operations because there are no lit candles to select.In the fourth test case, we can perform the following operations to transform $$$a$$$ into $$$b$$$: Select the $$$7$$$-th candle: $$$100010{\color{red}1}11\to 011101{\color{red} 1}00$$$. Select the $$$2$$$-nd candle: $$$0{\color{red} 1}1101100\to 1{\color{red} 1}0010011$$$. Select the $$$1$$$-st candle: $$${\color{red}1}10010011\to {\color{red}1}01101100$$$. In the fifth test case, we can perform the following operations to transform $$$a$$$ into $$$b$$$: Select the $$$6$$$-th candle: $$$00101{\color{red}1}011\to 11010{\color{red}1}100$$$ Select the $$$2$$$-nd candle: $$$1{\color{red}1}0101100\to 0{\color{red}1}1010011$$$ Select the $$$8$$$-th candle: $$$0110100{\color{red}1}1\to 1001011{\color{red}1}0$$$ Select the $$$7$$$-th candle: $$$100101{\color{red}1}10\to 011010{\color{red}1}01$$$
|
There are $$$n$$$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $$$s$$$, where the $$$i$$$-th candle is lit if and only if $$$s_i=1$$$. Initially, the candle lights are described by a string $$$a$$$. In an operation, you select a candle that is currently lit. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).You would like to make the candles look the same as string $$$b$$$. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.
|
For each test case, output the minimum number of operations required to transform $$$a$$$ to $$$b$$$, or $$$-1$$$ if it's impossible.
|
The first line contains an integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the number of candles. The second line contains a string $$$a$$$ of length $$$n$$$ consisting of symbols 0 and 1 — the initial pattern of lights. The third line contains a string $$$b$$$ of length $$$n$$$ consisting of symbols 0 and 1 — the desired pattern of lights. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_100.jsonl
|
ad2c6539a8ca5a7fd137ab7ef9c01165
|
256 megabytes
|
["5\n5\n11010\n11010\n2\n01\n11\n3\n000\n101\n9\n100010111\n101101100\n9\n001011011\n011010101"]
|
PASSED
|
import decimal
import heapq
import math
import os
import sys
from collections import Counter, deque
from io import BytesIO, IOBase
import bisect
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
def isPrime(n):
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 lcm(a, b): return (a * b) // math.gcd(a, b)
def ints_get(): return map(int, input().strip().split())
def list_get(): return list(map(int, sys.stdin.readline().strip().split()))
def chars_get(): return list(map(str, sys.stdin.readline().strip().split()))
def ipn(): return int(input())
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
# ******************************************************#
# **************** code starts here ********************#
# ******************************************************#
def main():
for _ in range(ipn()):
n = ipn()
a = [int(x) for x in input()]
b = [int(x) for x in input()]
p = a.count(1)
q = b.count(1)
w, e, f = 0, 0, 0
for i in range(n):
if a[i] != b[i]:
e += 1
elif a[i] == b[i] == 1:
w += 1
if a[i] == b[i]:
f += 1
o = 10**7
if p == q:
o = min(o, e)
if q == n - p + 1:
if w > 0 and f % 2 != 0:
o = min(o, f)
if o < 10**7:
print(o)
else:
print(-1)
return
if __name__ == "__main__":
main()
|
1640356500
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["6\n0\n36\n4"]
|
e4685bb0a1bf8c2da326cd0e5b8f4fe7
|
NoteIn the first test case, since all the numbers are equal, whatever permutation we take, the sequence is good. There are a total of $$$6$$$ permutations possible with numbers from $$$1$$$ to $$$3$$$: $$$[1,2,3]$$$, $$$[1,3,2]$$$, $$$[2,1,3]$$$, $$$[2,3,1]$$$, $$$[3,1,2]$$$, $$$[3,2,1]$$$.In the second test case, it can be proved that no permutation exists for which the sequence is good.In the third test case, there are a total of $$$36$$$ permutations for which the sequence is good. One of them is the permutation $$$[1,5,4,2,3]$$$ which results in the sequence $$$s=[0,0,3,2,0]$$$. This is a good sequence because $$$ s_1 = s_2 \: \& \: s_3 \: \& \: s_4 \: \& \: s_5 = 0$$$, $$$ s_1 \: \& \: s_2 = s_3 \: \& \: s_4 \: \& \: s_5 = 0$$$, $$$ s_1 \: \& \: s_2 \: \& \: s_3 = s_4 \: \& \: s_5 = 0$$$, $$$ s_1 \: \& \: s_2 \: \& \: s_3 \: \& \: s_4 = s_5 = 0$$$.
|
A sequence of $$$n$$$ non-negative integers ($$$n \ge 2$$$) $$$a_1, a_2, \dots, a_n$$$ is called good if for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following condition holds true: $$$$$$a_1 \: \& \: a_2 \: \& \: \dots \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: \dots \: \& \: a_n,$$$$$$ where $$$\&$$$ denotes the bitwise AND operation.You are given an array $$$a$$$ of size $$$n$$$ ($$$n \geq 2$$$). Find the number of permutations $$$p$$$ of numbers ranging from $$$1$$$ to $$$n$$$, for which the sequence $$$a_{p_1}$$$, $$$a_{p_2}$$$, ... ,$$$a_{p_n}$$$ is good. Since this number can be large, output it modulo $$$10^9+7$$$.
|
Output $$$t$$$ lines, where the $$$i$$$-th line contains the number of good permutations in the $$$i$$$-th test case modulo $$$10^9 + 7$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), denoting the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_088.jsonl
|
69cf754c2eb7e513e7f069f278a45395
|
256 megabytes
|
["4\n3\n1 1 1\n5\n1 2 3 4 5\n5\n0 2 0 3 0\n4\n1 3 5 1"]
|
PASSED
|
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
import math
def solve():
n = int(input())
arr = list(map(int, input().split()))
x = arr[0]
for i in range(1, n):
x &= arr[i]
count = arr.count(x)
if count < 2:
print(0)
return
print((count * (count - 1) * (math.factorial(n - 2))) % num)
num = int(1E9 + 7)
for _ in range(int(input())):
solve()
|
1618151700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0", "1", "impossible"]
|
bd5912fe2c5c37658f28f6b159b39645
|
NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.
|
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
|
Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.
|
First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_006.jsonl
|
dfb3d3b97813938b1ca9d196880963f2
|
256 megabytes
|
["yandex\n6", "yahoo\n5", "google\n7"]
|
PASSED
|
s = input()
k = int(input())
t = frozenset(s)
if len(s) < k:
print("impossible")
exit()
print(max(k - len(t), 0))
|
1503592500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["1\n2 \n3\n2 2 90 \n1\n4999999937 \n1\n4998207083"]
|
f8d064c90f1f2b4a18386795dbcd9cb9
| null |
You are given an integer $$$n$$$ ($$$n > 1$$$).Your task is to find a sequence of integers $$$a_1, a_2, \ldots, a_k$$$ such that: each $$$a_i$$$ is strictly greater than $$$1$$$; $$$a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$$$ (i. e. the product of this sequence is $$$n$$$); $$$a_{i + 1}$$$ is divisible by $$$a_i$$$ for each $$$i$$$ from $$$1$$$ to $$$k-1$$$; $$$k$$$ is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer: in the first line, print one positive integer $$$k$$$ — the maximum possible length of $$$a$$$. In the second line, print $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ — the sequence of length $$$k$$$ satisfying the conditions from the problem statement. If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{10}$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^{10}$$$ ($$$\sum n \le 10^{10}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| null |
train_004.jsonl
|
8ef7814241813f767fdefbc32a16c695
|
256 megabytes
|
["4\n2\n360\n4999999937\n4998207083"]
|
PASSED
|
def decompose(number):
prime_factors = []
while number % 2 == 0:
prime_factors.append(2)
number = number / 2
for i in range(3, int(number**(1/2)) + 1, 2):
while number % i == 0:
prime_factors.append(int(i))
number = number / i
if number > 2:
prime_factors.append(int(number))
return prime_factors
def check_double(A):
S = set(A)
my_dict = {x: A.count(x) for x in S if A.count(x)>1}
try:
return max(my_dict.keys(), key=(lambda k: my_dict[k]))
except ValueError:
return False
def prod(L):
result = 1
for x in L:
result *= x
return result
for _ in range(int(input())):
n = int(input())
prems = decompose(n)
comp = check_double(prems)
if comp == False:
print(1, n, sep='\n')
else:
remainder = int(comp*prod([prem for prem in prems if prem != comp]))
count = prems.count(comp)
print(count, end='\n')
for k in range(count-1):
print(comp, end=' ')
print(remainder, end='\n')
|
1606228500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["Yes\nNo\nYes\nYes\nNo"]
|
afce38aa7065da88d824d1d981b5b338
|
NoteFor $$$1$$$st case: We must select element $$$999$$$, and the sum is odd.For $$$2$$$nd case: We must select element $$$1000$$$, so overall sum is not odd.For $$$3$$$rd case: We can select element $$$51$$$.For $$$4$$$th case: We must select both elements $$$50$$$ and $$$51$$$ — so overall sum is odd.For $$$5$$$th case: We must select all elements — but overall sum is not odd.
|
Shubham has an array $$$a$$$ of size $$$n$$$, and wants to select exactly $$$x$$$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.
|
For each test case, print "Yes" or "No" depending on whether it is possible to choose $$$x$$$ elements such that their sum is odd. You may print every letter in any case you want.
|
The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \le x \le n \le 1000)$$$ — the length of the array and the number of elements you need to choose. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1000)$$$ — elements of the array.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_006.jsonl
|
a1e5ac91a1d94a564c71c75a94ee4ad1
|
256 megabytes
|
["5\n1 1\n999\n1 1\n1000\n2 1\n51 50\n2 2\n51 50\n3 3\n101 102 103"]
|
PASSED
|
from sys import stdin,stdout
for __ in range(int(stdin.readline())):
n,x = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
o = 0
e = 0
for i in range(n):
if a[i]%2 == 1:
o+=1
else:
e+=1
f=0
l = min(x,o)
for i in range(1,l+1,2):
h = x-i
if (h <= e) :
f=1
if f==1:
print("Yes")
else:
print("No")
|
1590935700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "6"]
|
2475df43379ffd450fa661927ae3b734
|
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
|
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
|
Output one number, representing how many palindrome pairs there are in the array.
|
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_003.jsonl
|
ab549f3abda40bede48f94f632480b6f
|
256 megabytes
|
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
|
PASSED
|
from collections import Counter
n = int(input())
strings = []
for i in range(0,n):
counter = { x: 0 for x in range(ord('a'), ord('z')+1) }
napis = input()
for val in napis:
counter[ord(val)] = (counter[ord(val)] + 1) % 2
napis = ""
for key, val in counter.items():
if val != 0:
napis+=chr(key)
strings.append(napis)
c = Counter(strings)
strings = sorted(c.most_common(), key=lambda i: i[0])
#print(strings)
count = 0
for key, val in strings:
if val > 1:
count += val*(val-1)/2
for charInt in range(ord('a'), ord('z')+1):
char = chr(charInt)
copy = {}
for key, val in strings:
if char in key:
copy[key.replace(char, "")] = copy.get(key.replace(char, ""), 0) + val
#print(copy)
for key, val in strings:
if copy.get(key,0) != 0:
count+=val * copy[key]
#print("pokrywa : ", key, " ", val*copy[key])
print(int(count))
|
1537612500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["0.500000000", "3.000000000"]
|
c0e18f6105f4b8129ebd73bbd12e904d
| null |
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n.This time the Little Elephant has permutation p1, p2, ..., pn. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the ai-th and the bi-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements.Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed.We'll call a pair of integers i, j (1 ≤ i < j ≤ n) an inversion in permutatuon p1, p2, ..., pn, if the following inequality holds: pi > pj.
|
In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 1000, n > 1) — the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n — the initial permutation. Next m lines each contain two integers: the i-th line contains integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the positions of elements that were changed during the i-th move.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,600 |
train_029.jsonl
|
901e74fda5ee93a2bbac133066882293
|
256 megabytes
|
["2 1\n1 2\n1 2", "4 3\n1 3 2 4\n1 2\n2 3\n1 4"]
|
PASSED
|
n, m = map(int, raw_input().split())
s = map(int, raw_input().split())
dp = [[0.0] * 2000 for i in xrange(2000)]
for i in xrange(n) :
for j in xrange(n) :
if s[i] > s[j] : dp[i][j] = 1.0
else : dp[i][j] = 0.0
for i in xrange(m) :
a, b = map(int, raw_input().split())
a = a - 1
b = b - 1
dp[a][b] = dp[b][a] = 0.5
for j in xrange(n) :
if j != b and j != a:
dp[j][a] = dp[j][b] = (dp[j][a] + dp[j][b]) / 2
dp[a][j] = dp[b][j] = (dp[a][j] + dp[b][j]) / 2
ans = 0.0
for i in xrange(n) :
for j in xrange(i + 1, n) :
ans += dp[i][j]
print "%.9f" % ans
|
1356190200
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second
|
["? 0 0\n? 10 1\n! 1\n? 0 0\n? 3 4\n? 2 5\n! 2\n? 2 4\n? 2 5\n? 3 10\n? 9 1\n! 3"]
|
eab8e5ac203d9f10c893ea35d249fe84
|
NoteIn the first test, you should play $$$3$$$ games with Petya's numbers $$$1$$$, $$$2$$$ and $$$3$$$.In the first game, Petya will answer "x" (without quotes) to any question, because $$$(x \bmod 1) = 0$$$ for any integer $$$x$$$. In the second game, if you will ask pair $$$(0, 0)$$$, the answer will be "x" (without quotes), because $$$(0 \bmod 2) \geq (0 \bmod 2)$$$. But if you will ask pair $$$(2, 5)$$$, the answer will be "y" (without quotes), because $$$(2 \bmod 2) < (5 \bmod 2)$$$, because $$$(2 \bmod 2) = 0$$$ and $$$(5 \bmod 2) = 1$$$.
|
This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number $$$a$$$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $$$(x, y)$$$. Petya will answer him: "x", if $$$(x \bmod a) \geq (y \bmod a)$$$. "y", if $$$(x \bmod a) < (y \bmod a)$$$. We define $$$(x \bmod a)$$$ as a remainder of division $$$x$$$ by $$$a$$$.Vasya should guess the number $$$a$$$ using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality $$$1 \leq a \leq 10^9$$$.Help Vasya playing this game and write a program, that will guess the number $$$a$$$.
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_010.jsonl
|
bd1b141da7da481011b7fda3428ec4f3
|
256 megabytes
|
["start\nx\nx\nstart\nx\nx\ny\nstart\nx\nx\ny\ny\nend"]
|
PASSED
|
import sys
def solve(x, y):
global aaa
if x%aaa>=y%aaa: return "x"
else: return "y"
while True:
cnt = 0
op=input()
if op=="end": break
left,right=1,2
while True:
cnt += 1
print("?", left, right)
sys.stdout.flush()
# result=solve(left, right)
# print(result)
result = input()
if result=="x": break
else:
left*=2
right*=2
while left<right:
mid = (left+right)//2
cnt += 1
print("?", left-1, mid)
sys.stdout.flush()
# result=solve(left-1, mid)
# print(result)
result = input()
if result=="x":
right=mid
else:
left=mid+1
print("!", left)
sys.stdout.flush()
|
1548167700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n6\n6"]
|
f2b2d12ab1c8a511d2ca550faa9768d4
|
NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$.
|
Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$.
|
For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,500 |
train_097.jsonl
|
b808754e754932416a428be3448ff7ae
|
256 megabytes
|
["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"]
|
PASSED
|
#!/usr/bin/env PyPy3
from collections import Counter, defaultdict, deque
import itertools
import re
import math
from functools import reduce
import operator
import bisect
from heapq import *
import functools
mod=998244353
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
t = int(input())
for _ in range(t):
n,k=map(int,input().split())
v = list(map(int,input().split()))
ans = 1
for i in range(1,k+1):
ans *= i
ans %= mod
cnt = 0
for i in range(n-k,n):
if v[i] > 0:
print(0)
break
else:
for i in range(n-k)[::-1]:
if v[i] > 0:
if v[i] > i:
print(0)
break
elif v[i] == 0:
ans *= k + 1
ans %= mod
else:
ans *= (k + 1 + i)
ans %= mod
else:
print(ans)
|
1652020500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2 3 6\n4 6 2 10\n9 0 7 3\n2 8 8 2\n\n\n1 1\n1 2\n1 3\n2 3\n2 4\n3 4\n4 4\n\n1 1\n2 1\n3 1\n3 2\n3 3\n3 4\n4 4\n\n1 1\n1 2\n1 3\n1 4\n2 4\n3 4\n4 4"]
|
8b0ec419248bb98b5e0c3d991c7e14fb
|
NoteThe duck's three journeys are illustrated below.$$$1 + 2 + 3 + 2 + 10 + 3 + 2 = 23$$$ $$$1 + 4 + 9 + 0 + 7 + 3 + 2 = 26$$$ $$$1 + 2 + 3 + 6 + 10 + 3 + 2 = 27$$$
|
This is an interactive problem.Omkar has just come across a duck! The duck is walking on a grid with $$$n$$$ rows and $$$n$$$ columns ($$$2 \leq n \leq 25$$$) so that the grid contains a total of $$$n^2$$$ cells. Let's denote by $$$(x, y)$$$ the cell in the $$$x$$$-th row from the top and the $$$y$$$-th column from the left. Right now, the duck is at the cell $$$(1, 1)$$$ (the cell in the top left corner) and would like to reach the cell $$$(n, n)$$$ (the cell in the bottom right corner) by moving either down $$$1$$$ cell or to the right $$$1$$$ cell each second.Since Omkar thinks ducks are fun, he wants to play a game with you based on the movement of the duck. First, for each cell $$$(x, y)$$$ in the grid, you will tell Omkar a nonnegative integer $$$a_{x,y}$$$ not exceeding $$$10^{16}$$$, and Omkar will then put $$$a_{x,y}$$$ uninteresting problems in the cell $$$(x, y)$$$. After that, the duck will start their journey from $$$(1, 1)$$$ to $$$(n, n)$$$. For each cell $$$(x, y)$$$ that the duck crosses during their journey (including the cells $$$(1, 1)$$$ and $$$(n, n)$$$), the duck will eat the $$$a_{x,y}$$$ uninteresting problems in that cell. Once the duck has completed their journey, Omkar will measure their mass to determine the total number $$$k$$$ of uninteresting problems that the duck ate on their journey, and then tell you $$$k$$$.Your challenge, given $$$k$$$, is to exactly reproduce the duck's path, i. e. to tell Omkar precisely which cells the duck crossed on their journey. To be sure of your mastery of this game, Omkar will have the duck complete $$$q$$$ different journeys ($$$1 \leq q \leq 10^3$$$). Note that all journeys are independent: at the beginning of each journey, the cell $$$(x, y)$$$ will still contain $$$a_{x,y}$$$ uninteresting tasks.
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_009.jsonl
|
baa0c91fa2f308c557ca8c9110c8c716
|
256 megabytes
|
["4\n\n\n\n\n3\n23\n\n\n\n\n\n\n\n26\n\n\n\n\n\n\n\n27"]
|
PASSED
|
import sys
n = int(input())
row = []
for x in range(0,n):
row.append(0)
for r in row:
print(r, end = ' ')
print()
sys.stdout.flush()
for y in range(2,n+1):
for x in range(0,n-1):
row[x] = row[x+1]+pow(2,2*n-2-x-y)
print(row[x], end=' ')
if(y!=n): print(0)
else: print(2**(n-1)-1)
sys.stdout.flush()
q = int(input())
for t in range(0,q):
a = int(input())
c = [1,1]
print(*c)
for i in range(2*n-3,-1,-1):
if(a&pow(2,i)): c[0]+=1
else: c[1]+=1
print(*c)
|
1597588500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["124124", "100100"]
|
84650ac76888fa6d17bc0283b0c0ab0c
|
NoteIn first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
|
Alice became interested in periods of integer numbers. We say positive $$$X$$$ integer number is periodic with length $$$L$$$ if there exists positive integer number $$$P$$$ with $$$L$$$ digits such that $$$X$$$ can be written as $$$PPPP…P$$$. For example:$$$X = 123123123$$$ is periodic number with length $$$L = 3$$$ and $$$L = 9$$$$$$X = 42424242$$$ is periodic number with length $$$L = 2,L = 4$$$ and $$$L = 8$$$$$$X = 12345$$$ is periodic number with length $$$L = 5$$$For given positive period length $$$L$$$ and positive integer number $$$A$$$, Alice wants to find smallest integer number $$$X$$$ strictly greater than $$$A$$$ that is periodic with length L.
|
One positive integer number representing smallest positive number that is periodic with length $$$L$$$ and is greater than $$$A$$$.
|
First line contains one positive integer number $$$L \ (1 \leq L \leq 10^5)$$$ representing length of the period. Second line contains one positive integer number $$$A \ (1 \leq A \leq 10^{100 000})$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_055.jsonl
|
6412f51877b8f0e0c5387f8499f94d0d
|
256 megabytes
|
["3\n123456", "3\n12345"]
|
PASSED
|
def revive(l):
res = pow(10 , l-1)
return str(res)
l = int(input())
s = input()
val = 0
if len(s) % l == 0:
ans = s[:l]
if ans*(len(s)//l) > s:
print(ans*(len(s)//l))
exit()
elif ans == "9"*l:
ans = revive(l)
val = l
else:
ans = str(int(ans) + 1)
else:
ans = revive(l)
print(ans*((len(s) + l-1 + val)//l))
|
1568554500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\nNO"]
|
8b2d29c3686bb2d58cdd08e73073d461
|
NoteThe two sample test cases correspond to the two mazes in the picture.
|
You are given a circular maze such as the ones shown in the figures. Determine if it can be solved, i.e., if there is a path which goes from the center to the outside of the maze which does not touch any wall. The maze is described by $$$n$$$ walls. Each wall can be either circular or straight. Circular walls are described by a radius $$$r$$$, the distance from the center, and two angles $$$\theta_1, \theta_2$$$ describing the beginning and the end of the wall in the clockwise direction. Notice that swapping the two angles changes the wall. Straight walls are described by an angle $$$\theta$$$, the direction of the wall, and two radii $$$r_1 < r_2$$$ describing the beginning and the end of the wall. Angles are measured in degrees; the angle $$$0$$$ corresponds to the upward pointing direction; and angles increase clockwise (hence the east direction corresponds to the angle $$$90$$$).
|
For each test case, print YES if the maze can be solved and NO otherwise.
|
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 20$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 5000$$$) — the number of walls. Each of the following $$$n$$$ lines each contains a character (C for circular, and S for straight) and three integers: either $$$r, \theta_1, \theta_2$$$ ($$$1 \leq r \leq 20$$$ and $$$0 \leq \theta_1,\theta_2 < 360$$$ with $$$\theta_1 \neq \theta_2$$$) if the wall is circular, or $$$r_1$$$, $$$r_2$$$ and $$$\theta$$$ ($$$1 \leq r_1 < r_2 \leq 20$$$ and $$$0 \leq \theta < 360$$$) if the wall is straight. It is guaranteed that circular walls do not overlap (but two circular walls may intersect at one or two points), and that straight walls do not overlap (but two straight walls may intersect at one point). However, circular and straight walls can intersect arbitrarily.
|
standard output
|
standard input
|
PyPy 2
|
Python
| -1 |
train_085.jsonl
|
e74eb510a755d424ecea4722ba6270ad
|
256 megabytes
|
["2\n5\nC 1 180 90\nC 5 250 230\nC 10 150 140\nC 20 185 180\nS 1 20 180\n6\nC 1 180 90\nC 5 250 230\nC 10 150 140\nC 20 185 180\nS 1 20 180\nS 5 10 0"]
|
PASSED
|
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return (int(input()))
def inlt():
return (list(map(int, input().split())))
def insr():
s = input()
return (list(s[:len(s) - 1]))
def inst():
s = input()
return s[:len(s) - 1]
def invr():
return (map(int, input().split()))
t = inp()
dr = [1, 0, -1, 0]
dth = [0, 1, 0, -1]
def solve():
n = inp()
m = [[True for j in range(720)] for i in range(40)]
nvis = [[True for j in range(720)] for i in range(40)]
for _ in range(n):
cmd = inst().split()
if cmd[0] == 'C':
r = (int(cmd[1]) - 1) * 2 + 1
th1 = (int(cmd[2]) * 2) % 720
th2 = (int(cmd[3]) * 2) % 720
while th1 != th2:
m[r][th1] = False
th1 = (th1 + 1) % 720
m[r][th1] = False
if cmd[0] == 'S':
r1 = (int(cmd[1]) - 1) * 2 + 1
r2 = (int(cmd[2]) - 1) * 2 + 1
th = int(cmd[3]) * 2
while r1 != r2:
m[r1][th] = False
r1 = r1 + 1
m[r1][th] = False
q = [(0, 0)]
while len(q) > 0:
pt = q.pop()
for i in range(4):
npt = (pt[0] + dr[i], (pt[1] + dth[i]) % 720)
if npt[0] >= 0 and npt[0] < 40 and m[npt[0]][npt[1]] and nvis[
npt[0]][npt[1]]:
q.append(npt)
nvis[npt[0]][npt[1]] = False
for i in range(720):
if nvis[39][i] == False:
print('YES')
return
print("NO")
for _ in range(t):
solve()
|
1650798300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["3\n1 2 3", "4\n1 3 5 7"]
|
d55afdb4a83aebdfce5a62e4ec934adb
|
NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$.
|
Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$.
|
The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any.
|
The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_110.jsonl
|
be296ef10fa7a7639a1f0f54a116cfde
|
256 megabytes
|
["5", "8"]
|
PASSED
|
from math import sqrt
n = int(input())
m = n
l = [0] * (n - 1)
if n%2 == 0 :
while m % 2 == 0:
m/=2
if m==1:
x = 2
else:
for i in range(2, n, 2) :
l[i - 1] += 1
for i in range(3, int(sqrt(m)) + 1, 2):
if m%i == 0:
while m % i == 0:
m /= i
if m == 1 :
x = i
break
else:
for i in range(i, n, i) :
l[i - 1] += 1
if m > 2:
op = []
prod = 1
for i in range(1, n) :
if l[i - 1] == 0 and i%m != 0 :
op.append(i)
prod*=i
prod%=n
else:
op = []
prod = 1
for i in range(1, n) :
if l[i - 1] == 0 and i%x != 0 :
op.append(i)
prod*=i
prod%=n
if prod != 1:
op.remove(prod)
print(len(op))
print(*op)
|
1618839300
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["17"]
|
3b4100b844e925af971061df42521712
|
NoteIn the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.
|
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer ai, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.
|
Print a single integer — the maximum possible efficiency of the workgroup.
|
The first line contains integer n (1 ≤ n ≤ 2·105) — the number of workers of the Big Software Company. Then n lines follow, describing the company employees. The i-th line contains two integers pi, ai (1 ≤ ai ≤ 105) — the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p1 = - 1, for all other people the condition 1 ≤ pi < i is fulfilled.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_006.jsonl
|
4594880860d878e618f5a0dbaa035fd7
|
256 megabytes
|
["7\n-1 3\n1 2\n1 1\n1 4\n4 5\n4 3\n5 2"]
|
PASSED
|
n = int(input())
t = [list(map(int, input().split())) for q in range(n)]
n += 1
u = [-1e7] * n
v = [0] * n
for i, (j, a) in list(enumerate(t, 1))[::-1]:
u[i] = max(u[i], v[i] + a)
v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i])
print(u[1])
|
1429286400
|
[
"trees",
"strings",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
1,
1
] |
|
2 seconds
|
["3", "2", "0"]
|
f8f0d00f8d93b5a4bbf0b2eedf1e754a
|
NoteIn the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.Limak can change one coefficient in three ways: He can set a0 = - 10. Then he would get Q(x) = - 10 - 9x - 3x2 + 5x3 and indeed Q(2) = - 10 - 18 - 12 + 40 = 0. Or he can set a2 = - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0. Or he can set a1 = - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.
|
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0, a1, ..., an denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied: ai is integer for every i; |ai| ≤ k for every i; an ≠ 0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.
|
Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.
|
The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients. The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial . It's guaranteed that P(2) ≠ 0.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_008.jsonl
|
18e3fd640bdd9d93bebe07a76bab9e51
|
256 megabytes
|
["3 1000000000\n10 -9 -3 5", "3 12\n10 -9 -3 5", "2 20\n14 -7 19"]
|
PASSED
|
from sys import stdin
from itertools import repeat
def main():
n, k = map(int, stdin.readline().split())
a = map(int, stdin.readline().split(), repeat(10, n + 1))
r = [0] * (n + 50)
c = 0
l = n + 100
for i, x in enumerate(a):
c += x
if c >= 0:
c, r[i] = c / 2, c % 2
else:
c, r[i] = -(-c / 2), -(-c % 2)
if r[i] and l == n + 100:
l = i
i = n + 1
while c:
if c >= 0:
c, r[i]= c / 2, c % 2
else:
c, r[i] = -(-c / 2), -(-c % 2)
if r[i] and l == n + 100:
l = i
i += 1
c = 0
ans = 0
while i > 0:
i -= 1
c = c * 2 + r[i]
if abs(c) > 100000000000:
break
if i <= l and i <= n and c and -k - a[i] <= -c <= k - a[i]:
if i != n or a[i] - c != 0:
ans += 1
print ans
main()
|
1459182900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "3", "9", "91"]
|
43fbb05dc01b5302f19d923e45e325e7
|
NoteIn the first sample, Ostap has to paint both vertices black.In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
|
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
|
Print one integer — the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
|
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ min(20, n - 1)) — the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k. Each of the next n - 1 lines contain two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_052.jsonl
|
662c78faf42f5f70d43c33b36151b5e1
|
256 megabytes
|
["2 0\n1 2", "2 1\n1 2", "4 1\n1 2\n2 3\n3 4", "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7"]
|
PASSED
|
import sys
#sys.stdin=open("data.txt")
#sys.stdout=open("data.txt","w")
input=sys.stdin.readline
n,k=map(int,input().split())
g=[[] for _ in range(n+1)]
vis=[0]*(n+1)
for _ in range(n-1):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
def getans(u,k):
vis[u]=1
# first k -> need k
# then cover exact
# last k -> covers k above
totalv=[0]*(2*k+1)
totalv[k-1]=1
carry=1 # total when this node is black
for v in g[u]:
if vis[v]: continue
getv=getans(v,k)
carry=(carry*sum(getv))%1000000007
out2=[0]*(2*k+1)
#print("before",totalv)
for i in range(1,2*k+1):
for j in range(2*k+1):
if j+i>=2*k:
out2[max(i-1,j)]+=getv[i]*totalv[j]
else:
out2[min(i-1,j)]+=getv[i]*totalv[j]
for i in range(2*k+1):
totalv[i]=out2[i]%1000000007
#print("after ",totalv,carry)
totalv[2*k]+=carry
#print(u,totalv)
return totalv
if k==0: print(1)
else:
temp=getans(1,k)
print(sum(temp[k:])%1000000007)
|
1480264500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["3\n4\n1\n4\n3\n1\n1608737403"]
|
bf21c4809cd10904f05d531dd7af4ab5
|
NoteLet's analyze the test cases of the example. In the first test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$3$$$ emotes respectively, and since $$$1 + 2 + 3 \ge 6$$$, you get banned after that. In the second test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$ emotes respectively, and since $$$1 + 2 + 3 + 4 \ge 7$$$, you get banned after that. In the third test case, you write one message containing exactly $$$1$$$ emote. It doesn't get you banned, since $$$1 < 2$$$, but you have already finished posting your emote triangle. So you wrote one message successfully. In the fourth test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$2$$$ emotes respectively, and since $$$1 + 2 + 3 + 2 \ge 7$$$, you get banned after that. In the fifth test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$1$$$ emote respectively. It doesn't get you banned, since $$$1 + 2 + 1 < 5$$$, but you have already finished posting your emote triangle. So you wrote three messages successfully. In the sixth test case, since $$$x = 1$$$, you get banned as soon as you send your first message. The seventh test case is too large to analyze, so we'll skip it.
|
You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size $$$k$$$. It consists of $$$2k-1$$$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $$$k$$$-th one — of $$$k$$$ emotes, the $$$k+1$$$-th one — of $$$k-1$$$ emotes, ..., and the last one — of one emote.For example, the emote triangle for $$$k=3$$$ consists of $$$5$$$ messages: Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $$$x$$$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $$$2k-1$$$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the number of messages you will write before getting banned for the corresponding values $$$k$$$ and $$$x$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains integers $$$k$$$ and $$$x$$$ ($$$1 \le k \le 10^9; 1 \le x \le 10^{18}$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_098.jsonl
|
177b9b58b3139380bcfdec4242f2708b
|
512 megabytes
|
["7\n4 6\n4 7\n1 2\n3 7\n2 5\n100 1\n1000000000 923456789987654321"]
|
PASSED
|
from heapq import heapify, heappush, heappop
from collections import Counter, defaultdict, deque
from queue import PriorityQueue
from itertools import combinations, product, permutations
from bisect import bisect_left, bisect_right
from functools import lru_cache
from sys import stdin, stdout # for input /output
import copy
import math
import array as arr
# import sys
# sys.setrecursionlimit(100000)
####################
# stdin = open("testcase.txt")
# def input():
# return stdin.readline().strip()
#####################################################################
class FastIO:
@classmethod
def input(cls):
from sys import stdin
x = stdin.buffer.readline().decode().strip()
return x
@classmethod
def integer_list(cls):
return list(map(int, cls.input().split()))
@classmethod
def print(cls, s = "", end = "\n"):
from sys import stdout
stdout.write(str(s) + end)
@classmethod
def flush(cls):
from sys import stdout
stdout.flush()
####################################################################
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
""" initial default value for each node """
""" func which you want to apply to range """
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[2*i], self.data[2*i + 1])
def __delitem__(self, idx):
""" delete item set item value to its default """
self[idx] = self._default
def __getitem__(self, idx):
""" geting item by inx """
return self.data[idx + self._size]
def __setitem__(self, idx, value):
""" changing seting value to given index"""
""" apply function to range """
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
#####################################################################
class BinaryIndexTree(object):
""" use one indexing """
def __init__(self, nums):
n = len(nums)
self._len = len(nums)
self.nums = [0 for _ in range(n+1)]
self.N = [0 for _ in range(n+1)]
for i, v in enumerate(nums):
self.__setitem__(i+1, v)
def _lowbit(self, a):
return a & -a
def __setitem__(self, i, val):
diff = val - self.nums[i]
self.nums[i] = val
while i < len(self.N):
self.N[i] += diff
i += self._lowbit(i)
def __getitem__(self, i):
# return sum up 0 to i
ret = 0
while i > 0:
ret += self.N[i]
i -= self._lowbit(i)
return ret
######################################################################
class DisJointSetsRank():
def __init__(self,N):
# Initially, all elements are single element subsets
self._parents = [node for node in range(N)]
self._ranks = [1 for _ in range(N)]
def find(self, u):
while u != self._parents[u]:
# path compression technique
self._parents[u] = self._parents[self._parents[u]]
u = self._parents[u]
return u
def connected(self, u, v):
return self.find(u) == self.find(v)
def union(self, u, v):
# Union by rank optimization
root_u, root_v = self.find(u), self.find(v)
if root_u == root_v:
return True
if self._ranks[root_u] > self._ranks[root_v]:
self._parents[root_v] = root_u
elif self._ranks[root_v] > self._ranks[root_u]:
self._parents[root_u] = root_v
else:
self._parents[root_u] = root_v
self._ranks[root_v] += 1
return False
#######################################################################
def integer_list():
return list(map(int, input().split()))
def pprint(matrix):
for i in range(len(matrix)):
print(*matrix[i])
#####################################################
#test case section
"""
1 2
3 --> 1, 3
4 ---> 1, 4
5 --> 1, 2, 3, 5
6 --> 1, 2
1 ..... k k-1 ...> 1
n*(n+1)//2
n*(n+1)//2 <= x
n**2 + n - 2x <= 0
-1 + sqrt(1+8x)//2
k-1 + k -2 ..... x
total - y*(y+1)//2 <= rem_x
0 <= y**2 + y + 2*rem_x - 2*total
y = -1 + sqrt(1 - 8(rem_x - totoal))//2
"""
#############################################################
# for manipulating 0 for runing to your system 1 for online
MOD = 10**9+7
ONLINE_JUDGE = 1
def main():
t = int(input())
for _ in range(t):
k, x = integer_list()
s_k = k*(k+1)//2
s_k_1 = (k-1)*k
s_k_1 = s_k_1//2
if s_k + s_k_1 <= x:
print(2*k - 1)
continue
if s_k == x:
print(k)
elif s_k > x:
s = 1
e = k
ans = 1
flag = False
while s <= e:
mid = (s + e)//2
sum_mid = (mid*(mid + 1))//2
if x == sum_mid:
flag = True
ans = mid
break
if x > sum_mid:
ans = mid + 1
s = mid+1
else:
e = mid - 1
print(ans)
else:
count = k
s = k -1
e = 1
rem_x = x - s_k
ans = k-1
flag = False
while s >= e:
mid = (s+e)//2
mid_s = s_k_1 - ((mid - 1)*mid)//2
if rem_x == mid_s:
flag = True
ans = mid
break
if rem_x > mid_s:
ans = mid - 1
s = mid - 1
else:
e = mid + 1
print(count + k - ans)
###############################################
if ONLINE_JUDGE:
input = lambda : stdin.buffer.readline().decode().strip()
else:
stdin = open("testcase.txt")
input = lambda : stdin.readline().strip()
main()
|
1637573700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\n2 5", "NO"]
|
d45f775613e701bbdaa4e457e6e189e2
|
NoteIn the first testcase the resulting string is "aacabba".
|
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $$$3$$$ and ends in position $$$6$$$), but "aa" or "d" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $$$s[l; r] = s_r s_{r - 1} \dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \ne y$$$), or there exists such $$$i$$$ ($$$1 \le i \le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
|
If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.
|
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,000 |
train_011.jsonl
|
9d84d103a211933635be2035f4cedd9f
|
256 megabytes
|
["7\nabacaba", "6\naabcfg"]
|
PASSED
|
'''input
6
aabcfg
'''
from sys import stdin, stdout
import math
from copy import deepcopy
from collections import defaultdict
import heapq
# main starts
n = int(stdin.readline().strip())
string = list(stdin.readline().strip())
for i in range(1, len(string)):
if string[i - 1] <= string[i]:
continue
else:
string[i - 1], string[i] = string[i], string[i - 1]
print('YES')
print(i, i + 1)
break
else:
print("NO")
|
1555943700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["11 492\n13 26\n140133 160776\n1 1"]
|
04330cb392bcfd51d1acffd72c8004cb
|
NoteIn the example: $$$gcd(11, 492) = 1$$$ $$$gcd(13, 26) = 13$$$ $$$gcd(140133, 160776) = 21$$$ $$$gcd(1, 1) = 1$$$
|
You are given three integers $$$a$$$, $$$b$$$ and $$$c$$$.Find two positive integers $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that: the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits; the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits; the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.Output $$$x$$$ and $$$y$$$. If there are multiple answers, output any of them.
|
For each testcase print two positive integers — $$$x$$$ and $$$y$$$ ($$$x > 0$$$, $$$y > 0$$$) such that the decimal representation of $$$x$$$ without leading zeroes consists of $$$a$$$ digits; the decimal representation of $$$y$$$ without leading zeroes consists of $$$b$$$ digits; the decimal representation of $$$gcd(x, y)$$$ without leading zeroes consists of $$$c$$$ digits.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 285$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b \le 9$$$, $$$1 \le c \le min(a, b)$$$) — the required lengths of the numbers. It can be shown that the answer exists for all testcases under the given constraints. Additional constraint on the input: all testcases are different.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,100 |
train_089.jsonl
|
a868f822fa11acf65ae027e92b416ca4
|
256 megabytes
|
["4\n2 3 1\n2 2 2\n6 6 2\n1 1 1"]
|
PASSED
|
def func_gcd(a,b):
if b==0:
return a
return func_gcd(b, a%b)
T = int(input())
for t in range(T):
a, b, c = map(int, input().split())
x_arr = ["1"] + ["0"]*(a-1)
y_arr = ["1"]*(b-c+1) + ["0"]*(c-1)
x = ""
y = ""
for elem in x_arr:
x += elem
for elem in y_arr:
y += elem
print(x, y)
|
1618238100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
4 seconds
|
["1 2 5 8", "1 2 3 4 5 6", "1 3 7"]
|
e25efe1020ae64d55b3257ba457f809d
| null |
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ — the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.
|
Print the path from the $$$1$$$-st to the $$$n$$$-th router. It starts with $$$1$$$ and ends with $$$n$$$. All the elements in the path should be distinct.
|
The first line contains integer number $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of the routers. The following line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is equal to index of the router to which the $$$i$$$-th was connected after purchase.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 900 |
train_008.jsonl
|
87e98ed66fa3037ce625dfc65c66fc15
|
256 megabytes
|
["8\n1 1 2 2 3 2 5", "6\n1 2 3 4 5", "7\n1 1 2 3 4 3"]
|
PASSED
|
a=int(input())
c=[]
h = raw_input()
b=(list(map(int,(h.split(' ')))))
k=a-2
c.append(a)
i=1
while k>=0:
c.append(b[k])
k=c[i]-2
i=i+1
c.reverse()
m=len(c)
for i in range (m):
print c[i]
|
1539335100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["0\n1\n1\n-1\n2\n1"]
|
96f0df1c8e014229e5ef773789aa2205
|
NoteIn the first test case, the product of all elements is initially $$$2$$$, so no operations needed.In the second test case, the product of elements initially equals $$$6$$$. We can apply the operation for $$$i = 2$$$, and then $$$a_2$$$ becomes $$$2\cdot2=4$$$, and the product of numbers becomes $$$3\cdot4=12$$$, and this product of numbers is divided by $$$2^n=2^2=4$$$. In the fourth test case, even if we apply all possible operations, we still cannot make the product of numbers divisible by $$$2^n$$$ — it will be $$$(13\cdot1)\cdot(17\cdot2)\cdot(1\cdot3)\cdot(1\cdot4)=5304$$$, which does not divide by $$$2^n=2^4=16$$$.In the fifth test case, we can apply operations for $$$i = 2$$$ and $$$i = 4$$$.
|
You are given an array of positive integers $$$a_1, a_2, \ldots, a_n$$$.Make the product of all the numbers in the array (that is, $$$a_1 \cdot a_2 \cdot \ldots \cdot a_n$$$) divisible by $$$2^n$$$.You can perform the following operation as many times as you like: select an arbitrary index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the value $$$a_i$$$ with $$$a_i=a_i \cdot i$$$. You cannot apply the operation repeatedly to a single index. In other words, all selected values of $$$i$$$ must be different.Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $$$2^n$$$. Note that such a set of operations does not always exist.
|
For each test case, print the least number of operations to make the product of all numbers in the array divisible by $$$2^n$$$. If the answer does not exist, print -1.
|
The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number test cases. Then the descriptions of the input data sets follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in a test does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_094.jsonl
|
2d43814374b3975000b8628c444355b5
|
256 megabytes
|
["6\n\n1\n\n2\n\n2\n\n3 2\n\n3\n\n10 6 11\n\n4\n\n13 17 1 1\n\n5\n\n1 1 12 1 1\n\n6\n\n20 7 14 18 3 5"]
|
PASSED
|
def countPow2(k):
count = 0
while k % 2 == 0:
count += 1
k //= 2
return count
for _ in [0] * int(input()):
n = int(input())
nums = list(map(int, input().rstrip().split()))
total = extra = 0
extArr = []
for num in nums:
total += countPow2(num)
for i in range(2, n+1):
temp = countPow2(i)
extra += temp
extArr += [temp]
extArr.sort(reverse=True)
if total >= n:
print(0)
elif total + extra < n:
print(-1)
else:
ans = 0
for i in range(len(extArr)):
ans += 1
if total + extArr[i] >= n:
break
total += extArr[i]
print(ans)
|
1665930900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["8", "5"]
|
c8667e7bca99c27e6da1841de8a15790
|
NoteAll possible coloring patterns of the first sample are given below.
|
You have a rooted tree consisting of n vertices. Let's number them with integers from 1 to n inclusive. The root of the tree is the vertex 1. For each i > 1 direct parent of the vertex i is pi. We say that vertex i is child for its direct parent pi.You have initially painted all the vertices with red color. You like to repaint some vertices of the tree. To perform painting you use the function paint that you call with the root of the tree as an argument. Here is the pseudocode of this function:count = 0 // global integer variable rnd() { // this function is used in paint code return 0 or 1 equiprobably}paint(s) { if (count is even) then paint s with white color else paint s with black color count = count + 1 if rnd() = 1 then children = [array of vertex s children in ascending order of their numbers] else children = [array of vertex s children in descending order of their numbers] for child in children { // iterating over children array if rnd() = 1 then paint(child) // calling paint recursively }}As a result of this function, some vertices may change their colors to white or black and some of them may remain red.Your task is to determine the number of distinct possible colorings of the vertices of the tree. We will assume that the coloring is possible if there is a nonzero probability to get this coloring with a single call of paint(1). We assume that the colorings are different if there is a pair of vertices that are painted with different colors in these colorings. Since the required number may be very large, find its remainder of division by 1000000007 (109 + 7).
|
Print a single integer — the answer to the problem modulo 1000000007 (109 + 7)
|
The first line contains a single integer n (2 ≤ n ≤ 105) — the number of vertexes in the tree. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i). Number pi is the parent of vertex i.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,700 |
train_010.jsonl
|
dc7fe4de1a1c1577dba1eb2b12bbbe47
|
256 megabytes
|
["4\n1 2 1", "3\n1 1"]
|
PASSED
|
from sys import stdin
def main():
n = int(stdin.readline())
a = map(int, stdin.readline().split())
e = [[] for _ in xrange(n)]
for i, x in enumerate(a, 1):
e[x-1].append(i)
dp = [[0, 0] for _ in xrange(n)]
mod = 1000000007
for i in xrange(n-1, -1, -1):
t0, t1 = 0, 1
for v in e[i]:
t0, t1 = (t0 + t0 * dp[v][0] + t1 * dp[v][1]) % mod, (t1 + t1 * dp[v][0] + t0 * dp[v][1]) % mod
r0, r1 = 0, 1
d0, d1 = 0, 1
for v in reversed(e[i]):
d0, d1 = (d0 + d1 * dp[v][1]) % mod, (d1 + d0 * dp[v][1]) % mod
r0, r1 = (r0 + r0 * dp[v][0] + r1 * dp[v][1]) % mod, (r1 + r1 * dp[v][0] + r0 * dp[v][1]) % mod
d1 = 1
for v in e[i]:
d1 = (d1 + d1 * dp[v][0]) % mod
dp[i][0] = (t0 + r0 - d0 + mod) % mod
dp[i][1] = (t1 + r1 - d1 + mod) % mod
print (dp[0][0] + dp[0][1]) % mod
main()
|
1414170000
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds
|
["3\n1 2 3\n2\n4 5\n2\nANSWER\n1 2\n2 3\n3 4\n2 5"]
|
685f266dbbc24434913fa092c0ac1f3f
|
NoteIn the sample, the tree is as follows. $$$n = 5$$$ is given to the program. The program then asks Mikaela a question where $$$S = \{1, 2, 3\}$$$, $$$T = \{4, 5\}$$$, and $$$v = 2$$$, to which she replies with $$$5$$$ (the pairs $$$(s, t)$$$ are $$$(1, 4)$$$, $$$(1, 5)$$$, $$$(2, 4)$$$, $$$(2, 5)$$$, and $$$(3, 5)$$$).
|
This is an interactive problem.A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains $$$n$$$ vertices, enumerated from $$$1$$$ through $$$n$$$. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices $$$S$$$ and $$$T$$$, along with any vertex $$$v$$$ that you like. Then, Mikaela will count and give you the number of pairs of vertices $$$(s, t)$$$ where $$$s \in S$$$ and $$$t \in T$$$ such that the simple path from $$$s$$$ to $$$t$$$ contains $$$v$$$.Mikaela the Goddess is busy and will be available to answer at most $$$11\,111$$$ questions.This is your only chance. Your task is to determine the tree and report its edges.
|
When program has realized the tree and is ready to report the edges, print "ANSWER" in a separate line. Make sure that all letters are capitalized. Then, print $$$n-1$$$ lines, each containing two space-separated integers, denoting the vertices that are the endpoints of a certain edge. Each edge should be reported exactly once. Your program should then immediately terminate.
|
The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 500$$$) — the number of vertices in the tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,100 |
train_024.jsonl
|
8211dbca8b128af3d4a18e859e29dca8
|
256 megabytes
|
["5\n5"]
|
PASSED
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cnyali_lk'
import sys
def query(s,t,v):
if len(s)==0 or len(t)==0:
return 0
print(len(s))
for i in s:
print(i,end=' ')
print()
print(len(t))
for i in t:
print(i,end=' ')
print()
print(v)
sys.stdout.flush()
return int(input())
n=int(input())
d=[0]*(n+1)
for i in range(2,n+1):
d[i]=query(list(range(2,i))+list(range(i+1,n+1)),[1],i)
v=list(range(2,n+1))
v.sort(key=lambda x:d[x])
nofa=[]
ans=[]
for i in v:
if len(nofa):
for t in range(query([1],nofa,i)):
l,r=1,len(nofa)
while l<=r:
mid=(l+r)//2
if query([1],nofa[:mid],i)>0:
r=mid-1
else:
l=mid+1
w=nofa[r]
nofa.remove(w)
ans.append((w,i))
nofa.append(i)
for i in nofa:
ans.append((i,1))
print("ANSWER")
for i in ans:
print(i[0],i[1])
|
1551022500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1", "2\n2"]
|
a2b71d66ea1fdc3249e37be3ab0e67ef
| null |
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
|
Output q lines. On i-th of them output single integer — answer for i-th query.
|
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_002.jsonl
|
de0c6f0d62bc8e0c0362c588e21ebfd6
|
256 megabytes
|
["1 1\n1", "2 2\n1\n2"]
|
PASSED
|
import random
import time
seed = int(time.time())
random.seed(seed)
def solve(k, p):
pass
def main():
xs = [int(x) for x in raw_input().strip().split()]
k = xs[0]
dp = [[0.0 for _ in range(k+1)] for _ in range(10000)]
for d in range(1, 10000):
dp[d][1] = 1.0
for ki in range(2, min(d, k)+1):
dp[d][ki] = (float(k-ki+1)/k)*dp[d-1][ki-1] + (float(ki-1)/k)*dp[d-1][ki]
for _ in range(xs[1]):
p = int(raw_input().strip())
for d in range(k, 10000):
if dp[d][k] > float(p)/2000:
print d
break
if '__main__'==__name__:
main()
|
1487606700
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["0.5", "-1", "0.625"]
|
d01f153d0049c22a21e321d5c4fbece9
|
NoteIn the first sample it is optimal to build the reserve with the radius equal to $$$0.5$$$ and the center in $$$(0,\ 0.5)$$$.In the second sample it is impossible to build a reserve.In the third sample it is optimal to build the reserve with the radius equal to $$$\frac{5}{8}$$$ and the center in $$$(\frac{1}{2},\ \frac{5}{8})$$$.
|
There is a forest that we model as a plane and live $$$n$$$ rare animals. Animal number $$$i$$$ has its lair in the point $$$(x_{i}, y_{i})$$$. In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by $$$y = 0$$$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.
|
If the reserve cannot be built, print $$$-1$$$. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of animals. Each of the next $$$n$$$ lines contains two integers $$$x_{i}$$$, $$$y_{i}$$$ ($$$-10^7 \le x_{i}, y_{i} \le 10^7$$$) — the coordinates of the $$$i$$$-th animal's lair. It is guaranteed that $$$y_{i} \neq 0$$$. No two lairs coincide.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_075.jsonl
|
35db850cdb879297958ecc38b003f782
|
256 megabytes
|
["1\n0 1", "3\n0 1\n0 2\n0 -3", "2\n0 1\n1 1"]
|
PASSED
|
l , r =-100000000, 1000000000
def check(mid):
mx = 0
for i in range(n):
x,y = x1[i],y1[i]
mx = max (mx ,(x1[i] - mid) ** 2 / (2 * y1[i]) + (y1[i] / 2))
return mx
n = int(input())
count1 = 0
count2 = 0
x1 = []
y1 = []
for i in range(n):
a,b = map(int,input().split())
if b>=0:
count1+=1
else:
count2+=1
x1.append(a)
y1.append(abs(b))
if count1 and count2:
print(-1)
exit()
for i in range(100):
mid1 = l+(r-l)/3
mid2 = r-(r-l)/3
if check(mid1)>check(mid2):
l = mid1
else:
r = mid2
# print(l,r)
print(check(l))
|
1538750100
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["1 2 3 4 5", "2 4 3 7 1", "-1"]
|
b85c8bfbe67a23a81bef755f9313115a
|
Notegcd(x, y) is greatest common divisor of x and y.
|
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
|
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
|
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_027.jsonl
|
badc6d98fcdde7d8aa0ec13fda172fc5
|
256 megabytes
|
["5 2", "5 3", "7 2"]
|
PASSED
|
n,k=map(int, input().split(' '))
if k<n//2 :
print(-1)
elif n==1:
if k == 0:
print(1)
else:
print(-1)
else:
x=(k-n//2)+1
ans=[x,2*x]
for i in range(n-2):
ans.append(200000001 + i)
print(*ans)
|
1396798800
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["2", "1", "18", "16"]
|
6956d1c98c4047f1b8f832df3566ddce
|
Note The first sample will be (1 + 1) = 2. The second sample will be (2 + (1 - 2)) = 1. The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16.
|
Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.An Ahmes arithmetic expression can be defined as: "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.
|
Print one line containing the answer to the problem.
|
The first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'. The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,300 |
train_017.jsonl
|
b2481597d857a96d042ef7525a5b366b
|
256 megabytes
|
["(1?1)\n1 0", "(2?(1?2))\n1 1", "((1?(5?7))?((6?2)?7))\n3 2", "((1?(5?7))?((6?2)?7))\n2 3"]
|
PASSED
|
from math import inf
class Node:
def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0):
self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ
def __str__(self):
return "Node"
memo = {}
def Memoize(node, p, maxValue, minValue):
if not node in memo:
memo.update({node : {p : [maxValue, minValue]} })
else:
memo[node].update({p : [maxValue, minValue]})
def ExpMaxValue(root: Node, p):
m = root.signQ - p
"""if root.signQ == 1:
if p == 1:
return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value]
else:
return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]"""
if root.signQ == 0:
return [root.value, root.value]
if root in memo:
if p in memo[root]:
return memo[root][p]
if m == 0:
value = ExpMaxValue(root.leftExp, root.leftExp.signQ)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ)[0]
Memoize(root, p, value, value)
return [value, value]
if p == 0:
value = ExpMaxValue(root.leftExp, 0)[0] - ExpMaxValue(root.rightExp, 0)[0]
Memoize(root, p, value, value)
return [value, value]
maxValue = -inf
minValue = inf
if m >= p:
for pQMid in range(2):
pQLeftMin = min(p - pQMid, root.leftExp.signQ)
for pQLeft in range(pQLeftMin + 1):
if root.leftExp.signQ - pQLeft + (1 - pQMid) > m:
continue
resLeft = ExpMaxValue(root.leftExp, pQLeft)
resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft)
if pQMid == 1:
maxValue = max(resLeft[0] + resRight[0], maxValue)
minValue = min(resLeft[1] + resRight[1], minValue)
else:
maxValue = max(resLeft[0] - resRight[1], maxValue)
minValue = min(resLeft[1] - resRight[0], minValue)
else:
for mQMid in range(2):
mQLeftMin = min(m - mQMid, root.leftExp.signQ)
for mQLeft in range(mQLeftMin + 1):
pQLeft = root.leftExp.signQ - mQLeft
if pQLeft + (1 - mQMid) > p:
continue
resLeft = ExpMaxValue(root.leftExp, pQLeft)
resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft)
if mQMid == 0:
maxValue = max(resLeft[0] + resRight[0], maxValue)
minValue = min(resLeft[1] + resRight[1], minValue)
else:
maxValue = max(resLeft[0] - resRight[1], maxValue)
minValue = min(resLeft[1] - resRight[0], minValue)
Memoize(root, p, int(maxValue), int(minValue))
return [int(maxValue), int(minValue)]
def PrintNodes(root: Node):
if root.signQ != 0:
leftExp = root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value
rightExp = root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value
check = root.signQ == root.leftExp.signQ + root.rightExp.signQ + 1
print(root.signQ, root.parent, leftExp, rightExp, check)
PrintNodes(root.leftExp)
PrintNodes(root.rightExp)
def main():
exp = str(input())
if len(exp) == 1:
print(exp)
return
#root = Node(None, None, None)
#root.parent = root
cNode = Node()
isRight = False
for i in range(1, len(exp) - 1):
if exp[i] == '(':
if not isRight:
cNode.leftExp = Node(cNode)
cNode = cNode.leftExp
else:
cNode.rightExp = Node(cNode)
cNode = cNode.rightExp
isRight = False
elif exp[i] == '?':
isRight = True
cNode.signQ += 1
elif exp[i] == ')':
if cNode.parent != None:
cNode.parent.signQ += cNode.signQ
cNode = cNode.parent
isRight = False
else:
if not isRight:
cNode.leftExp = Node(cNode)
cNode.leftExp.value = int(exp[i])
else:
cNode.rightExp = Node(cNode)
cNode.rightExp.value = int(exp[i])
#PrintNodes(cNode)
ss = str(input()).split()
p, m = int(ss[0]), int(ss[1])
print(ExpMaxValue(cNode, p)[0])
main()
|
1519058100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1 1\n0 0\n1 0\n0 1", "0 1\n0 10\n0 0\n0 9"]
|
78d54d76cb113cf74ea89fb77471859b
| null |
You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.
|
Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10 - 6 precision.
|
The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_009.jsonl
|
cd1e3e6628a76671baf4b45d7c64d285
|
256 megabytes
|
["1 1", "0 10"]
|
PASSED
|
import sys
import itertools
from math import *
n, m = map(int, raw_input().split(" "))
a, b = None, None
for i in xrange(0, n + 1):
for j in xrange(0, m + 1):
if not ((i, j) in [(0, 0), (n, m)]):
if a == None and b == None:
a = i
b = j
else:
if (0 - i)**2 + (0 - j)**2 > (0 - a)**2 + (0 - b)**2:
a, b = i, j
v = [(a, b), (0, 0)]
c, d = a, b
a, b = None, None
for i in xrange(0, n + 1):
for j in xrange(0, m + 1):
if not ((i, j) in [(0, 0), (n, m), (c, d)]):
if a == None and b == None:
a = i
b = j
else:
if (n - i)**2 + (m - j)**2 > (n - a)**2 + (m - b)**2:
a, b = i, j
v += [(n, m), (a, b)]
#print v
def d(x):
return sqrt((x[1][0] - x[0][0])**2 + (x[1][1] - x[0][1])**2) + sqrt((x[2][0] - x[1][0])**2 + (x[2][1] - x[1][1])**2) + sqrt((x[3][0] - x[2][0])**2 + (x[3][1] - x[2][1])**2)
v = list(itertools.permutations(v))
if n != 0 and m != 0:
v += list(itertools.permutations([(0, 0), (n, m), (n, 0), (0, m)]))
for a in sorted(zip(map(d, v), v))[-1][1]:
print "%d %d" % a
|
1406480400
|
[
"geometry",
"trees"
] |
[
0,
1,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["2\n1\n61\n6"]
|
8db0c45990fd49245f537f7bea048307
|
NoteHere is the list of non-elegant numbers up to $$$10$$$: $$$4 = 2^2, GCD = 2$$$; $$$8 = 2^3, GCD = 3$$$; $$$9 = 3^2, GCD = 2$$$. The rest have $$$GCD = 1$$$.
|
Consider some positive integer $$$x$$$. Its prime factorization will be of form $$$x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dots$$$Let's call $$$x$$$ elegant if the greatest common divisor of the sequence $$$k_1, k_2, \dots$$$ is equal to $$$1$$$. For example, numbers $$$5 = 5^1$$$, $$$12 = 2^2 \cdot 3$$$, $$$72 = 2^3 \cdot 3^2$$$ are elegant and numbers $$$8 = 2^3$$$ ($$$GCD = 3$$$), $$$2500 = 2^2 \cdot 5^4$$$ ($$$GCD = 2$$$) are not.Count the number of elegant integers from $$$2$$$ to $$$n$$$.Each testcase contains several values of $$$n$$$, for each of them you are required to solve the problem separately.
|
Print $$$T$$$ lines — the $$$i$$$-th line should contain the number of elegant numbers from $$$2$$$ to $$$n_i$$$.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^5$$$) — the number of values of $$$n$$$ in the testcase. Each of the next $$$T$$$ lines contains a single integer $$$n_i$$$ ($$$2 \le n_i \le 10^{18}$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_054.jsonl
|
e261d538d7d69514662d7c672ad3408d
|
256 megabytes
|
["4\n4\n2\n72\n10"]
|
PASSED
|
import sys, math
from sys import stdin, stdout
rem = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 6+5)
#from resource import *; setrlimit(RLIMIT_STACK, (RLIM_INFINITY, RLIM_INFINITY))
take = lambda: map(int, stdin.readline().strip().split())
from bisect import bisect_left,bisect_right
from collections import deque
from heapq import heapify,heappush,heappop
def help(n):
left=0
right=10**9 +10
while(left<=right):
#print left,right
mid=(left+right+1)/2
num=mid*mid
if num==n or left==right:
break
elif num>n:
right=mid-1
else :
left=mid
return mid
pf={}
for i in range(10**4):
pf[i*i]=1
all=[]
done={}
for i in range(3,61,2):
p=1
for j in range(1,10**6+5):
num=pow(j,i)
if j in pf:
continue
if num>10**18:
break
if num not in done:
done[num]=1
all.append(num)
all.sort()
#print len(all)
t=input()
anss=[]
for q in range(t):
b=take()[0]
a=2
ans=bisect_right(all,b)-bisect_right(all,a-1)
ans+=help(b)-help(a-1)
anss.append(str(b-a+1-ans))
print '\n'.join(anss)
|
1536330900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["2\n4\n-1\n2\n5"]
|
a18692e5fe2f98717608449b1d9b77f7
|
NoteIn the first test case, imposters can be Andreas $$$2$$$ and $$$3$$$.In the second test case, imposters can be Andreas $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$.In the third test case, comments contradict each other. This is because player $$$1$$$ says that player $$$2$$$ is an imposter, and player $$$2$$$ says that player $$$1$$$ is a crewmate. If player $$$1$$$ is a crewmate, then he must be telling the truth, so player $$$2$$$ must be an imposter. But if player $$$2$$$ is an imposter then he must be lying, so player $$$1$$$ can't be a crewmate. Contradiction.
|
Theofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus).In each game, Theofanis plays with $$$n$$$ other players. Since they all have the same name, they are numbered from $$$1$$$ to $$$n$$$.The players write $$$m$$$ comments in the chat. A comment has the structure of "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). The comment means that player $$$i$$$ said that player $$$j$$$ has the role $$$c$$$.An imposter always lies, and a crewmate always tells the truth. Help Theofanis find the maximum possible number of imposters among all the other Cypriot players, or determine that the comments contradict each other (see the notes for further explanation).Note that each player has exactly one role: either imposter or crewmate.
|
For each test case, print one integer — the maximum possible number of imposters. If the comments contradict each other, print $$$-1$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of each test case follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 5 \cdot 10^5$$$) — the number of players except Theofanis and the number of comments. Each of the next $$$m$$$ lines contains a comment made by the players of the structure "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). There can be multiple comments for the same pair of $$$(i, j)$$$. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ and the sum of all $$$m$$$ does not exceed $$$5 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_097.jsonl
|
8d4a1e1247a28467583c4fa499de6e4c
|
256 megabytes
|
["5\n3 2\n1 2 imposter\n2 3 crewmate\n5 4\n1 3 crewmate\n2 5 crewmate\n2 4 imposter\n3 4 imposter\n2 2\n1 2 imposter\n2 1 crewmate\n3 5\n1 2 imposter\n1 2 imposter\n3 2 crewmate\n3 2 crewmate\n1 3 imposter\n5 0"]
|
PASSED
|
from collections import defaultdict
from collections import deque
from functools import lru_cache
import heapq
from locale import resetlocale
import sys
import random
import math
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s)
def invr():
return(map(int,input().split()))
z = inp()
for q in range(1, z+1):
[players, comments] = inlt()
graph = defaultdict(list)
fakeNode = players + 1
for _ in range(comments):
s = sys.stdin.readline()
s = s.split(" ")
a = int(s[0])
b = int(s[1])
c = s[2]
# print("line", a,b,c)
if("imposter" in c):
graph[a].append(b)
graph[b].append(a)
else:
graph[a].append(fakeNode)
graph[fakeNode].append(b)
graph[b].append(fakeNode)
graph[fakeNode].append(a)
fakeNode += 1
colors = [0] * (fakeNode+1)
ok = True
# print(graph)
def validColors(color, node):
if(colors[node] != 0):
return colors[node] == color
colors[node] = color
for neighbour in graph[node]:
if(not validColors(-color, neighbour)):
return False
return True
for i in range(1,players+1):
if(colors[i] != 0):
continue
level = deque([i])
colors[i] = 1
while(level):
length = len(level)
for _ in range(length):
node = level.popleft()
for neighbour in graph[node]:
# print(colors, node, neighbour)
if(colors[neighbour] == 0):
colors[neighbour] = -colors[node]
level.append(neighbour)
elif(colors[neighbour] != -colors[node]):
# print("not ok")
ok = False
break
if(not ok):
break
if(not ok):
print(-1)
continue
cnt = defaultdict(int)
# print(colors)
visited = set()
res = 0
for i in range(1, players+1):
if(i in visited):
continue
component = set()
level = set([i])
while(level):
newLevel = set()
for node in level:
if(node in visited):
continue
visited.add(node)
component.add(node)
for neighbour in graph[node]:
newLevel.add(neighbour)
level = newLevel
cnt = defaultdict(int)
for idx in component:
if(idx > players ):
continue
cnt[colors[idx]] += 1
res += max(cnt[-1], cnt[1])
# print("ans",res)
print(res)
|
1633705500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["2", "-1"]
|
48494a73273cd8d999e94ba1a9581fdf
| null |
This is the easier version of the problem. In this version, $$$1 \le n \le 10^5$$$ and $$$0 \le a_i \le 1$$$. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k > 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
|
If there is no way for Charlie to make Alice happy, print $$$-1$$$. Otherwise, print a single integer $$$x$$$ — the minimum number of seconds for Charlie to help Bob make Alice happy.
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of chocolate boxes. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the number of chocolate pieces in the $$$i$$$-th box. It is guaranteed that at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_003.jsonl
|
43ea29d48d104f990b6e12a84b2e6274
|
256 megabytes
|
["3\n1 0 1", "1\n1"]
|
PASSED
|
def count_wyn(st_p, end_p, curr_x):
tmp_wyn_to_ret = 0
tmp_wyn_to_ret_1 = 0
num_1 = 0
mid_10 = 0
mid_11 = 0
mid_12 = 0
mid = False
for x in range(st_p, end_p + 1):
if t[x] != 0:
if mid == False:
num_1 += 1
if num_1 == curr_x//2:
mid_10 = x
mid_11 = x
mid = True
else:
mid_12 = x
break
if curr_x%2 == 0:
for xx in range(st_p, end_p + 1):
if t[xx] == 1:
tmp_wyn_to_ret += abs(mid_10 - xx)
#print('DLA MID_P ZWRACAM:', tmp_wyn_to_ret, 'st_p:', st_p, 'end_p:', end_p, 'mid_10:', mid_10)
#print('------------------------------------')
return tmp_wyn_to_ret
else:
for xx in range(st_p, end_p + 1):
if t[xx] == 1:
tmp_wyn_to_ret += abs(xx - mid_11)
tmp_wyn_to_ret_1 += abs(xx - mid_12)
#print('DLA MID_P_1_2 ZWRACAM:', min(tmp_wyn_to_ret, tmp_wyn_to_ret_1), 'st_p:', st_p, 'end_p:', end_p, 'mid_11', mid_11, 'mid_12', mid_12)
#print('------------------------------------')
return min(tmp_wyn_to_ret, tmp_wyn_to_ret_1)
n = int(input())
t = list(map(int, input().split()))
t_sum = sum(t)
wyn = 10**18
t_div = []
if t_sum <= 1:
print('-1')
exit(0)
for i in range(2, int(t_sum ** .5) + 2):
if t_sum % i == 0:
while t_sum % i == 0:
t_sum //= i
t_div.append(i)
if t_sum > 1:
t_div.append(t_sum)
for x in t_div:
tmp_s = 0
tmp_wyn = 0
pocz = 0
for y in range(0, len(t), +1):
tmp_s += t[y]
if tmp_s == x:
#print('WYWOLUJE DLA - pocz:', pocz, 'y:', y, 'x:', x)
tmp_wyn += count_wyn(pocz ,y, x)
pocz = y+1
tmp_s = 0
if tmp_wyn <= wyn:
wyn = tmp_wyn
print(wyn)
|
1574174100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["abacaba", "aaa", "ababab"]
|
d66e55ac7fa8a7b57ccd57d9242fd2a2
| null |
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.
|
Print lexicographically minimal string that fits all the information Ivan remembers.
|
The first line contains single integer n (1 ≤ n ≤ 105) — the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order — positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≤ xi, j ≤ 106, 1 ≤ ki ≤ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,700 |
train_065.jsonl
|
75266791808763d7c03b40f6916d7986
|
256 megabytes
|
["3\na 4 1 3 5 7\nab 2 1 5\nca 1 4", "1\na 1 3", "3\nab 1 1\naba 1 3\nab 2 3 5"]
|
PASSED
|
def magic():
string=['1']*10000005
n=input()
m_index=0
till=0
for _ in xrange(n):
arr=raw_input().split()
s=arr[0]
times=int(arr[1])
arr=map(int,arr[2:])
l=len(s)
m_index=max(m_index,arr[-1]+l)
start=end=0
for index in arr:
if index==1 and till==0:
till=l
upto=index+l-1
if upto<till or upto<end:
continue
elif index<end:
m=end+1
j=end-index+1
else:
m=index
j=0
for i in xrange(m,upto+1):
string[i]=s[j]
j+=1
end=max(end,upto)
while till<3000000:
if string[till]!='1':
till+=1
else:
break
for i in xrange(1,m_index):
if string[i]=='1':
string[i]='a'
print ''.join(string[1:m_index])
magic()
|
1499791500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1\n-1\n2\n3\n-1\n5\n4\n7\n-1\n-1\n18\n-1"]
|
b5dcee7034ee2742b666aea4cbfc616f
| null |
Let us denote by $$$d(n)$$$ the sum of all divisors of the number $$$n$$$, i.e. $$$d(n) = \sum\limits_{k | n} k$$$.For example, $$$d(1) = 1$$$, $$$d(4) = 1+2+4=7$$$, $$$d(6) = 1+2+3+6=12$$$.For a given number $$$c$$$, find the minimum $$$n$$$ such that $$$d(n) = c$$$.
|
For each test case, output: "-1" if there is no such $$$n$$$ that $$$d(n) = c$$$; $$$n$$$, otherwise.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$c$$$ ($$$1 \le c \le 10^7$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_107.jsonl
|
ac4c7b26c3642643230d4a2563e7c3cd
|
512 megabytes
|
["12\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n39\n691"]
|
PASSED
|
import sys
input = sys.stdin.readline
n=10**7
l=[0]+[1]*n
for i in range(2,n+1):
j=i
while(j<=n):
l[j]+=i
j+=i
l1=[-1]*(n+1)
for i in range(n,0,-1):
if(l[i]<=n):
l1[l[i]]=i
for w in range(int(input())):
print(l1[int(input())])
|
1618065300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["10\n4\n179"]
|
2ced6a414a9752e7c50d37e1e1c8ffd7
|
NoteFor the first pair, where $$$p_1 = 10$$$ and $$$q_1 = 4$$$, the answer is $$$x_1 = 10$$$, since it is the greatest divisor of $$$10$$$ and $$$10$$$ is not divisible by $$$4$$$.For the second pair, where $$$p_2 = 12$$$ and $$$q_2 = 6$$$, note that $$$12$$$ is not a valid $$$x_2$$$, since $$$12$$$ is divisible by $$$q_2 = 6$$$; $$$6$$$ is not valid $$$x_2$$$ as well: $$$6$$$ is also divisible by $$$q_2 = 6$$$. The next available divisor of $$$p_2 = 12$$$ is $$$4$$$, which is the answer, since $$$4$$$ is not divisible by $$$6$$$.
|
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.To improve his division skills, Oleg came up with $$$t$$$ pairs of integers $$$p_i$$$ and $$$q_i$$$ and for each pair decided to find the greatest integer $$$x_i$$$, such that: $$$p_i$$$ is divisible by $$$x_i$$$; $$$x_i$$$ is not divisible by $$$q_i$$$. Oleg is really good at division and managed to find all the answers quickly, how about you?
|
Print $$$t$$$ integers: the $$$i$$$-th integer is the largest $$$x_i$$$ such that $$$p_i$$$ is divisible by $$$x_i$$$, but $$$x_i$$$ is not divisible by $$$q_i$$$. One can show that there is always at least one value of $$$x_i$$$ satisfying the divisibility conditions for the given constraints.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of pairs. Each of the following $$$t$$$ lines contains two integers $$$p_i$$$ and $$$q_i$$$ ($$$1 \le p_i \le 10^{18}$$$; $$$2 \le q_i \le 10^{9}$$$) — the $$$i$$$-th pair of integers.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_005.jsonl
|
2b39cd37232df20a6f63561fe73d0737
|
512 megabytes
|
["3\n10 4\n12 6\n179 822"]
|
PASSED
|
import math
def smallestDivisor(n):
if (n % 2 == 0):
return 2;
i = 3;
while(i * i <= n):
if (n % i == 0):
return i;
i += 2;
return n;
def prevPowerofK(n, k):
p = int(math.log(n) / math.log(k))
return int(math.pow(k, p))
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(i)
n = n // i
if n > 2:
l.append(n)
return l
t = int(input())
while t:
n,x= map(int,input().split())
if n%x!=0:
print(n)
else:
l2 = primeFactors(x)
d2 = {}
for j in l2:
if j in d2:
d2[j]+=1
else:
d2[j]=1
ans = 0
for i in d2:
if n%i==0:
power = 1
number = i
while n%number==0:
power+=1
number *=i
if power>1:
xxx = n// i**(power-1)
xxx *= i**(d2[i]-1)
ans = max(ans,xxx)
print(ans)
t-=1
|
1604228700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["1 2 2 2 \n1 1 \n2 2 3 3 3 3 3"]
|
6d76fb5753eec2b5ebe38c10ed1564f9
|
Note In the first testcase: For $$$x = 1$$$, we can an edge between vertices $$$1$$$ and $$$3$$$, then $$$d(1) = 0$$$ and $$$d(2) = d(3) = d(4) = 1$$$, so $$$f(1) = 1$$$. For $$$x \ge 2$$$, no matter which edge we add, $$$d(1) = 0$$$, $$$d(2) = d(4) = 1$$$ and $$$d(3) = 2$$$, so $$$f(x) = 2$$$.
|
This version of the problem differs from the previous one only in the constraint on $$$n$$$.A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with $$$n$$$ vertices, each edge has a weight of $$$1$$$. Denote $$$d(v)$$$ as the distance between vertex $$$1$$$ and vertex $$$v$$$.Let $$$f(x)$$$ be the minimum possible value of $$$\max\limits_{1 \leq v \leq n} \ {d(v)}$$$ if you can temporarily add an edge with weight $$$x$$$ between any two vertices $$$a$$$ and $$$b$$$ $$$(1 \le a, b \le n)$$$. Note that after this operation, the graph is no longer a tree.For each integer $$$x$$$ from $$$1$$$ to $$$n$$$, find $$$f(x)$$$.
|
For each test case, print $$$n$$$ integers in a single line, $$$x$$$-th of which is equal to $$$f(x)$$$ for all $$$x$$$ from $$$1$$$ to $$$n$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$). Each of the next $$$n−1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) indicating that there is an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_084.jsonl
|
f636b826f0d0c047c78ecb1d7a1a1490
|
512 megabytes
|
["3\n\n4\n\n1 2\n\n2 3\n\n1 4\n\n2\n\n1 2\n\n7\n\n1 2\n\n1 3\n\n3 4\n\n3 5\n\n3 6\n\n5 7"]
|
PASSED
|
# import sys
# I = lambda: [*map(int, sys.stdin.readline().split())]
import io,os
read = io.BytesIO(os.read(0, os.fstat(0).st_size))
I = lambda:map(int, read.readline().split())
def maxsparse(a):
l = []
l.append(a)
c = 1
while c < len(a):
new = []
for i in range(len(a)):
if i + c < len(l[-1]):
new.append(max(l[-1][i], l[-1][i + c]))
else:
break
l.append(new)
c *= 2
return l
def partial(table, i, j):
if j <= i:
return -1000000
yyy = 1
aaa = 0
while 2 * yyy <= j - i:
yyy *= 2
aaa += 1
return max(table[aaa][i], table[aaa][j - yyy])
t, = I()
for _ in range(t):
n, = I()
graph = [[] for i in range(n)]
for i in range(n - 1):
a, b = I()
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
parents = [None] * n
parents[0] = -1
children = [[] for i in range(n)]
layer = [0]
while layer:
newlayer = []
for guy in layer:
for boi in graph[guy]:
if parents[boi] is None:
newlayer.append(boi)
children[guy].append(boi)
parents[boi] = guy
layer = newlayer
parents[0] = None
inds = [0] * n
order = []
curr = 0
while curr is not None:
if inds[curr] == len(children[curr]):
order.append(curr)
curr = parents[curr]
else:
inds[curr] += 1
curr = children[curr][inds[curr] - 1]
lowest = [0] * n
for v in order:
if children[v]:
big = max(lowest[i] for i in children[v])
lowest[v] = big + 1
depth = lowest[0]
path = [0]
curr = 0
while True:
biggest = -1
count = 0
rep = None
for child in children[curr]:
if lowest[child] > biggest:
biggest = lowest[child]
count = 1
rep = child
elif lowest[child] == biggest:
count += 1
if count == 1:
path.append(rep)
curr = rep
else:
break
other = [0] * len(path)
for i in range(len(path) - 1):
if len(children[path[i]]) == 1:
other[i] = 0
else:
other[i] = max(lowest[j] for j in children[path[i]] if j != path[i + 1]) + 1
other[-1] = lowest[path[-1]]
bigs = [other[0]]
for i in range(len(path) - 1):
bigs.append(max(bigs[-1], other[i + 1] + i + 1))
# print(path)
# print(other)
# print(bigs)
# print(children)
# print(parents)
# print(lowest)
xx = [other[i] - i for i in range(len(path))]
sparse = maxsparse(xx)
if len(path) == 1:
out = [lowest[0]] * n
else:
out = []
curr = 2
currcost = -1
for x in range(1, n + 1):
if x >= len(path) - 1 or currcost >= lowest[0]:
out.append(lowest[0])
continue
currcost = max(bigs[(x + curr) // 2], lowest[path[curr]] + x, partial(sparse, (x + curr) // 2 + 1, curr) + x + curr)
while curr < len(path) - 1:
#print(x, curr)
nextcost = max(bigs[(x + curr + 1) // 2], lowest[path[curr + 1]] + x, partial(sparse, (x + curr + 1) // 2 + 1, curr + 1) + x + curr + 1)
if nextcost < currcost:
curr += 1
currcost = nextcost
else:
break
out.append(currcost)
print(*out)
|
1643553300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["YES\n3 4 5\n6 7 8", "NO"]
|
3815d18843dbd15a73383d69eb6880dd
| null |
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.
|
If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.
|
The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_001.jsonl
|
2ce52f2ba8f831461aa573ed5b19b5fe
|
256 megabytes
|
["2 3\n2 9\n5 3 13", "3 3\n1 7 6\n2 15 12"]
|
PASSED
|
from functools import reduce
n, m = list(map(int, input().split()))
ns = list(map(int, input().split()))
ms = list(map(int, input().split()))
xn = reduce(lambda acc, cur: acc ^ cur, ns, 0)
xm = reduce(lambda acc, cur: acc ^ cur, ms, 0)
if xn ^ xm != 0:
print('NO')
else:
print('YES')
print(xm ^ ns[0] ^ ms[0], *ms[1:])
for i in range(1, n):
print(ns[i], *[0] * (m - 1))
|
1533307500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["galileo galilei was an italian physicist, mathematician, astronomer", "galileo was born in pisa"]
|
8c26daa1eed2078af3b32737da0a0f84
| null |
You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules: if there is no punctuation mark between two words, then they should be separated by exactly one space there should be no spaces before each punctuation mark there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.
|
Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.
|
The input data contains of a single non-empty line — the text whose length is no more than 10000 characters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_011.jsonl
|
b0606edead6ae69a64253f902eec9425
|
256 megabytes
|
["galileo galilei was an italian physicist ,mathematician,astronomer", "galileo was born in pisa"]
|
PASSED
|
x=input()
m=('.',',','?','!')
for i in range(len(x)-1):
if x[i] in m and x[i + 1] != ' ':
print(x[i] + ' ', end='')
elif not(x[i]==' ' and x[i+1]==' ' or x[i]==' ' and x[i+1] in m):
print(x[i],end='')
print(x[len(x)-1])
|
1325602800
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["29", "174", "235"]
|
7a3108216f400a4f5bb809353ceb18d4
|
NoteIn the first example, you can reverse the subarray $$$[4, 5]$$$. Then $$$a = [2, 3, 2, 3, 1]$$$ and $$$2 \cdot 1 + 3 \cdot 3 + 2 \cdot 2 + 3 \cdot 4 + 1 \cdot 2 = 29$$$.In the second example, you don't need to use the reverse operation. $$$13 \cdot 2 + 37 \cdot 4 = 174$$$.In the third example, you can reverse the subarray $$$[3, 5]$$$. Then $$$a = [1, 8, 3, 6, 7, 6]$$$ and $$$1 \cdot 5 + 8 \cdot 9 + 3 \cdot 6 + 6 \cdot 8 + 7 \cdot 8 + 6 \cdot 6 = 235$$$.
|
You are given two integer arrays $$$a$$$ and $$$b$$$ of length $$$n$$$.You can reverse at most one subarray (continuous subsegment) of the array $$$a$$$. Your task is to reverse such a subarray that the sum $$$\sum\limits_{i=1}^n a_i \cdot b_i$$$ is maximized.
|
Print single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of $$$a$$$.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^7$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_102.jsonl
|
51c27eb0e1d42474c3fb96c6bd874f2e
|
256 megabytes
|
["5\n2 3 2 1 3\n1 3 2 4 2", "2\n13 37\n2 4", "6\n1 8 7 6 3 6\n5 9 6 8 8 6"]
|
PASSED
|
from itertools import combinations, accumulate, groupby, count
from sys import stdout, stdin, setrecursionlimit
from collections import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
def fast(): return stdin.readline()
def zzz(): return [int(i) for i in fast().split()]
z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer): stdout.write(str(answer))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
###########################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some , Then you probably don't know him !
"""
###########################---START-CODING---###############################################
n = int(z())
a = zzz()
b = zzz()
primarySum = sum(a[i] * b[i] for i in range(n))
mxSum = primarySum
for i in range(n):
left, right = i + 1, i - 1
currentSum = primarySum
while left < n and right >= 0:
currentSum -= (a[left] - a[right]) * (b[left] - b[right])
mxSum = max(mxSum, currentSum)
left += 1
right -= 1
currentSum = primarySum
left, right = i + 1, i
while left < n and right >= 0:
currentSum -= (a[left] - a[right]) * (b[left] - b[right])
mxSum = max(mxSum, currentSum)
left += 1
right -= 1
print(mxSum)
|
1619706900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3.5 seconds
|
["? 1 2\n! 1 2", "? 2 1\n? 1 3\n? 4 1\n? 2 3\n? 4 2\n? 4 3\n! 0 0"]
|
90a9d883408d5c283d6e7680c0b94c8b
|
NoteIn the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house $$$1$$$ to house $$$2$$$. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits.In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city.
|
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.There is a city in which Dixit lives. In the city, there are $$$n$$$ houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the $$$i$$$-th house is $$$k_i$$$.Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of $$$|k_A - k_B|$$$, where $$$k_i$$$ is the number of roads leading to the house $$$i$$$. If more than one optimal pair exists, any of them is suitable.Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?In the problem input, you are not given the direction of each road. You are given — for each house — only the number of incoming roads to that house ($$$k_i$$$).You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice.Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit.See the Interaction section below for more details.
| null |
The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) denoting the number of houses in the city. The next line contains $$$n$$$ space-separated integers $$$k_1, k_2, \dots, k_n$$$ ($$$0 \le k_i \le n - 1$$$), the $$$i$$$-th of them represents the number of incoming roads to the $$$i$$$-th house.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_107.jsonl
|
5a6268e3fd0eb83fb22370944d3d1e40
|
256 megabytes
|
["3\n1 1 1\nYes", "4\n1 2 0 3\nNo\nNo\nNo\nNo\nNo\nNo"]
|
PASSED
|
import os,sys
from random import randint
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# n = int(input())
# for i in range(n, n + 100000000):
# s = str(i)
# x = 0
# for j in range(len(s)):
# x += int(s[j])
# if math.gcd(x, i) > 1:
# print(i)
# break
# for _ in range(int(input())):
# n, w = list(map(int, input().split()))
# a = list(map(int, input().split()))
# cnt = Counter(a)
# cnt = sorted([[i, j] for i, j in cnt.items()])
# ans = 0
# tot = 0
# for i, j in cnt:
# tot += j
# while tot > 0:
# i = len(cnt) - 1
# cur = 0
# while i >= 0 and cur < w:
# wi, c = cnt[i]
# if wi * c <= w - cur:
# cur += wi * c
# cnt[i][1] = 0
# tot -= c
# else:
# k = (w - cur) // wi
# cur += k * wi
# cnt[i][1] -= k
# tot -= k
# i -= 1
# ans += 1
# print(ans)
# mod = 10 ** 9 + 7
# for _ in range(int(input())):
# n, k = list(map(int, input().split()))
# if k == 1:
# print(1)
# continue
# if n == 1:
# print(2)
# continue
# ans = 1 + n
# a = [1] * (n - 1)
# for i in range(k - 2):
# if i % 2 == 0:
# for j in range(n - 2)[::-1]:
# a[j] = (a[j] + a[j + 1]) % mod
# else:
# for j in range(1, n - 1):
# a[j] = (a[j] + a[j - 1]) % mod
# ans += sum(a)
# print(ans % mod)
# N = 10 ** 5
# n, m = list(map(int, input().split()))
# q = deque()
# q.append(0)
# vis = [0] * (m + 1)
# vis[0] = 1
# ans = [-1] * (m + 1)
# for idx in range(n):
# t, x, y = list(map(int, input().split()))
# if t == 1:
# x = (x + N - 1) // N
# for i in range(x):
# k = -1
# for j in range(i, m + 1, x):
# if vis[j] == 1:
# k = 0
# elif k != -1:
# k += 1
# if vis[j] == 0 and k <= y:
# ans[j] = idx + 1
# vis[j] = 1
# else:
# vis2 = [0] * (m + 1)
# for i in range(1, m + 1):
# if vis2[i] == 0:
# vis2[i] = 1
# j = i
# k = -1
# while j <= m:
# vis2[j] = 1
# if vis[j] == 1:
# k = 0
# elif k != -1:
# k += 1
# if vis[j] == 0 and k <= y:
# ans[j] = idx + 1
# vis[j] = 1
# j = (j * x + N - 1) // N
# print(*ans[1:])
def solve():
n = int(input())
a = list(map(int, input().split()))
# id = [i for i in range(n)]
# id.sort(key=lambda x : a[x], reverse=True)
id = []
for i in range(n):
for j in range(n):
if a[i] > a[j] or (a[i] == a[j] and i != j):
id.append([i, j])
# print(id)
id.sort(key=lambda x : a[x[1]] - a[x[0]])
# for i in range(n):
# for j in range(i + 1, n)[::-1]:
# print('?', id[i] + 1, id[j] + 1)
# sys.stdout.flush()
# if input() == 'Yes':
# print('!', id[i] + 1, id[j] + 1)
# sys.stdout.flush()
# return
for i, j in id:
print('?', i + 1, j + 1)
sys.stdout.flush()
if input() == 'Yes':
print('!', i + 1, j + 1)
sys.stdout.flush()
return
print('!', 0, 0)
sys.stdout.flush()
solve()
|
1617028500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.