prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
⌀ | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
⌀ | prob_desc_input_spec
stringlengths 38
2.42k
⌀ | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
⌀ | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
sequencelengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
sequencelengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3 seconds | ["9 8", "4608 4096"] | 59d5e5ed2bc4b316e950e2a4dbc99d68 | null | Let's call a positive integer composite if it has at least one divisor other than $$$1$$$ and itself. For example: the following numbers are composite: $$$1024$$$, $$$4$$$, $$$6$$$, $$$9$$$; the following numbers are not composite: $$$13$$$, $$$1$$$, $$$2$$$, $$$3$$$, $$$37$$$. You are given a positive integer $$$n$$$. Find two composite integers $$$a,b$$$ such that $$$a-b=n$$$.It can be proven that solution always exists. | Print two composite integers $$$a,b$$$ ($$$2 \leq a, b \leq 10^9, a-b=n$$$). It can be proven, that solution always exists. If there are several possible solutions, you can print any. | The input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^7$$$): the given integer. | standard output | standard input | Python 3 | Python | 800 | train_000.jsonl | f516914c2ba0dc71e80ae4421503ee32 | 256 megabytes | ["1", "512"] | PASSED | n = int(input())
x = 1000000000
while True:
if n%2==0:
if x%2==0 and (x-n)%2==0:
print(x , x-n)
break
else:
x-=2
else:
if x%3 == 0:
print(x , x-n)
break
else:
x-=1
| 1576926300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["Yes", "No", "Yes"] | 69edc72ec29d4dd56751b281085c3591 | NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example: | Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here. | Print "Yes" if the tree is a spruce and "No" otherwise. | The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. | standard output | standard input | Python 3 | Python | 1,200 | train_004.jsonl | bb997e3fc91e795280644a6ec10ead40 | 256 megabytes | ["4\n1\n1\n1", "7\n1\n1\n1\n2\n2\n2", "8\n1\n1\n1\n1\n3\n3\n3"] | PASSED | # cook your dish here
from sys import stdin,stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I=lambda: map(int,stdin.readline().split())
I1=lambda: stdin.readline()
#(a/b)%m =((a%m)*pow(b,m-2)%m)%m
n=int(I1())
l=[]
for _ in range(n-1):
x=int(I1())
l.append(x)
s=list(set(l))
#print(l)
for x in s:
c=0
for i in range(n-1):
if x==l[i]:
if i+2 not in s:
c+=1
if c<3:
print("No")
exit()
print("Yes")
| 1515422700 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["2 2 3 1 2", "9999 10000 9998"] | ced70b400694fa16929d4b0bce3da294 | null | Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array! | In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any. | The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table. The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$. | standard output | standard input | Python 3 | Python | 1,300 | train_008.jsonl | 2fb176bcdb407b7469020d3abb7eb641 | 256 megabytes | ["5\n0 4 6 2 4\n4 0 6 2 4\n6 6 0 3 6\n2 2 3 0 2\n4 4 6 2 0", "3\n0 99990000 99970002\n99990000 0 99980000\n99970002 99980000 0"] | PASSED | I=input
I()
a=[*map(int,I().split())]
a[0]=a[1]*a[2]/int(I().split()[2])
print(*(int(y/a[0]**.5)for y in a)) | 1568822700 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1.5 seconds | ["1 2 1 1 1 \n0 0 1"] | a4101af56ea6afdfaa510572eedd6320 | Note In example case $$$1$$$, For $$$k = 0$$$, there is $$$1$$$ path that is from $$$2$$$ to $$$3$$$ as $$$MEX([2, 3]) = 0$$$. For $$$k = 1$$$, there are $$$2$$$ paths that is from $$$0$$$ to $$$2$$$ as $$$MEX([0, 2]) = 1$$$ and $$$0$$$ to $$$3$$$ as $$$MEX([0, 2, 3]) = 1$$$. For $$$k = 2$$$, there is $$$1$$$ path that is from $$$0$$$ to $$$1$$$ as $$$MEX([0, 1]) = 2$$$. For $$$k = 3$$$, there is $$$1$$$ path that is from $$$1$$$ to $$$2$$$ as $$$MEX([1, 0, 2]) = 3$$$ For $$$k = 4$$$, there is $$$1$$$ path that is from $$$1$$$ to $$$3$$$ as $$$MEX([1, 0, 2, 3]) = 4$$$. In example case $$$2$$$, For $$$k = 0$$$, there are no such paths. For $$$k = 1$$$, there are no such paths. For $$$k = 2$$$, there is $$$1$$$ path that is from $$$0$$$ to $$$1$$$ as $$$MEX([0, 1]) = 2$$$. | You are given a tree with $$$n$$$ nodes, numerated from $$$0$$$ to $$$n-1$$$. For each $$$k$$$ between $$$0$$$ and $$$n$$$, inclusive, you have to count the number of unordered pairs $$$(u,v)$$$, $$$u \neq v$$$, such that the MEX of all the node labels in the shortest path from $$$u$$$ to $$$v$$$ (including end points) is $$$k$$$.The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. | For each test case, print $$$n+1$$$ integers: the number of paths in the tree, such that the MEX of all the node labels in that path is $$$k$$$ for each $$$k$$$ from $$$0$$$ 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 2 \cdot 10^{5}$$$). The next $$$n-1$$$ lines of each test case describe the tree that has to be constructed. These lines contain two integers $$$u$$$ and $$$v$$$ ($$$0 \le u,v \le n-1$$$) denoting an edge between $$$u$$$ and $$$v$$$ ($$$u \neq v$$$). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^{5}$$$. | standard output | standard input | PyPy 3-64 | Python | 2,400 | train_085.jsonl | 84fcbbead088d2584d8a95a2557697de | 256 megabytes | ["2\n4\n0 1\n0 2\n2 3\n2\n1 0"] | PASSED | import sys
input = sys.stdin.buffer.readline
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, begin, end):
depth = (end - begin).bit_length() - 1
return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])
class LCA:
def __init__(self, root, graph):
self.time = [-1] * len(graph)
self.path = [-1] * len(graph)
P = [-1] * len(graph)
t = -1
dfs = [root]
while dfs:
node = dfs.pop()
self.path[t] = P[node]
self.time[node] = t = t + 1
for nei in graph[node]:
if self.time[nei] == -1:
P[nei] = node
dfs.append(nei)
self.rmq = RangeQuery(self.time[node] for node in self.path)
def __call__(self, a, b):
if a == b:
return a
a = self.time[a]
b = self.time[b]
if a > b:
a, b = b, a
return self.path[self.rmq.query(a, b)]
def process(n, G):
g = [[] for i in range(n)]
for u, v in G:
g[u].append(v)
g[v].append(u)
"""
Step One:
Generate LCA and size of all subtrees
rooted at zero.
"""
L = LCA(0, g)
size = [0 for i in range(n)]
parent = [None for i in range(n)]
depth = [[0]]
parent[0] = -1
while True:
next_s = []
for x in depth[-1]:
for y in g[x]:
if parent[y] is None:
parent[y] = x
next_s.append(y)
if len(next_s)==0:
break
depth.append(next_s)
while len(depth) > 0:
for x in depth.pop():
size[x]+=1
if parent[x] != -1:
size[parent[x]]+=size[x]
seen_yet = [0 for i in range(n+2)]
"""
Step 2:
answer1[i] = number of pairs with mex >= i
IE
number of pairs whose path includes
everything from 0 to i-1
"""
answer1 = [None for i in range(n+1)]
"""
Step 3:
answer1[0] = all possible pairs.
"""
answer1[0] = n*(n-1)//2
"""
Step 4:
answer1[1] = all possible pairs
except those in the same subtree of 0
"""
answer1[1] = n*(n-1)//2
for x in g[0]:
s1 = size[x]
answer1[1]-=(s1*(s1-1))//2
"""
Step 5:
answer1[2] = all possible pairs
where one is a descendant of 1
and the other is a descendant of 0
(but on another subtree)
"""
path = [1]
while path[-1] != 0:
x = path[-1]
path.append(parent[x])
s1 = size[1]
s0 = 1
for x in g[0]:
if x != path[-2]:
s0+=size[x]
answer1[2] = s1*s0
"""
Step 6:
Everything on the path from 1 to 0
if we have say, 2, 3, 4, 5
then they are the same as 2
"""
for x in path:
seen_yet[x] = 1
smallest_unseen = 1
while seen_yet[smallest_unseen]==1:
answer1[smallest_unseen+1] = answer1[2]
smallest_unseen+=1
"""
Step 7:
we have a path from 1 to 0
that also contains
2, ..., I-1, if anything
find the first my_mex after that
such that my_mex-1 is not a descendant of 1
or on that series of paths.
"""
p1 = 0
p2 = 1
"""
Step 8:
Similar but now separate subtrees.
"""
last_bad = None
while smallest_unseen <= n-1:
if answer1[smallest_unseen+1] is None:
if L(smallest_unseen, p2)==p2:
path = [smallest_unseen]
while path[-1] != p2:
x2 = path[-1]
path.append(parent[x2])
s1 = size[smallest_unseen]
if p1==0:
s2 = s0
else:
s2 = size[p1]
for x2 in path:
seen_yet[x2] = 1
p2 = smallest_unseen
while seen_yet[smallest_unseen]==1:
answer1[smallest_unseen+1] = s1*s2
smallest_unseen+=1
elif L(smallest_unseen, p1)==p1 and (p1 > 0 or L(smallest_unseen, p2)==p1):
path = [smallest_unseen]
while path[-1] != p1:
x2 = path[-1]
path.append(parent[x2])
s1 = size[smallest_unseen]
s2 = size[p2]
p1 = smallest_unseen
for x2 in path:
seen_yet[x2] = 1
while seen_yet[smallest_unseen]==1:
answer1[smallest_unseen+1] = s1*s2
smallest_unseen+=1
else:
last_bad = smallest_unseen+1
break
if last_bad is not None:
for i in range(last_bad, n+1):
answer1[i] = 0
answer = [None for i in range(n+1)]
for i in range(n):
answer[i] = answer1[i]-answer1[i+1]
answer[n] = answer1[n]
answer = ' '.join(map(str, answer))
sys.stdout.write(f'{answer}\n')
t = int(input())
for i in range(t):
n = int(input())
G = []
for i in range(n-1):
u, v = [int(x) for x in input().split()]
G.append([u, v])
process(n, G) | 1621521300 | [
"math",
"trees"
] | [
0,
0,
0,
1,
0,
0,
0,
1
] |
|
1 second | ["8", "32400"] | dcb483886c81d2cc0ded065aa1e74091 | NoteIn the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698. | Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1·10k - 1 + c2·10k - 2 + ... + ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109 + 7. | Print a single integer — the number of good phone numbers of length n modulo 109 + 7. | The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k. The second line of the input contains n / k space-separated positive integers — sequence a1, a2, ..., an / k (1 ≤ ai < 10k). The third line of the input contains n / k space-separated positive integers — sequence b1, b2, ..., bn / k (0 ≤ bi ≤ 9). | standard output | standard input | PyPy 2 | Python | 1,600 | train_001.jsonl | 00f679d582870d46f97794dfc57dab1d | 256 megabytes | ["6 2\n38 56 49\n7 3 4", "8 2\n1 22 3 44\n5 4 3 2"] | PASSED | n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
an=1
mod=int(1e9+7)
num=int('9'*k)
for i in xrange(n/k):
val1=a[i]
val2=int(str(b[i])+'9'*(k-1))
val3=int(str(b[i]-1)+'9'*(k-1))
ans=0
if b[i]==0:ans=num/val1-val2/val1
else:ans=num/val1+1-(val2/val1-val3/val1)
an*=ans
an%=mod
print an
| 1447000200 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1", "1", "-1", "-1"] | 91cfd24b8d608eb379f709f4509ecd2d | NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1. | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. | The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. | standard output | standard input | Python 3 | Python | 1,600 | train_015.jsonl | f1f384fee93ed675a955e34f1458c18d | 256 megabytes | ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"] | PASSED | n = int(input())
ref = [int(x) for x in input().split()]
state = [[float('inf')]*2 for x in range(n)]
prev = input()
state[0][0] = 0
state[0][1] = ref[0]
flag = 0
for i in range(1,n):
cur = input()
if cur >= prev:
state[i][0] = min(state[i][0],state[i-1][0])
if cur >= prev[-1::-1]:
state[i][0] = min(state[i][0],state[i-1][1])
if cur[-1::-1] >= prev:
state[i][1] = min(state[i][1],state[i-1][0]+ref[i])
if cur[-1::-1] >= prev[-1::-1]:
state[i][1] = min(state[i][1],state[i-1][1]+ref[i])
prev = cur
if state[i][0] >= float('inf') and state[i][1] >= float('inf'):
flag = 1
break
if flag == 1:
print(-1)
else:
print(min(state[n-1][0],state[n-1][1]))
| 1470933300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["2\n6"] | fc01082e3ed7877126e750bc380f5c63 | NoteIn the second test case, if we place a mine under the fourth building and then activate it, then all mines on the field are activated. The cost of such operations is six, $$$b=1$$$ coin for placing a mine and $$$a=5$$$ coins for activating. | Bertown is a city with $$$n$$$ buildings in a straight line.The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $$$n$$$, where the $$$i$$$-th character is "1" if there is a mine under the building number $$$i$$$ and "0" otherwise.Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered $$$x$$$ is activated, it explodes and activates two adjacent mines under the buildings numbered $$$x-1$$$ and $$$x+1$$$ (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes $$$a$$$ coins. He can repeat this operation as many times as you want.Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes $$$b$$$ coins. He can also repeat this operation as many times as you want.The sapper can carry out operations in any order.You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city. | For each test case, output one integer — the minimum number of coins that the sapper will have to pay. | The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 1000$$$) — the cost of activating and placing one mine, respectively. The next line contains a map of mines in the city — a string consisting of zeros and ones. The sum of the string lengths for all test cases does not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,300 | train_015.jsonl | 9473e87dc494be577586b887e7ed05be | 256 megabytes | ["2\n1 1\n01000010\n5 1\n01101110"] | PASSED | import math
N = int(input())
for _ in range(N):
a,b = map(int,input().split())
s = input()
while len(s) !=0 and s[0] == '0':
s = s[1:]
while len(s) !=0 and s[-1] == '0':
s = s[0:-1]
zerosForSkip = int(math.ceil(a / b))
zeroesCount = 0
res = 0
tryFill = False
for i in s:
if i == '0' and tryFill:
zeroesCount += 1
res += b
elif i == '1':
zeroesCount = 0
if not tryFill:
res += a
tryFill = True
if zeroesCount == zerosForSkip:
res -= zeroesCount*b
tryFill = False
zeroesCount = 0
print(res)
| 1604327700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["25", "138"] | 3bf7c6e2491367b2afcb73fd14f62dd2 | null | Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height ai in the beginning), then the cost of charging the chain saw would be bi. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, ai < aj and bi > bj and also bn = 0 and a1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you? | The only line of output must contain the minimum cost of cutting all the trees completely. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. | The first line of input contains an integer n (1 ≤ n ≤ 105). The second line of input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The third line of input contains n integers b1, b2, ..., bn (0 ≤ bi ≤ 109). It's guaranteed that a1 = 1, bn = 0, a1 < a2 < ... < an and b1 > b2 > ... > bn. | standard output | standard input | Python 3 | Python | 2,100 | train_018.jsonl | 6fea2bd2e2b3cf5ea1d5f7f19dfe19d4 | 256 megabytes | ["5\n1 2 3 4 5\n5 4 3 2 0", "6\n1 2 3 10 20 30\n6 5 4 3 2 0"] | PASSED | read = lambda: map(int, input().split())
n = int(input())
a = list(read())
b = list(read())
dp = [0] * n
ch = [0]
def get(i, x):
return b[i] * x + dp[i]
def f1():
if len(ch) < 2:
return 0
return get(ch[0], a[i]) >= get(ch[1], a[i])
def f2():
if len(ch) < 2:
return 0
i1 = ch[-1]
x = (dp[i1] - dp[i]) / (b[i] - b[i1])
return get(ch[-2], x) <= get(i, x)
for i in range(1, n):
while f1():
ch.pop(0)
dp[i] = get(ch[0], a[i])
while f2():
ch.pop()
ch.append(i)
print(dp[n - 1])
| 1371992400 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["537.500000000", "2121.000000000"] | 295c768a404d11a4ac480aaaf653c45c | NoteConsider the first test case. If Manao listens to the songs in the order in which they were originally compiled, the mathematical expectation will be equal to 467.5 seconds. The maximum expected value is obtained by putting the first song at the end of the playlist.Consider the second test case. The song which is 360 seconds long should be listened to first. The song 300 seconds long which Manao will dislike for sure should be put in the end. | Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist: If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song. If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following: Manao listens to A, he likes it, he remembers it. Manao listens to B, he does not like it, so he listens to A, again. Manao listens to C, he likes the song and he remembers it, too. Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening.Manao has received n songs: the i-th of them is li seconds long and Manao may like it with a probability of pi percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist. | In a single line print a single real number — the maximum expected listening time over all permutations of songs. The answer will be considered valid if the absolute or relative error does not exceed 10 - 9. | The first line contains a single integer n (1 ≤ n ≤ 50000). The i-th of the following n lines contains two integers, separated by a single space — li and pi (15 ≤ li ≤ 1000, 0 ≤ pi ≤ 100) — the length of the i-th song in seconds and the probability that Manao will like the song, in percents. | standard output | standard input | Python 2 | Python | 2,100 | train_004.jsonl | fd2a48fb44b0df05a3e9a8e99e362734 | 256 megabytes | ["3\n150 20\n150 50\n100 50", "4\n300 0\n300 50\n240 50\n360 80"] | PASSED | n=input()
v=[0]*n
e,f=0,0
for i in range(n):
a,b=map(int,raw_input().split())
e+=a
v[i]=(a*b,100-b)
v.sort(cmp=lambda x,y:x[1]*y[0]-x[0]*y[1])
for x in v:
e+=f*x[1]/100.
f+=x[0]/100.
print '%.12f'%e
| 1359387000 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds | ["1\n-1\n1\n-1", "2"] | c4016ba22de92d1c7c2e6d13fedc062d | NoteIn the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.In the second sample the cities to capture are 3 and 5. | Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.Help the King to calculate this characteristic for each of his plan. | For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective. | The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom. Each of the next n - 1 lines contains two distinct integers ui, vi (1 ≤ ui, vi ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans. Each of the next q lines looks as follows: first goes number ki — the number of important cities in the King's plan, (1 ≤ ki ≤ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan. The sum of all ki's does't exceed 100 000. | standard output | standard input | PyPy 3 | Python | 2,800 | train_064.jsonl | 143c8460793f6650b2ab94cd4e58a5b0 | 256 megabytes | ["4\n1 3\n2 3\n4 3\n4\n2 1 2\n3 2 3 4\n3 1 2 4\n4 1 2 3 4", "7\n1 2\n2 3\n3 4\n1 5\n5 6\n5 7\n1\n4 2 4 6 7"] | PASSED | import sys
from collections import deque
def solve():
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
stk = [-1, 0]
it = [0]*N
while len(stk) > 1:
v = stk[-1]
i = it[v]
if i == 0:
FS[v] = len(S)
depth[v] = len(stk)
if i < len(G[v]) and G[v][i] == stk[-2]:
it[v] += 1
i += 1
if i == len(G[v]):
LS[v] = len(S)
stk.pop()
else:
stk.append(G[v][i])
it[v] += 1
S.append(v)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [[]]*N
P = [0]*N
deg = [0]*N
KS = [0]*N
A = [0]*N
B = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(k-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
G0[v] = []
it[v] = 0
stk.append(v)
prv = v
que = deque()
prv = -1
P[vs[0]] = -1
for v in vs:
if v == prv:
continue
for w in G0[v]:
P[w] = v
deg[v] = len(G0[v])
if deg[v] == 0:
que.append(v)
prv = v
while que:
v = que.popleft()
if KS[v]:
a = 0
for w in G0[v]:
ra = A[w]; rb = B[w]
if depth[v]+1 < depth[w]:
a += min(ra, rb+1)
else:
a += ra
A[v] = INF
B[v] = a
else:
a = 0; b = c = INF
for w in G0[v]:
ra = A[w]; rb = B[w]
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
A[v] = min(a, b+1, c+1)
B[v] = b
p = P[v]
if p != -1:
deg[p] -= 1
if deg[p] == 0:
que.append(p)
v = min(A[vs[0]], B[vs[0]])
if v >= INF:
ans.append("-1\n")
else:
ans.append("%d\n" % v)
for v in vs:
KS[v] = 0
writelines(ans)
solve() | 1452789300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["? 1 1\n\n? 1 2\n\n? 1 3\n\n! 6 5 3"] | d70b9c132e08cadb760569495f48053c | NoteThe array $$$A$$$ in the example is $$$\{{1, 2, 4\}}$$$. The first element of the password is bitwise OR of $$$A_2$$$ and $$$A_3$$$, the second element is bitwise OR of $$$A_1$$$ and $$$A_3$$$ and the third element is bitwise OR of $$$A_1$$$ and $$$A_2$$$. Hence the password sequence is $$$\{{6, 5, 3\}}$$$. | This is an interactive problem.Ayush devised yet another scheme to set the password of his lock. The lock has $$$n$$$ slots where each slot can hold any non-negative integer. The password $$$P$$$ is a sequence of $$$n$$$ integers, $$$i$$$-th element of which goes into the $$$i$$$-th slot of the lock.To set the password, Ayush comes up with an array $$$A$$$ of $$$n$$$ integers each in the range $$$[0, 2^{63}-1]$$$. He then sets the $$$i$$$-th element of $$$P$$$ as the bitwise OR of all integers in the array except $$$A_i$$$.You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the bitwise OR all elements of the array with index in this subset. You can ask no more than 13 queries. | null | The first line of input contains one integer $$$n$$$ $$$(2 \le n \le 1000)$$$ — the number of slots in the lock. | standard output | standard input | Python 3 | Python | 2,800 | train_017.jsonl | 855af565914412305e68fc055bcc27ee | 256 megabytes | ["3\n\n1\n\n2\n\n4"] | PASSED | def subset(n,k,res,bit):
while bit<1<<n:res.append(bit);x=bit&-bit;y=bit+x;bit=((bit&~y)//x>>1)|y
return res
n=int(input());bb=subset(13,6,[],63);bb=bb[:n];m=bb[-1].bit_length();xx=[0]*m;ans=[0]*n
for k in range(m):
cur=[]
for i,b in enumerate(bb):
if b>>k&1:cur.append(i+1)
print("?",len(cur),*cur,flush=True);xx[k]=int(input())
for i,b in enumerate(bb):
for k in range(m):
if b>>k&1==0:ans[i]|=xx[k]
print("!",*ans,flush=True)
| 1591540500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n1", "2\n1 2", "1\n2", "1\n6", "1\n1"] | d6dc1895a58e13cdac98377819f6ec68 | NoteIn the first example, we set point $$$(0, 0)$$$ to group $$$A$$$ and points $$$(0, 1)$$$ and $$$(1, 0)$$$ to group $$$B$$$. In this way, we will have $$$1$$$ yellow number $$$\sqrt{2}$$$ and $$$2$$$ blue numbers $$$1$$$ on the blackboard.In the second example, we set points $$$(0, 1)$$$ and $$$(0, -1)$$$ to group $$$A$$$ and points $$$(-1, 0)$$$ and $$$(1, 0)$$$ to group $$$B$$$. In this way, we will have $$$2$$$ yellow numbers $$$2$$$, $$$4$$$ blue numbers $$$\sqrt{2}$$$ on the blackboard. | You are given a set of $$$n\ge 2$$$ pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups $$$A$$$ and $$$B$$$, such that the following condition holds:For every two points $$$P$$$ and $$$Q$$$, write the Euclidean distance between them on the blackboard: if they belong to the same group — with a yellow pen, and if they belong to different groups — with a blue pen. Then no yellow number is equal to any blue number.It is guaranteed that such a partition exists for any possible input. If there exist multiple partitions, you are allowed to output any of them. | In the first line, output $$$a$$$ ($$$1 \le a \le n-1$$$) — the number of points in a group $$$A$$$. In the second line, output $$$a$$$ integers — the indexes of points that you include into group $$$A$$$. If there are multiple answers, print any. | The first line contains one integer $$$n$$$ $$$(2 \le n \le 10^3)$$$ — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^6 \le x_i, y_i \le 10^6$$$) — the coordinates of the $$$i$$$-th point. It is guaranteed that all $$$n$$$ points are pairwise different. | standard output | standard input | Python 3 | Python | 2,300 | train_019.jsonl | e89639cf2d4389383dc572105e9464b2 | 256 megabytes | ["3\n0 0\n0 1\n1 0", "4\n0 1\n0 -1\n1 0\n-1 0", "3\n-2 1\n1 1\n-1 0", "6\n2 5\n0 3\n-4 -1\n-5 -4\n1 0\n3 -1", "2\n-1000000 -1000000\n1000000 1000000"] | PASSED | from sys import stdin
def rl():
return [int(w) for w in stdin.readline().split()]
n, = rl()
x0,y0 = rl()
d = [0]
for i in range(n-1):
x,y = rl()
d.append((x-x0)**2 + (y-y0)**2)
while not any(x&1 for x in d):
for i in range(n):
d[i] >>= 1
A = [i+1 for i in range(n) if d[i]&1]
print(len(A))
print(*A)
| 1577628300 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["First", "Second"] | 808611f86c70659a1d5b8fc67875de31 | NoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose. | Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally? | Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes). | First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109). | standard output | standard input | Python 3 | Python | 1,100 | train_009.jsonl | 65336d113ae609069348cf8a985ce9fc | 256 megabytes | ["4\n1 3 2 3", "2\n2 2"] | PASSED | input(); print(("Second", "First")[any(int(i) % 2 for i in input().split())])
| 1503068700 | [
"math",
"games"
] | [
1,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"] | d43786ca0472a5da735b04b9808c62d9 | null | Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. | Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. | The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive. | standard output | standard input | Python 3 | Python | 2,400 | train_077.jsonl | fb3402eb1ed73655f48921abd801a033 | 256 megabytes | ["4 4 4\n4 4\n4"] | PASSED | def get_input():
a, b, d = map(int, input().split())
c, e = map(int, input().split())
f = int(input())
return [a, b, c, d, e, f]
def check_condition(a, b, c, d, e, f):
condition1 = (a + b + c) % 2 == 0
condition2 = (d + e + a) % 2 == 0
condition3 = (e + f + c) % 2 == 0
condition4 = (d + f + b) % 2 == 0
condition = condition1 and condition2 and condition3 and condition4
return condition
def find_t(a, b, c, d, e, f):
t_min1 = round((d + f - a - c) / 2)
t_min2 = round((e + f - a - b) / 2)
t_min3 = round((d + e - b - c) / 2)
t_min4 = 0
t_min = max(t_min1, t_min2, t_min3, t_min4)
t_max1 = round((d + e - a) / 2)
t_max2 = round((e + f - c) / 2)
t_max3 = round((d + f - b) / 2)
t_max = min(t_max1, t_max2, t_max3)
if t_min <= t_max:
return t_min
else:
return -1
def find_all(a, b, c, d, e, f, t):
x1 = round((a + c - d - f) / 2 + t)
x2 = round((d + f - b) / 2 - t)
y1 = round((a + b - e - f) / 2 + t)
y2 = round((e + f - c) / 2 - t)
z1 = round((b + c - d - e) / 2 + t)
z2 = round((d + e - a) / 2 - t)
return [x1, x2, y1, y2, z1, z2]
def generate_string(x1, x2, y1, y2, z1, z2, t):
n = x1 + x2 + y1 + y2 + z1 + z2 + t
s1 = ''.join(['a'] * n)
s2 = ''.join(['a'] * (z1 + z2 + t)) + ''.join(['b'] * (x1 + x2 + y1 + y2))
s3 = ''.join(['a'] * t) + ''.join(['b'] * (y1 + y2 + z1 + z2)) + ''.join(['a'] * (x1 + x2))
s4 = ''.join(['b'] * (t + z2)) + ''.join(['a'] * (z1 + y2)) + ''.join(['b'] * (y1 + x2)) + ''.join(['a'] * x1)
return [s1, s2, s3, s4]
def __main__():
fail_output = "-1"
a, b, c, d, e, f = map(int, get_input())
if not(check_condition(a, b, c, d, e, f)):
print(fail_output)
return False
t = find_t(a, b, c, d, e, f)
if t < 0:
print(fail_output)
return False
x1, x2, y1, y2, z1, z2 = map(int, find_all(a, b, c, d, e, f, t))
s1, s2, s3, s4 = map(str, generate_string(x1, x2, y1, y2, z1, z2, t))
print(str(x1 + x2 + y1 + y2 + z1 + z2 + t) + '\n')
print(s1 + '\n')
print(s2 + '\n')
print(s3 + '\n')
print(s4 + '\n')
__main__()
# Made By Mostafa_Khaled | 1338737400 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds | ["14", "131"] | a240eefaf9f3f35de9ea9860302b96d9 | NoteIn the first example, it's optimal to rearrange the elements of the given array in the following order: $$$[6, \, 2, \, 2, \, 2, \, 3, \, 1]$$$:$$$$$$\operatorname{gcd}(a_1) + \operatorname{gcd}(a_1, \, a_2) + \operatorname{gcd}(a_1, \, a_2, \, a_3) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5, \, a_6) = 6 + 2 + 2 + 2 + 1 + 1 = 14.$$$$$$ It can be shown that it is impossible to get a better answer.In the second example, it's optimal to rearrange the elements of a given array in the following order: $$$[100, \, 10, \, 10, \, 5, \, 1, \, 3, \, 3, \, 7, \, 42, \, 54]$$$. | This is the easy version of the problem. The only difference is maximum value of $$$a_i$$$.Once in Kostomuksha Divan found an array $$$a$$$ consisting of positive integers. Now he wants to reorder the elements of $$$a$$$ to maximize the value of the following function: $$$$$$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i),$$$$$$ where $$$\operatorname{gcd}(x_1, x_2, \ldots, x_k)$$$ denotes the greatest common divisor of integers $$$x_1, x_2, \ldots, x_k$$$, and $$$\operatorname{gcd}(x) = x$$$ for any integer $$$x$$$.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you. | Output the maximum value of the function that you can get by reordering elements of the array $$$a$$$. | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_{1}, \, a_{2}, \, \dots, \, a_{n}$$$ ($$$1 \le a_{i} \le 5 \cdot 10^6$$$) — the array $$$a$$$. | standard output | standard input | PyPy 3-64 | Python | 2,100 | train_098.jsonl | 9ee9085d2d85e6408bc743204c76975e | 1024 megabytes | ["6\n2 3 1 2 6 2", "10\n5 7 10 3 1 10 100 3 42 54"] | PASSED | import sys
input = sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))
MAX=max(A)+3
# エラトステネスの篩
# Sieve[i]で、iの最も小さい約数を返す。
Sieve=[i for i in range(MAX)]
for i in range(2,MAX):
if Sieve[i]!=i:
continue
for j in range(i,MAX,i):
if Sieve[j]==j:
Sieve[j]=i
# 素因数分解
def fact(x):
D=dict()
while x!=1:
k=Sieve[x]
if k in D:
D[k]+=1
else:
D[k]=1
x//=k
return D
# 約数列挙
def faclist(x):
LIST=[1]
while x!=1:
k=Sieve[x]
count=0
while x%k==0:
count+=1
x//=k
LIST2=[]
for i in range(count+1):
for l in LIST:
LIST2.append(l*k**i)
LIST=LIST2
return LIST
ANS=[0]*(MAX)
DP=[-1]*(MAX)
for a in A:
for x in faclist(a):
ANS[x]+=1
DP[x]=0
DP[1]=ANS[1]
for i in range(2,MAX):
if DP[i]==-1:
continue
for k in faclist(i):
DP[i]=max(DP[i],DP[k]+ANS[i]*(i-k))
print(max(DP))
| 1637925300 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds | ["0", "1\n2 4", "5\n5 2\n2 3\n3 4\n4 7\n6 8"] | 1bf6e28c366b555664a3a6d2c0ded909 | NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$. | This is the hard version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that: After adding edges, both of their graphs are still forests. They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add. | The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add. Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edge you add each time. If there are multiple correct answers, you can print any one of them. | The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le m_1, m_2 < n$$$) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Diana's forest. | standard output | standard input | PyPy 3 | Python | 2,500 | train_095.jsonl | 4318a30d916c7f2a01651423c9fedd52 | 256 megabytes | ["3 2 2\n1 2\n2 3\n1 2\n1 3", "5 3 2\n5 4\n2 1\n4 3\n4 3\n1 4", "8 1 2\n1 7\n2 6\n1 5"] | PASSED | import collections as _collections
import random as _random
import sys as _sys
def _main():
[tests_n] = [1]
for i_test in range(tests_n):
[n, m_1, m_2] = _read_ints()
edges_1 = tuple(_read_n_egdes(m_1))
edges_2 = tuple(_read_n_egdes(m_2))
new_edges = add_max_edges_n(n, edges_1, edges_2)
print(len(new_edges))
for u, v in new_edges:
print(u+1, v+1)
def add_max_edges_n(nodes_n, edges_1, edges_2):
nodes = list(range(nodes_n))
colors_1 = _DSU.from_equivalence_relations(edges_1, nodes=nodes)
colors_2 = _DSU.from_equivalence_relations(edges_2, nodes=nodes)
del edges_1, edges_2
new_edges = []
while min(len(colors_1.owners), len(colors_2.owners)) > 1:
colors_1, colors_2, nodes, new_new_edges = _try_remove_largest_group(nodes, colors_1, colors_2)
new_edges.extend(new_new_edges)
colors_2, colors_1, nodes, new_new_edges = _try_remove_largest_group(nodes, colors_2, colors_1)
new_edges.extend(new_new_edges)
return new_edges
def _try_remove_largest_group(nodes, colors_1, colors_2):
new_edges = []
def consider_edge(u, v):
if not colors_1.is_same_owner(u, v) and not colors_2.is_same_owner(u, v):
new_edges.append((u, v))
colors_1.merge_owners(u, v)
colors_2.merge_owners(u, v)
largest_owner_1 = max(colors_1.owners, key=lambda owner: len(colors_1.get_group_by_owner(owner)))
largest_1 = set(colors_1.get_group_by_owner(largest_owner_1))
from_largest = next(iter(largest_1))
for node in nodes:
if node != from_largest:
consider_edge(node, from_largest)
if not colors_1.is_same_owner(node, from_largest):
assert colors_2.is_same_owner(node, from_largest)
nontrivial_largest = [x for x in largest_1 if not colors_2.is_same_owner(x, from_largest)]
for node in nodes:
if colors_1.is_same_owner(node, from_largest):
continue
while nontrivial_largest and colors_2.is_same_owner(node, nontrivial_largest[-1]):
nontrivial_largest.pop()
if nontrivial_largest:
consider_edge(node, nontrivial_largest.pop())
nodes = [node for node in nodes if node not in largest_1]
colors_1 = _DSU.from_other_dsu(colors_1, nodes=nodes)
colors_2 = _DSU.from_other_dsu(colors_2, nodes=nodes)
return colors_1, colors_2, nodes, new_edges
class _DSU:
def __init__(self, nodes):
nodes = set(nodes)
self._parents = {node: node for node in nodes}
self._owners = set(nodes)
self._groups_by_owners = {owner: [owner] for owner in nodes}
def _is_owner(self, node):
return node == self._parents[node]
def _get_owner(self, node):
to_fix = []
while not self._is_owner(node):
to_fix.append(node)
node = self._parents[node]
for x in to_fix:
self._parents[x] = node
return node
def is_same_owner(self, node_1, node_2):
return self._get_owner(node_1) == self._get_owner(node_2)
def merge_owners(self, node_1, node_2):
node_1 = self._get_owner(node_1)
node_2 = self._get_owner(node_2)
assert node_1 != node_2
self._parents[node_2] = node_1
self._owners.discard(node_2)
old_groups = [self._groups_by_owners[node_1], self._groups_by_owners[node_2]]
del self._groups_by_owners[node_1], self._groups_by_owners[node_2]
lower_group, higher_group = sorted(old_groups, key=len)
higher_group.extend(lower_group)
lower_group.clear()
self._groups_by_owners[node_1] = higher_group
def get_group_by_owner(self, owner):
return self._groups_by_owners[owner]
@property
def owners(self):
return self._owners
@classmethod
def from_equivalence_relations(cls, equivalence_relations, *, nodes):
self = cls(nodes)
for u, v in equivalence_relations:
if not self.is_same_owner(u, v):
self.merge_owners(u, v)
return self
@classmethod
def from_other_dsu(cls, other_dsu, *, nodes):
nodes = set(nodes)
groups = [other_dsu.get_group_by_owner(owner) for owner in other_dsu.owners]
new_dsu = cls(nodes)
for group in groups:
group = [node for node in group if node in nodes]
if group:
u, *vs = group
for v in vs:
new_dsu.merge_owners(u, v)
return new_dsu
def _read_n_egdes(edges_n):
edges = (_read_ints() for i_edge in range(edges_n))
edges = ((u-1, v-1) for u, v in edges)
return edges
def _read_ints():
return map(int, _read_string().split())
def _read_string():
result = _sys.stdin.readline()
assert result and result[-1] == '\n'
return result[:-1]
if __name__ == '__main__':
_main()
| 1629038100 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
3 seconds | ["1", "0", "0", "1", "0", "2"] | 92afa6f770493109facb1b9ca8d94e0c | NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST. | You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \le w_i$$$). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it. | Print one integer — the minimum number of operations to unify MST of the initial graph without changing the cost of MST. | The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected. | standard output | standard input | Python 3 | Python | 2,100 | train_016.jsonl | a321fd26173999f1cd152127162d06cb | 256 megabytes | ["8 10\n1 2 1\n2 3 2\n2 4 5\n1 4 2\n6 3 3\n6 1 3\n3 5 2\n3 7 1\n4 8 1\n6 2 4", "4 3\n2 1 3\n4 3 4\n2 4 1", "3 3\n1 2 1\n2 3 2\n1 3 3", "3 3\n1 2 1\n2 3 3\n1 3 3", "1 0", "5 6\n1 2 2\n2 3 1\n4 5 3\n2 4 2\n1 4 2\n1 5 3"] | PASSED | import sys
input = sys.stdin.readline
n,m=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(m)]
EDGE.sort(key=lambda x:x[2])
WCHANGE=[]
for i in range(1,m):
if EDGE[i-1][2]!=EDGE[i][2]:
WCHANGE.append(i)
WCHANGE.append(m)
Group=[i for i in range(n+1)]
def find(x):
while Group[x] != x:
x=Group[x]
return x
def Union(x,y):
if find(x) != find(y):
Group[find(y)]=Group[find(x)]=min(find(y),find(x))
NOW=0
noneed=[0]*m
ANS=0
for wc in WCHANGE:
for j in range(NOW,wc):
if find(EDGE[j][0])==find(EDGE[j][1]):
noneed[j]=1
for j in range(NOW,wc):
if noneed[j]==1:
continue
x,y,w=EDGE[j]
if find(x)!=find(y):
Union(x,y)
else:
ANS+=1
NOW=wc
print(ANS)
| 1548254100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["5\n1 2 3 4 5", "6\n1 2 9 4 5 3", "-1"] | e984b4e1120b8fb083a3ebad9bb93709 | NoteIn the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. | Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. | Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m — the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers — numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. | The first line contains n and k (1 ≤ k ≤ n ≤ 105) — the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n — numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≤ ti ≤ n - 1) — the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n — numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. | standard output | standard input | Python 3 | Python | 1,500 | train_006.jsonl | c20814721939efd11bbcc7a1f347d3b9 | 256 megabytes | ["6 2\n5 3\n0\n0\n0\n2 2 1\n1 4\n1 5", "9 3\n3 9 5\n0\n0\n3 9 4 5\n0\n0\n1 8\n1 6\n1 2\n2 1 2", "3 3\n1 2 3\n1 2\n1 3\n1 1"] | PASSED | import collections as col
import itertools as its
import sys
import operator
from copy import copy, deepcopy
class Solver:
def __init__(self):
pass
def solve(self):
n, k = map(int, input().split())
q = list(map(lambda x: int(x) - 1, input().split()))
used = [False] * n
for e in q:
used[e] = True
edges = [[] for _ in range(n)]
redges = [[] for _ in range(n)]
for i in range(n):
l = list(map(lambda x: int(x) - 1, input().split()))[1:]
edges[i] = l
for e in l:
redges[e].append(i)
degs = [len(edges[i]) for i in range(n)]
d = 0
while d < len(q):
v = q[d]
d += 1
for e in edges[v]:
if not used[e]:
used[e] = True
q.append(e)
q = q[::-1]
nq = []
for v in q:
if degs[v] == 0:
nq.append(v)
d = 0
while d < len(nq):
v = nq[d]
d += 1
for e in redges[v]:
if not used[e]:
continue
degs[e] -= 1
if degs[e] == 0:
nq.append(e)
#print(nq)
if len(q) != len(nq):
print(-1)
return
print(len(nq))
print(' '.join(map(lambda x: str(x + 1), nq)))
if __name__ == '__main__':
s = Solver()
s.solve()
| 1489233600 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
0.5 second | ["YES", "YES", "NO"] | d3a0402de1338a1a542a86ac5b484acc | null | There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not. | Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO". | The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood. | standard output | standard input | Python 3 | Python | 1,600 | train_017.jsonl | 1feb2bb7e3510e258a58701d7cb91b79 | 256 megabytes | ["3\n1 1 1", "6\n1 0 1 1 1 0", "6\n1 0 0 1 0 1"] | PASSED | n=int(input())
L=list(map(int,input().split()))
prime=[]
nn=n
i=2
while i*i<=n:
if nn%i==0:
prime.append(i)
while nn%i==0:
nn//=i
i+=1
#print(prime,nn)
if nn!=1:
prime.append(nn)
if prime[0]==2:
prime=prime[1:]
if n%4==0:
prime=[4]+prime
#print(prime)
out=False
for x in prime:
p=n//x
for i in range(p):
f=True
for j in range(i,n,p):
if not L[j]:
f=False
if f:
out=True
#print(p,i)
break
if out:
print("YES")
break
if not out:
print("NO")
| 1301410800 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["fatma\nmona", "likes\nposted"] | b1a86308739067f2b6c9940b564e2648 | null | Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).This priority factor will be affected by three types of actions: 1. "X posted on Y's wall" (15 points), 2. "X commented on Y's post" (10 points), 3. "X likes Y's post" (5 points). X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you. | Print m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order. Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor. The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1 ≤ i ≤ min(|a|, |b|)), that ai < bi, and for any j (1 ≤ j < i) aj = bj, where |a| and |b| stand for the lengths of strings a and b correspondently. | The first line contains your name. The second line contains an integer n, which is the number of actions (1 ≤ n ≤ 100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters. | standard output | standard input | Python 3 | Python | 1,500 | train_013.jsonl | 791614154f3071e5cfd2550bb1ad06a3 | 256 megabytes | ["ahmed\n3\nahmed posted on fatma's wall\nfatma commented on ahmed's post\nmona likes ahmed's post", "aba\n1\nlikes likes posted's post"] | PASSED | r={'posted':15,'commented':10,'likes':5}
n=input()
a={}
m=set()
for _ in '0'*int(input()):
t=input().split()
s=t[0]
p=t[3-(t[1]=='likes')][:-2]
m.add(s)
m.add(p)
if s==n:
a[p]=a.get(p,0)+r[t[1]]
if p==n:
a[s]=a.get(s,0)+r[t[1]]
if n in m:
m.remove(n)
for v in sorted(set(a.values())|set([0]))[::-1]:
print('\n'.join(sorted(s for s in m if a.get(s,0)==v)))
| 1302706800 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds | ["6", "9"] | ca22cf92727a38fbb3c085b9362602db | NoteThe figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example. | Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1. | Print the maximum possible sum of distances in the division of universities into k pairs. | The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n. The second line contains 2k distinct integers u1, u2, ..., u2k (1 ≤ ui ≤ n) — indices of towns in which universities are located. The next n - 1 line contains the description of roads. Each line contains the pair of integers xj and yj (1 ≤ xj, yj ≤ n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads. | standard output | standard input | PyPy 3 | Python | 1,800 | train_021.jsonl | bca5d4900ad1b57488a9095c876c7b89 | 256 megabytes | ["7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6", "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8"] | PASSED | from collections import defaultdict
from sys import stdin
def put(): return map(int, stdin.readline().split())
def dfs():
s = [(1,0)]
ans = 0
vis = [0]*(n+1)
while s:
i,p = s.pop()
if vis[i]==0:
vis[i]=1
s.append((i,p))
for j in tree[i]:
if j!=p:
s.append((j,i))
elif vis[i]==1:
vis[i]=2
for j in tree[i]:
if j != p:
mark[i]+= mark[j]
ans += min(mark[i], 2*k - mark[i])
print(ans)
n,k = put()
l = list(put())
edge = defaultdict()
tree = [[] for i in range(n+1)]
mark = [0]*(n+1)
for i in l:
mark[i]=1
for _ in range(n-1):
x,y = put()
tree[x].append(y)
tree[y].append(x)
dfs() | 1469205300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["YES\n1 2\n3 4\nNO\nYES\n3 4\n7 8\n11 12\n2 1\n6 5\n10 9\nYES\n1 2\n3 4\n5 6\n7 8\n9 10\n11 12\n13 14"] | d4fc7e683f389e0c7bbee8e115cef459 | NoteIn the first test case, splitting into pairs $$$(1, 2)$$$ and $$$(3, 4)$$$ is suitable, same as splitting into $$$(1, 4)$$$ and $$$(3, 2)$$$.In the second test case, $$$(1 + 0) \cdot 2 = 1 \cdot (2 + 0) = 2$$$ is not divisible by $$$4$$$, so there is no partition. | A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $$$n$$$ and $$$k$$$, where $$$n$$$ is even. Next, he takes all the integers from $$$1$$$ to $$$n$$$, and splits them all into pairs $$$(a, b)$$$ (each integer must be in exactly one pair) so that for each pair the integer $$$(a + k) \cdot b$$$ is divisible by $$$4$$$ (note that the order of the numbers in the pair matters), or reports that, unfortunately for viewers, such a split is impossible.Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $$$n$$$ and $$$k$$$.Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it. | For each test case, first output the string "YES" if there is a split into pairs, and "NO" if there is none. If there is a split, then in the following $$$\frac{n}{2}$$$ lines output pairs of the split, in each line print $$$2$$$ numbers — first the integer $$$a$$$, then the integer $$$b$$$. | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The single line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$, $$$0 \leq k \leq 10^9$$$, $$$n$$$ is even) — the number of integers and the number being added $$$k$$$. 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 | 800 | train_090.jsonl | f8d305b6370b60602a0a646b9b4a4d42 | 256 megabytes | ["4\n\n4 1\n\n2 0\n\n12 10\n\n14 11"] | PASSED | tests = int(input())
def solve(n, k):
if(k&1):
print("YES")
for i in range(1, n+1, 2):
print(str(i) + " " + str(i+1))
else:
if(k % 4 == 0):
print("NO")
else:
print("YES")
for i in range(1, n+1, 4):
print(str(i+1) + " " + str(i))
if(i+3 <= n):
print(str(i+2) + " " + str(i+3))
for _ in range(tests):
n, k = [int(i) for i in input().split(" ")]
solve(n, k)
| 1660660500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds | ["1 1\n1 1\n2 0\n3 1\n2 4\n5 4", "4 3\n2 5\n2 1\n2 5\n1 5\n4 1\n1 2\n3 2"] | b021a3c7ae119671c81c51da7cfabdb3 | null | You are given $$$n$$$ distinct points on a plane. The coordinates of the $$$i$$$-th point are $$$(x_i, y_i)$$$.For each point $$$i$$$, find the nearest (in terms of Manhattan distance) point with integer coordinates that is not among the given $$$n$$$ points. If there are multiple such points — you can choose any of them.The Manhattan distance between two points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$. | Print $$$n$$$ lines. In the $$$i$$$-th line, print the point with integer coordinates that is not among the given $$$n$$$ points and is the nearest (in terms of Manhattan distance) to the $$$i$$$-th point from the input. Output coordinates should be in range $$$[-10^6; 10^6]$$$. It can be shown that any optimal answer meets these constraints. If there are several answers, you can print any of them. | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points in the set. The next $$$n$$$ lines describe points. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le 2 \cdot 10^5$$$) — coordinates of the $$$i$$$-th point. It is guaranteed that all points in the input are distinct. | standard output | standard input | PyPy 3 | Python | 1,900 | train_104.jsonl | 3241226f7d89dd9a4757c78b68f8a6c6 | 256 megabytes | ["6\n2 2\n1 2\n2 1\n3 2\n2 3\n5 5", "8\n4 4\n2 4\n2 2\n2 3\n1 4\n4 2\n1 3\n3 3"] | PASSED | # def redirect_io():
# import pathlib, sys
# fname = pathlib.Path(__file__).parent/"input.txt"
# sys.stdin = open(fname, 'r')
# redirect_io()
import sys
input = sys.stdin.buffer.readline
from collections import deque
# NOTE: Got MLE's originally, space optimal to just keep hashmap (have access to points)
def solve(points_id: dict) -> list:
# identify surrounding neighborhood
dx_ = [1, -1, 0, 0]
dy_ = [0, 0, 1, -1]
d = deque() # stores (cur_pt, starting_pt), answer for cur_pt is staring_pt
for x,y in points_id:
for i in range(4):
dx, dy = dx_[i], dy_[i]
if (x+dx, y+dy) in points_id:
continue
d.append((x+dx, y+dy, x+dx, y+dy)) # these are start_points
n = len(points_id)
ans = [(0,0)] * n
# starts out having 4 * len(points)
# multi-source bfs
while d:
cx, cy, sx, sy = d.popleft()
# search towards "surrounding boundary" towards center
# think of water ripples
for i in range(4):
dx, dy = dx_[i], dy_[i]
nx, ny = cx + dx, cy + dy
if (nx, ny) not in points_id: # only add points that head towards all_points
continue
d.append((nx, ny, sx, sy))
ans[points_id[(nx, ny)]] = (sx, sy)
points_id.pop((nx, ny)) # so you cannot revisit an original point multiple times
return ans
points_id = {}
for i in range(int(input())):
x,y = map(int, input().split())
points_id[(x,y)] = i
ans = solve(points_id)
ans = [f"{x} {y}" for x,y in ans]
# ans = [f"{x} {y}" for x,y in ans]
print('\n'.join(ans))
| 1646922900 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["11", "14", "36"] | 189a8a9a6e99ed52bda9a5773bf2621b | null | There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b).Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card.Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. | Print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. | The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces. | standard output | standard input | Python 3 | Python | 2,200 | train_011.jsonl | ac1c209e4a0a35c1c535a917c9b2ccb2 | 256 megabytes | ["1 6\n2", "1 6\n7", "2 10\n13 7"] | PASSED | # written with help of editorial
n, m = map(int, input().split())
a = list(map(int, input().split()))
def gcd(x, y):
while y:
x, y = y, x % y
return x
g = 0
for x in a:
g = gcd(g, x - 1)
answer = 0
def process(x):
global answer
if x % 2 == 0:
return 0
for i in range(30):
v = 2 ** i * x
if v > m:
break
answer += m - v
for i in range(1, g + 1):
if i * i > g:
break
if g % i:
continue
process(i)
if i * i != g:
process(g // i)
print(answer)
| 1360596600 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["6", "2", "2"] | 16d4035b138137bbad247ccd5e560051 | null | One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. | Print a single integer — the maximum length of a repost chain. | The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. | standard output | standard input | Python 3 | Python | 1,200 | train_027.jsonl | 42d7229f42127e235f0fdac93052e2ea | 256 megabytes | ["5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya", "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp", "1\nSoMeStRaNgEgUe reposted PoLyCaRp"] | PASSED | from collections import defaultdict
n=int(input())
d=defaultdict(list)
for i in range(n):
s=list(map(str,input().split()))
for i in range(3):
s[i]=s[i].lower()
d[s[2]].append(s[0])
q=list()
q.append('polycarp')
q.append(None)
c=0
b=1
while q:
a=q[0]
q.pop(0)
b-=1
if a==None :
c+=1
q.append(None)
else:
if a in d:
a=d[a]
b=len(a)
for i in range(len(a)):
q.append(a[i])
if len(q)==1:
c+=1
break
print(c)
| 1425740400 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["0\n36\n0\n0\n1999999994\n1999999994\n2\n4"] | 18f2e54e4147e8887da737d5b6639473 | null | Three friends are going to meet each other. Initially, the first friend stays at the position $$$x = a$$$, the second friend stays at the position $$$x = b$$$ and the third friend stays at the position $$$x = c$$$ on the coordinate axis $$$Ox$$$.In one minute each friend independently from other friends can change the position $$$x$$$ by $$$1$$$ to the left or by $$$1$$$ to the right (i.e. set $$$x := x - 1$$$ or $$$x := x + 1$$$) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $$$a'$$$, $$$b'$$$ and $$$c'$$$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $$$|a' - b'| + |a' - c'| + |b' - c'|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer $$$q$$$ independent test cases. | For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute. | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of test cases. The next $$$q$$$ lines describe test cases. The $$$i$$$-th test case is given as three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal. | standard output | standard input | Python 3 | Python | 900 | train_021.jsonl | e0ce1c983175912654155578f9c9eaf9 | 256 megabytes | ["8\n3 3 4\n10 20 30\n5 5 5\n2 4 3\n1 1000000000 1000000000\n1 1000000000 999999999\n3 2 5\n3 2 6"] | PASSED | for _ in range(int(input())):
a, b, c = map(int, input().split())
x = abs(a - b) + abs(a - c) + abs(b - c)
print(max(0, x - 4))
| 1576157700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nNO"] | d53575e38f79990304b679ff90c5de34 | NoteIn first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana. | Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.Also Vova can fight monsters. Every monster is characterized by two values tj and hj — monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.You have to write a program which can answer two types of queries: 1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second. 2 t h — Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.For every query of second type you have to determine if Vova is able to win the fight with corresponding monster. | For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise. | The first line contains two integer numbers q and m (2 ≤ q ≤ 105, 1 ≤ m ≤ 1012) — the number of queries and the amount of mana at the beginning of every fight. i-th of each next q lines contains three numbers ki, ai and bi (1 ≤ ki ≤ 2, 1 ≤ ai, bi ≤ 106). Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these). If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1. If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1. | standard output | standard input | Python 3 | Python | 3,100 | train_077.jsonl | 4fda2ed51bffa6f0d333cf63e278d633 | 256 megabytes | ["3 100\n1 4 9\n2 19 49\n2 19 49"] | PASSED | #!/usr/bin/env python3
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _/
def is_right(xy0, xy1, xy):
(x0, y0) = xy0
(x1, y1) = xy1
(x, y) = xy
return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)
def in_chull(x, y):
i = 0
if x > spell_chull[-1][0]:
return False
while spell_chull[i][0] < x:
i += 1
if spell_chull[i][0] == x:
return spell_chull[i][1] <= y
else:
return is_right(spell_chull[i - 1], spell_chull[i], (x, y))
def add_spell(x, y):
global spell_chull
if in_chull(x, y):
return
i_left = 0
while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
i_left += 1
i_right = i_left + 1
while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
i_right += 1
if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
i_right += 1
spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]
for i, qi in enumerate(qis):
(k, a, b) = qi
x = (a + j) % mod + 1
y = (b + j) % mod + 1
if k == 1:
add_spell(x, y)
else: #2
if in_chull(y / x, m / x):
print ('YES')
j = i + 1
else:
print ('NO')
| 1490625300 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
4 seconds | ["1 2", "2 4", "1 4"] | acb7acc82c52db801f515631dca20eba | null | You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$.Your problem is to find such pair of indices $$$i, j$$$ ($$$1 \le i < j \le n$$$) that $$$lcm(a_i, a_j)$$$ is minimum possible.$$$lcm(x, y)$$$ is the least common multiple of $$$x$$$ and $$$y$$$ (minimum positive number such that both $$$x$$$ and $$$y$$$ are divisors of this number). | Print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i < j \le n$$$) such that the value of $$$lcm(a_i, a_j)$$$ is minimum among all valid pairs $$$i, j$$$. If there are multiple answers, you can print any. | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 10^6$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | standard output | standard input | PyPy 2 | Python | 2,200 | train_003.jsonl | 5cc950bc4d43701630f80ed0f9ff6dfa | 1024 megabytes | ["5\n2 4 8 3 6", "5\n5 2 11 3 7", "6\n2 5 10 1 10 2"] | PASSED | import math
import re
import sys
from collections import defaultdict
def read(type = int):
return type(raw_input())
def read_list(type = int, split = ' ', F = None):
if F:
return map(lambda x: F(type(x)), raw_input().split(split))
return map(type, raw_input().split(split))
def read_list_of_list(N, type = int, split = ' ', F = None):
return [read_list(type, F = F) for _ in xrange(N)]
def solve():
N = read()
A = read_list()
C = {}
X = 3163
E = [1]*X
P = []
p = 2
while p < X:
if E[p]:
P += [p]
x = p
while x<X:
E[x] = 0
x += p
p += 1
LP = len(P)
Cm = {}
CM = {}
M = 1e30
for a in sorted(A):
if a >= M:
break
b = a
D = set([1])
p = 0
while a and p < LP:
while a%P[p]==0:
D.update(set(d*P[p] for d in D))
a /= P[p]
p += 1
if a > 1:
D.update(set(d*a for d in D))
for d in D:
if d not in Cm:
Cm[d] = b
elif d not in CM:
CM[d] = b
if M > Cm[d]*CM[d]/d:
x, y = Cm[d], CM[d]
M = Cm[d] * CM[d] / d
l1 = A.index(x)
if x==y:
l2 = l1 + 1 + A[l1+1:].index(y)
else:
l2 = A.index(y)
l1 += 1
l2 += 1
if l1<l2:
print l1,l2
else:
print l2,l1
solve() | 1555425300 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["3\n1 0 2 \n3\n1 1 2\n1\n0"] | e21f235ffe7f26d9a7af12a7f3f9a2fd | NoteIn the first test case, the following process results in bacteria with total mass $$$9$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$ each. Night $$$1$$$: All bacteria's mass increases by one. There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: None split. Night $$$2$$$: There are now two bacteria with mass $$$2.5$$$. Day $$$3$$$: Both bacteria split. There are now four bacteria with mass $$$1.25$$$. Night $$$3$$$: There are now four bacteria with mass $$$2.25$$$. The total mass is $$$2.25+2.25+2.25+2.25=9$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights.$$$ $$$In the second test case, the following process results in bacteria with total mass $$$11$$$: Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$. Night $$$1$$$: There are now two bacteria with mass $$$1.5$$$. Day $$$2$$$: One bacterium splits. There are now three bacteria with masses $$$0.75$$$, $$$0.75$$$, and $$$1.5$$$. Night $$$2$$$: There are now three bacteria with masses $$$1.75$$$, $$$1.75$$$, and $$$2.5$$$. Day $$$3$$$: The bacteria with mass $$$1.75$$$ and the bacteria with mass $$$2.5$$$ split. There are now five bacteria with masses $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$, and $$$1.75$$$. Night $$$3$$$: There are now five bacteria with masses $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$, and $$$2.75$$$. The total mass is $$$1.875+1.875+2.25+2.25+2.75=11$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights.$$$ $$$In the third test case, the bacterium does not split on day $$$1$$$, and then grows to mass $$$2$$$ during night $$$1$$$. | Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist! | For each test case, if there is no way for the bacteria to exactly achieve total mass $$$n$$$, print -1. Otherwise, print two lines. The first line should contain an integer $$$d$$$ — the minimum number of nights needed. The next line should contain $$$d$$$ integers, with the $$$i$$$-th integer representing the number of bacteria that should split on the $$$i$$$-th day. If there are multiple solutions, print any. | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the sum of bacteria masses that Phoenix is interested in. | standard output | standard input | Python 3 | Python | 1,900 | train_008.jsonl | ae6833ee413cffa26830e7570a13cafb | 256 megabytes | ["3\n9\n11\n2"] | PASSED | for _ in range(int(input())):
arr = []
n = int(input())
x = 1
while x < n:
arr.append(x)
n -= x
x *= 2
if n > 0:
arr.append(n)
arr.sort()
s = []
print(len(arr)-1)
for i in range(len(arr)-1):
s.append(arr[i+1]-arr[i])
print(*s)
| 1588343700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["19 8\n-1\n-1\n-1\n2000000000 1000000000\n0"] | d6721fb3dd02535fc08fc69a4811d60c | null | For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.This generator takes four non-negative numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$. $$$n$$$ and $$$m$$$ must be positive, $$$s$$$ non-negative and for $$$c$$$ it must be true that $$$0 \leq c < m$$$. The array $$$a$$$ of length $$$n$$$ is created according to the following rules: $$$a_1 = s \bmod m$$$, here $$$x \bmod y$$$ denotes remainder of the division of $$$x$$$ by $$$y$$$; $$$a_i = (a_{i-1} + c) \bmod m$$$ for all $$$i$$$ such that $$$1 < i \le n$$$. For example, if $$$n = 5$$$, $$$m = 7$$$, $$$c = 4$$$, and $$$s = 10$$$, then $$$a = [3, 0, 4, 1, 5]$$$.Price of such an array is the value of $$$m$$$ in this generator.Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$ that generate this array. If yes, then maximize $$$m$$$. | For every array print: $$$-1$$$, if there are no such four numbers that generate this array; $$$0$$$, if $$$m$$$ can be arbitrary large; the maximum value $$$m$$$ and any appropriate $$$c$$$ ($$$0 \leq c < m$$$) in other cases. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of arrays. The first line of array description contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of this array. The second line of array description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$ ) — elements of the array. It is guaranteed that the sum of array sizes does not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,500 | train_092.jsonl | 96385ea75a3f003e972a1f3f84e717f8 | 256 megabytes | ["6\n6\n1 9 17 6 14 3\n3\n4 2 2\n3\n7 3 4\n3\n2 2 4\n5\n0 1000000000 0 1000000000 0\n2\n1 1"] | PASSED | def fun(a,n):
if n == 1 or n == 2:
return 0
p = set()
for i in range(1,n):
p.add(a[i]-a[i-1])
p = list(p)
p.sort()
if len(p) > 2:
return -1
elif len(p) == 2:
m = p[1]+(abs(p[0]) if p[0]<0 else -p[0])
c = p[1]
if m <= max(a):
return -1
for i in range(1,n):
if a[i] != (a[i-1]+c)%m:
return -1
return m, c
elif len(p) == 1:
return 0
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
try:
print(*fun(a, n))
except:
print(fun(a,n)) | 1616322000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n2\n2\n5"] | 130fdf010c228564611a380b6dd37a34 | NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$. | We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal? | For each test case output the minimum number of operations needed. | The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. 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,700 | train_083.jsonl | 084838375de70eaf0619dec6dded977e | 256 megabytes | ["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"] | PASSED | import collections, math, bisect, heapq, random, functools, itertools, copy, typing
import platform; LOCAL = (platform.uname().node == 'AMO')
# Fast IO Region
import os, sys; from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def debug(*args):
if LOCAL:
print('\033[92m', end='')
printf(*args)
print('\033[0m', end='')
def printf(*args):
if LOCAL:
print('>>>: ', end='')
for arg in args:
if isinstance(arg, typing.Iterable) and \
not isinstance(arg, str) and \
not isinstance(arg, dict):
print(' '.join(map(str, arg)), end=' ')
else:
print(arg, end=' ')
print()
for _ in range(int(input())):
n = int(input())
p = list(map(lambda x: int(x)-1, input().split()))
l, r = [], []
for i in range(n):
a, b = map(int, input().split())
l.append(a)
r.append(b)
g = [[] for _ in range(n)]
for i, x in enumerate(p):
g[x].append(i+1)
a = [0] * n
ans = 0
for u in range(n-1, -1, -1):
for v in g[u]:
a[u] += a[v]
a[u] = min(a[u], r[u])
if a[u] < l[u]:
ans += 1
a[u] = r[u]
print(ans)
| 1655390100 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second | ["3\n19 11\n15 9\n3 7", "-1", "1\n15 8", "-1"] | d1e4269be1f81875c163c15a0759df88 | NoteIn the first sample let's consider the array $$$t$$$ for each pair: $$$(19,\, 11)$$$: $$$t = [8, 3, 2, 1]$$$; $$$(15,\, 9)$$$: $$$t = [6, 3]$$$; $$$(3,\, 7)$$$: $$$t = [1]$$$. So in total $$$t = [8, 3, 2, 1, 6, 3, 1]$$$, which is the same as the input $$$t$$$ (up to a permutation).In the second test case it is impossible to find such array $$$p$$$ of pairs that all integers are not greater than $$$10$$$ and $$$t = [7, 1]$$$In the third test case for the pair $$$(15,\, 8)$$$ array $$$t$$$ will be $$$[7, 1]$$$. | Let's consider Euclid's algorithm for finding the greatest common divisor, where $$$t$$$ is a list:function Euclid(a, b): if a < b: swap(a, b) if b == 0: return a r = reminder from dividing a by b if r > 0: append r to the back of t return Euclid(b, r)There is an array $$$p$$$ of pairs of positive integers that are not greater than $$$m$$$. Initially, the list $$$t$$$ is empty. Then the function is run on each pair in $$$p$$$. After that the list $$$t$$$ is shuffled and given to you.You have to find an array $$$p$$$ of any size not greater than $$$2 \cdot 10^4$$$ that produces the given list $$$t$$$, or tell that no such array exists. | If the answer does not exist, output $$$-1$$$. If the answer exists, in the first line output $$$k$$$ ($$$1 \le k \le 2 \cdot 10^4$$$) — the size of your array $$$p$$$, i. e. the number of pairs in the answer. The $$$i$$$-th of the next $$$k$$$ lines should contain two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le m$$$) — the $$$i$$$-th pair in $$$p$$$. If there are multiple valid answers you can output any of them. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le m \le 10^9$$$) — the length of the array $$$t$$$ and the constraint for integers in pairs. The second line contains $$$n$$$ integers $$$t_1, t_2, \ldots, t_n$$$ ($$$1 \le t_i \le m$$$) — the elements of the array $$$t$$$. | standard output | standard input | PyPy 3 | Python | 2,800 | train_103.jsonl | 5d2a0f28f67fcbeea892ef652a817c55 | 256 megabytes | ["7 20\n1 8 1 6 3 2 3", "2 10\n7 1", "2 15\n1 7", "1 1000000000\n845063470"] | PASSED | # import io,os
# read = io.BytesIO(os.read(0, os.fstat(0).st_size))
# I = lambda: [*map(int, read.readline().split())]
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
n, m = I()
t = I()
bad = []
for guy in t:
if m < 2 * guy + 1:
print(-1)
exit()
elif m < 3 * guy:
bad.append(guy)
out = []
counts = {}
for guy in t:
if guy in counts:
counts[guy] += 1
else:
counts[guy] = 1
for guy in bad:
counts[guy] -= 1
biggest = 0
for boi in counts:
if counts[boi] > 0 and guy % boi == 0 and boi + 2 * guy <= m:
biggest = boi
if biggest == 0:
print(-1)
exit()
else:
counts[biggest] -= 1
out.append((guy + biggest, 2 * guy + biggest))
for guy in counts:
for i in range(counts[guy]):
out.append((2 * guy, 3 * guy))
print(len(out))
for guy in out:
print(*guy) | 1652970900 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["25\n42\n35"] | 2c67ee95eba7ffbbed99cb488abb5f3d | NoteThe points in the first testcase of the example: $$$(1, 0)$$$, $$$(2, 0)$$$; $$$(2, 8)$$$, $$$(3, 8)$$$, $$$(4, 8)$$$; $$$(0, 1)$$$, $$$(0, 4)$$$, $$$(0, 6)$$$; $$$(5, 4)$$$, $$$(5, 5)$$$. The largest triangle is formed by points $$$(0, 1)$$$, $$$(0, 6)$$$ and $$$(5, 4)$$$ — its area is $$$\frac{25}{2}$$$. Thus, the doubled area is $$$25$$$. Two points that are on the same side are: $$$(0, 1)$$$ and $$$(0, 6)$$$. | A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that: exactly two of them belong to the same side of a rectangle; the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer. | For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,000 | train_095.jsonl | ce5a497333c5150c253d7ad1f2606384 | 256 megabytes | ["3\n5 8\n2 1 2\n3 2 3 4\n3 1 4 6\n2 4 5\n10 7\n2 3 9\n2 1 7\n3 1 3 4\n3 4 5 6\n11 5\n3 1 6 8\n3 3 6 8\n3 1 3 4\n2 2 4"] | PASSED | def base(arr):
return abs(arr[-1]-arr[1])
for _ in range(int(input())):
n,m=map(int,input().split())
h1=list(map(int,input().split()))
h2=list(map(int,input().split()))
v1=list(map(int,input().split()))
v2=list(map(int,input().split()))
print(max(max(base(h1),base(h2))*m,max(base(v1),base(v2))*n)) | 1639841700 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["4\n2\n0\n4\n0", "4\n2"] | c61f07f38156a6038a9bc57da9b65ea9 | NoteThe bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself. | Ehab has an array a of n integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?A subsequence can contain elements that are not neighboring. | For each query, output its answer modulo 109 + 7 in a newline. | The first line contains integers n and q (1 ≤ n, q ≤ 105), the number of elements in the array and the number of queries. The next line contains n integers a1, a2, ..., an (0 ≤ ai < 220), the elements of the array. The next q lines, each contains integers l and x (1 ≤ l ≤ n, 0 ≤ x < 220), representing the queries. | standard output | standard input | PyPy 2 | Python | 2,400 | train_066.jsonl | 74ea04621b243e6589c7b03e436547bd | 512 megabytes | ["5 5\n0 1 2 3 4\n4 3\n2 0\n3 7\n5 7\n5 8", "3 2\n1 1 1\n3 1\n2 0"] | PASSED | import sys
range = xrange
input = raw_input
MOD = 10**9 + 7
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
q = inp[ii]; ii += 1
A = inp[ii: ii + n]; ii += n
zeros = [1]
Abase = []
base = []
for i in range(n):
a = A[i]
for b in base:
if a ^ b < a:
a ^= b
if a:
base = list(base)
base.append(a)
base.sort(reverse = True)
zeros.append(zeros[-1])
else:
zeros.append(zeros[-1] * 2 % MOD)
Abase.append(base)
out = []
for _ in range(q):
l = inp[ii] - 1; ii += 1
x = inp[ii]; ii += 1
for b in Abase[l]:
if x ^ b < x:
x ^= b
out.append(0 if x else zeros[l + 1])
print '\n'.join(str(x) for x in out)
| 1522771500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n3", "2\n3 4", "0", "1\n999999998"] | b96427767128e235d46bea8d5c4cbbaf | NoteIn the first test, $$$p=2$$$. If $$$x \le 2$$$, there are no valid permutations for Yuzu. So $$$f(x)=0$$$ for all $$$x \le 2$$$. The number $$$0$$$ is divisible by $$$2$$$, so all integers $$$x \leq 2$$$ are not good. If $$$x = 3$$$, $$$\{1,2,3\}$$$ is the only valid permutation for Yuzu. So $$$f(3)=1$$$, so the number $$$3$$$ is good. If $$$x = 4$$$, $$$\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}$$$ are all valid permutations for Yuzu. So $$$f(4)=4$$$, so the number $$$4$$$ is not good. If $$$x \ge 5$$$, all $$$6$$$ permutations are valid for Yuzu. So $$$f(x)=6$$$ for all $$$x \ge 5$$$, so all integers $$$x \ge 5$$$ are not good. So, the only good number is $$$3$$$.In the third test, for all positive integers $$$x$$$ the value $$$f(x)$$$ is divisible by $$$p = 3$$$. | This is the hard version of the problem. The difference between versions is the constraints on $$$n$$$ and $$$a_i$$$. You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has $$$x$$$ candies. There are also $$$n$$$ enemies numbered with integers from $$$1$$$ to $$$n$$$. Enemy $$$i$$$ has $$$a_i$$$ candies.Yuzu is going to determine a permutation $$$P$$$. A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$\{2,3,1,5,4\}$$$ is a permutation, but $$$\{1,2,2\}$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$\{1,3,4\}$$$ is also not a permutation (because $$$n=3$$$ but there is the number $$$4$$$ in the array).After that, she will do $$$n$$$ duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy $$$P_i$$$, she wins the duel and gets $$$1$$$ candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations $$$P$$$ exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define $$$f(x)$$$ as the number of valid permutations for the integer $$$x$$$.You are given $$$n$$$, $$$a$$$ and a prime number $$$p \le n$$$. Let's call a positive integer $$$x$$$ good, if the value $$$f(x)$$$ is not divisible by $$$p$$$. Find all good integers $$$x$$$.Your task is to solve this problem made by Akari. | In the first line, print the number of good integers $$$x$$$. In the second line, output all good integers $$$x$$$ in the ascending order. It is guaranteed that the number of good integers $$$x$$$ does not exceed $$$10^5$$$. | The first line contains two integers $$$n$$$, $$$p$$$ $$$(2 \le p \le n \le 10^5)$$$. It is guaranteed, that the number $$$p$$$ is prime (it has exactly two divisors $$$1$$$ and $$$p$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$. | standard output | standard input | PyPy 3 | Python | 2,300 | train_033.jsonl | 8e7f812ab7c09ce85936d67c3f1ba480 | 256 megabytes | ["3 2\n3 4 5", "4 3\n2 3 5 6", "4 3\n9 1 1 1", "3 2\n1000000000 1 999999999"] | PASSED | import sys
import collections
def input():
return sys.stdin.readline().rstrip()
def split_input():
return [int(i) for i in input().split()]
n,p = split_input()
a = split_input()
start = max(a) - n + 1
x = [0 for i in range(n)]
for i in a:
ind = i - start
if ind <= 0:
x[0] += 1
else:
x[ind] += 1
for i in range(1,n):
x[i] += x[i-1]
zero_ind = -1
for i in range(n):
zero_ind = max(i - x[i], zero_ind)
s = set()
for i in range(zero_ind+1, n):
if x[i] >= p:
# t = p
# while (x[i] >= t):
# s.add(i - (x[i] - t))
# t += p
s.add((i + start - x[i])%p)
ans = []
for i in range(zero_ind + 1, p):
if (i+start)%p not in s:
ans.append(i + start)
print(len(ans))
print(*ans, sep = " ") | 1593610500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["# include <cstdio>\nusingnamespacestd;intmain(){puts(\"Hello#World\");#\n#\n}", "#\n\n#"] | a16bb696858bc592c33dcf0fd99df197 | NoteIn the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other. | Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output. | Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline. Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter. | The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 ( = 220) bytes. Newlines are included in this size. In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one. It is guaranteed that the input contains at least one character other than a newline. It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means. | standard output | standard input | PyPy 2 | Python | 1,700 | train_022.jsonl | 1a4a78ec10ba184a0b9273620183bdc7 | 256 megabytes | ["# include <cstdio>\n\nusing namespace std;\n\nint main ( ){\nputs(\"Hello # World\"); #\n#\n}", "#\n\n#"] | PASSED | lis = []
while True:
try:
val = raw_input()
isAmplifying = False
for c in val:
if not c.isspace():
if c == "#":
isAmplifying = True
break
else:
break
if isAmplifying:
lis.append((val, True))
else:
lis.append(("".join(val.split()), False))
except (EOFError):
break
index = 0
result = []
while index < len(lis):
if lis[index][1] == True:
print lis[index][0]
else:
lisss = []
while index < len(lis) and lis[index][1] != True:
lisss.append(lis[index][0])
index += 1
index -= 1
print "".join(lisss)
index += 1
for r in result:
print r
| 1332860400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["4\n0 1 2 3\n2\n0 2\n2\n2 3"] | 04a37e9c68761f9a2588c0bbecad2147 | NoteIn the first test case, any number of breaks between $$$0$$$ and $$$3$$$ could happen during the match: Alice holds serve, Borys holds serve, Alice holds serve: $$$0$$$ breaks; Borys holds serve, Alice holds serve, Alice breaks serve: $$$1$$$ break; Borys breaks serve, Alice breaks serve, Alice holds serve: $$$2$$$ breaks; Alice breaks serve, Borys breaks serve, Alice breaks serve: $$$3$$$ breaks. In the second test case, the players could either both hold serves ($$$0$$$ breaks) or both break serves ($$$2$$$ breaks).In the third test case, either $$$2$$$ or $$$3$$$ breaks could happen: Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve: $$$2$$$ breaks; Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve: $$$3$$$ breaks. | Alice and Borys are playing tennis.A tennis match consists of games. In each game, one of the players is serving and the other one is receiving.Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa.Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve.It is known that Alice won $$$a$$$ games and Borys won $$$b$$$ games during the match. It is unknown who served first and who won which games.Find all values of $$$k$$$ such that exactly $$$k$$$ breaks could happen during the match between Alice and Borys in total. | For each test case print two lines. In the first line, print a single integer $$$m$$$ ($$$1 \le m \le a + b + 1$$$) — the number of values of $$$k$$$ such that exactly $$$k$$$ breaks could happen during the match. In the second line, print $$$m$$$ distinct integers $$$k_1, k_2, \ldots, k_m$$$ ($$$0 \le k_1 < k_2 < \ldots < k_m \le a + b$$$) — the sought values of $$$k$$$ in increasing order. | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. Each of the next $$$t$$$ lines describes one test case and contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^5$$$; $$$a + b > 0$$$) — the number of games won by Alice and Borys, respectively. It is guaranteed that the sum of $$$a + b$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,300 | train_086.jsonl | 91fe744b5f1d05510066faf7c91f39fc | 512 megabytes | ["3\n2 1\n1 1\n0 5"] | PASSED | for _ in range(int(input())):
a, b = list(map(int, input().split()))
if a == 0 and b == 0:
print(0)
elif a == 0 or b == 0:
if a == 0 and b % 2 == 1:
print(2)
print(b // 2, b // 2 + 1)
elif b == 0 and a % 2 == 1:
print(2)
print(a // 2, a // 2 + 1)
elif a == 0 and b % 2 == 0:
print(1)
print(b // 2)
elif b == 0 and a % 2 == 0:
print(1)
print(a // 2)
else:
if (a + b) % 2 == 0:
if b > a:
b, a = a, b
c = 2 * b
a -= b
if a % 2 == 0:
d = a // 2
e = a // 2
else:
d = a // 2
e = d + 1
arr = [i for i in range(d, e + c + 1, 2)]
print(len(arr))
print(*arr, sep=" ")
else:
if b > a:
b, a = a, b
c = 2 * b
a -= b
if a % 2 == 0:
d = a // 2
e = a // 2
else:
d = a // 2
e = d + 1
arr = [i for i in range(d, e + c + 1)]
print(len(arr))
print(*arr, sep=" ")
| 1629815700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["YES\n4 2 4\nYES\n55 5 5 35\nNO\nNO\nYES\n1 1 1 1 1 1 1 1\nNO\nYES\n3 1 1\nYES\n111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120"] | 6b94dcd088b0328966b54acefb5c6d22 | null | You are given two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it. | For each test case print: YES and the required values $$$a_i$$$, if the answer exists (if there are several answers, print any of them); NO if the answer does not exist. The letters in the words YES and NO can be printed in any case. | The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$). | standard output | standard input | Python 3 | Python | 1,200 | train_004.jsonl | 28b8458492b817a649cc5bbd13c90cef | 256 megabytes | ["8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9"] | PASSED | t = input()
t = int(t)
while t > 0 :
line = input()
i = line.split()
x = int(i[0])
y = int(i[1])
o = x - (y-1)
if o%2==1 and o>0 :
print('YES')
for j in range(y-1) :
print('1', end = " ")
print(o)
t = t-1
continue
e = x - (y-1)*2
if e%2==0 and e>0 :
print('YES')
for j in range(y-1) :
print("2", end = " ")
print(e)
else :
print("NO")
t = t - 1
| 1589034900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n2 1 4", "NO", "0"] | 0939354d9bad8301efb79a1a934ded30 | null | A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions.Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2. | Print "NO" (without quotes), if such sequence of transfusions does not exist. Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2·n2). In the following k lines print transfusions in the format x y d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer. | First line of the input contains integers n, v, e (1 ≤ n ≤ 300, 1 ≤ v ≤ 109, 0 ≤ e ≤ 50000). Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≤ ai, bi ≤ v). Next e lines describe one tube each in the format x y (1 ≤ x, y ≤ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way. | standard output | standard input | Python 2 | Python | 2,500 | train_054.jsonl | e29f2f49edcc8cf58b9affe1ec2e357f | 256 megabytes | ["2 10 1\n1 9\n5 5\n1 2", "2 10 0\n5 2\n4 2", "2 10 0\n4 2\n4 2"] | PASSED | n,v,e=map(int,raw_input().split())
a=[0]*(n+10)
b=[0]*(n+10)
E=[[] for i in xrange(n)]
f=[i for i in xrange(n)]
vis=[0]*(n+10)
ans=[]
rem=0
def fd(x):
if f[x]==x: return x
else:
f[x]=fd(f[x])
return f[x]
def dfs2(u,f,ty):
global rem
if rem<=a[u] and rem>0:
if ty==0: ans.append([u,f,rem])
else: ans.append([f,u,rem])
a[u]-=rem
a[f]+=rem
rem=0
else:
rem-=a[u]
for v in E[u]:
if v==f or vis[v]: continue
dfs2(v,u,ty)
if rem==0: break
if f!=-1:
if ty==0: ans.append([u,f,a[u]])
else: ans.append([f,u,a[u]])
a[f]+=a[u]
a[u]=0
def solve(c):
if a[c]==b[c]: return
global rem
if a[c]<b[c]:
rem=b[c]
dfs2(c,-1,0)
else:
for i in xrange(n): a[i],b[i]=v-a[i],v-b[i]
rem=b[c]
dfs2(c,-1,1)
for i in xrange(n): a[i],b[i]=v-a[i],v-b[i]
def dfs(u,f):
for v in E[u]:
if v==f: continue
dfs(v,u)
solve(u)
vis[u]=1
a=map(int,raw_input().split())
b=map(int,raw_input().split())
for i in xrange(e):
x,y=map(lambda x:int(x)-1,raw_input().split())
if fd(x)!=fd(y):
E[x].append(y)
E[y].append(x)
f[fd(x)]=fd(y)
for i in xrange(n):
if fd(i)!=i: continue
sa=sum(a[j] for j in xrange(n) if (fd(j)==i))
sb=sum(b[j] for j in xrange(n) if (fd(j)==i))
if sa!=sb:
print "NO"
exit()
dfs(i,-1)
print len(ans)
for c in ans:
print c[0]+1,c[1]+1,c[2]
| 1371223800 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["YES\nCAN 2\nCAN 1\nCAN 1\nCAN 1\nCAN 1\nYES", "YES\nYES\nCAN 81", "YES\nNO"] | d818876d0bb7a22b7aebfca5b77d2cd5 | NoteThe cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6. | Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. | Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). | The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. | standard output | standard input | PyPy 3 | Python | 2,200 | train_011.jsonl | 38c7b8906d8508da8428036aef712d26 | 256 megabytes | ["6 7 1 6\n1 2 2\n1 3 10\n2 3 7\n2 4 8\n3 5 3\n4 5 2\n5 6 1", "3 3 1 3\n1 2 10\n2 3 10\n1 3 100", "2 2 1 2\n1 2 1\n1 2 2"] | PASSED | from heapq import *
import sys
MOD = 1000000181
def addM(a,b):
return (a+b)%MOD
def mulM(a,b):
return (a*b)%MOD
def dijk(adj,n,s):
dist = [10**18]*n
ways = [0]*n
frontier = []
dist[s] = 0
ways[s] = 1
heappush(frontier,(0,s))
while (len(frontier)>0):
x = heappop(frontier)
if x[0]!=dist[x[1]]:
continue
x = x[1]
for (i,l) in adj[x]:
if dist[x]+l<dist[i]:
dist[i] = dist[x]+l
ways[i] = ways[x]
heappush(frontier,(dist[i],i))
elif dist[x]+l==dist[i]:
ways[i] = addM(ways[i],ways[x])
return (dist,ways)
n,m,s,t = map(int,sys.stdin.readline().split())
s-=1
t-=1
adj = [[] for i in range(n)]
jda = [[] for i in range(n)]
edges = []
for i in range(m):
a,b,l = map(int,sys.stdin.readline().split())
a-=1
b-=1
adj[a].append((b,l))
jda[b].append((a,l))
edges.append((a,b,l))
one = dijk(adj,n,s)
two = dijk(jda,n,t)
for i in edges:
if one[0][i[0]]+i[2]+two[0][i[1]]==one[0][t] and mulM(one[1][i[0]],two[1][i[1]])==one[1][t]:
sys.stdout.write("YES\n")
else:
x = one[0][t]-1-one[0][i[0]]-two[0][i[1]]
if x<=0:
sys.stdout.write("NO\n")
else:
sys.stdout.write("CAN "+str(i[2]-x)+"\n") | 1438790400 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["4", "11", "2"] | b86a61e6b759b308656e888641f75776 | NoteLet's list all the pairs of segments that Vasya could choose in the first example: $$$[2, 2]$$$ and $$$[2, 5]$$$; $$$[1, 2]$$$ and $$$[2, 4]$$$; $$$[5, 5]$$$ and $$$[2, 5]$$$; $$$[5, 6]$$$ and $$$[3, 5]$$$; | Vasya had three strings $$$a$$$, $$$b$$$ and $$$s$$$, which consist of lowercase English letters. The lengths of strings $$$a$$$ and $$$b$$$ are equal to $$$n$$$, the length of the string $$$s$$$ is equal to $$$m$$$. Vasya decided to choose a substring of the string $$$a$$$, then choose a substring of the string $$$b$$$ and concatenate them. Formally, he chooses a segment $$$[l_1, r_1]$$$ ($$$1 \leq l_1 \leq r_1 \leq n$$$) and a segment $$$[l_2, r_2]$$$ ($$$1 \leq l_2 \leq r_2 \leq n$$$), and after concatenation he obtains a string $$$a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \ldots a_{r_1} b_{l_2} b_{l_2 + 1} \ldots b_{r_2}$$$.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments $$$[l_1, r_1]$$$ and $$$[l_2, r_2]$$$ have non-empty intersection, i.e. there exists at least one integer $$$x$$$, such that $$$l_1 \leq x \leq r_1$$$ and $$$l_2 \leq x \leq r_2$$$; the string $$$a[l_1, r_1] + b[l_2, r_2]$$$ is equal to the string $$$s$$$. | Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. | The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 500\,000, 2 \leq m \leq 2 \cdot n$$$) — the length of strings $$$a$$$ and $$$b$$$ and the length of the string $$$s$$$. The next three lines contain strings $$$a$$$, $$$b$$$ and $$$s$$$, respectively. The length of the strings $$$a$$$ and $$$b$$$ is $$$n$$$, while the length of the string $$$s$$$ is $$$m$$$. All strings consist of lowercase English letters. | standard output | standard input | PyPy 3 | Python | 2,700 | train_008.jsonl | c3f005ad55302e52986dc15536091562 | 512 megabytes | ["6 5\naabbaa\nbaaaab\naaaaa", "5 4\nazaza\nzazaz\nazaz", "9 12\nabcabcabc\nxyzxyzxyz\nabcabcayzxyz"] | PASSED | import sys, logging
logging.basicConfig(level=logging.INFO)
logging.disable(logging.INFO)
def build(S, n):
Z = [0 for i in range(3 * n + 3)]
#logging.info(S)
n = len(S)
L = 0
R = 0
Z[0] = n
for i in range(1, n):
if(i > R):
L = R = i
while(R < n and S[R] == S[R - L]):
R += 1
Z[i] = R - L
R -= 1
else:
k = i - L
if(Z[k] < R - i + 1):
Z[i] = Z[k]
else:
L = i
while(R < n and S[R] == S[R - L]):
R += 1
Z[i] = R - L
R -= 1
return Z
def update1(n, x, val):
while(x <= n + 1):
bit1[x] += val
x += x & -x
def get1(n, x):
ans = 0
while(x > 0):
ans += bit1[x]
x -= x & -x
return ans
def update2(n, x, val):
while(x <= n + 1):
bit2[x] += val
x += x & -x
def get2(n, x):
ans = 0
while(x > 0):
ans += bit2[x]
x -= x & -x
return ans
def process(n, m, fa, fb):
r2 = int(1)
ans = 0
for l1 in range(1, n + 1):
while(r2 <= min(n, l1 + m - 2)):
update1(n, m - fb[r2] + 1, 1)
update2(n, m - fb[r2] + 1, fb[r2] - m + 1)
r2 += 1
ans += get1(n, fa[l1] + 1) * fa[l1] + get2(n, fa[l1] + 1)
update1(n, m - fb[l1] + 1, -1)
update2(n, m - fb[l1] + 1, m - 1 - fb[l1])
print(ans)
def main():
n, m = map(int, sys.stdin.readline().split())
a = sys.stdin.readline()
b = sys.stdin.readline()
s = sys.stdin.readline()
a = a[:(len(a) - 1)]
b = b[:(len(b) - 1)]
s = s[:(len(s) - 1)]
fa = build(s + a, n)
kb = build(s[::-1] + b[::-1], n)
fb = [0 for k in range(n + 2)]
for i in range(m, m + n):
fa[i - m + 1] = fa[i]
if(fa[i - m + 1] >= m):
fa[i - m + 1] = m - 1
fb[m + n - i] = kb[i]
if(fb[m + n - i] >= m):
fb[m + n - i] = m - 1
logging.info(fa[1:(n + 1)])
logging.info(fb[1:(n + 1)])
process(n, m, fa, fb)
bit1 = [0 for i in range(500004)]
bit2 = [0 for i in range(500004)]
if __name__ == "__main__":
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
main() | 1582448700 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["1 3 4 3 3", "1 4 1 1 2 4 2"] | c412a489a0bd2327a46f1e47a78fd03f | NoteIn the first sample case, the following paths are palindromic:2 - 3 - 42 - 3 - 54 - 3 - 5Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:1 - 2 - 31 - 2 - 3 - 41 - 2 - 3 - 5 | You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through. | Print n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree. | The first line contains an integer n (2 ≤ n ≤ 2·105) — the number of vertices in the tree. The next n - 1 lines each contain two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree. The next line contains a string consisting of n lowercase characters from a to t where the i-th (1 ≤ i ≤ n) character is the label of vertex i in the tree. | standard output | standard input | PyPy 2 | Python | 2,400 | train_046.jsonl | ab65d0f5f4b80c415ac227c484f30272 | 256 megabytes | ["5\n1 2\n2 3\n3 4\n3 5\nabcbb", "7\n6 2\n4 3\n3 7\n5 2\n7 2\n1 4\nafefdfs"] | PASSED | import sys
range = xrange
input = raw_input
def centroid_decomp(coupl):
n = len(coupl)
bfs = [n - 1]
for node in bfs:
bfs += coupl[node]
for nei in coupl[node]:
coupl[nei].remove(node)
size = [0] * n
for node in reversed(bfs):
size[node] = 1 + sum(size[child] for child in coupl[node])
def centroid_reroot(root):
N = size[root]
while True:
for child in coupl[root]:
if size[child] > N // 2:
size[root] = N - size[child]
coupl[root].remove(child)
coupl[child].append(root)
root = child
break
else:
return root
bfs = [n - 1]
for node in bfs:
centroid = centroid_reroot(node)
bfs += coupl[centroid]
yield centroid
inp = sys.stdin.read().split(); ii = 0
n = int(inp[ii]); ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = int(inp[ii]) - 1; ii += 1
v = int(inp[ii]) - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
A = [1 << ord(c) - ord('a') for c in inp[ii]]; ii += 1
palistates = [0] + [1 << i for i in range(20)]
ans = [0.0] * n
dp = [0.0] * n
val = [0] * n
counter = [0] * (1 << 20)
for centroid in centroid_decomp(coupl):
bfss = []
for root in coupl[centroid]:
bfs = [root]
for node in bfs:
bfs += coupl[node]
bfss.append(bfs)
for node in bfs:
val[node] ^= A[node]
for child in coupl[node]:
val[child] = val[node]
entire_bfs = [centroid]
for bfs in bfss:
entire_bfs += bfs
for node in entire_bfs:
val[node] ^= A[centroid]
counter[val[node]] += 1
for bfs in bfss:
for node in bfs:
counter[val[node]] -= 1
for node in bfs:
v = val[node] ^ A[centroid]
for p in palistates:
dp[node] += counter[v ^ p]
for node in bfs:
counter[val[node]] += 1
for node in reversed(entire_bfs):
dp[node] += sum(dp[child] for child in coupl[node])
dp[centroid] += 1
for p in palistates:
dp[centroid] += counter[p]
dp[centroid] //= 2
for node in entire_bfs:
ans[node] += dp[node]
counter[val[node]] = val[node] = 0
dp[node] = 0.0
print ' '.join(str(int(x)) for x in ans)
| 1516462500 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["1 1 1", "3 3", "6 12"] | ea8f191447a4089e211a17bccced97dc | NoteIn the second example, there are $$$3$$$ sequences he can get after $$$1$$$ swap, because there are $$$3$$$ pairs of cubes he can swap. Also, there are $$$3$$$ sequences he can get after $$$2$$$ swaps: $$$[1,2,3]$$$, $$$[3,1,2]$$$, $$$[2,3,1]$$$. | This time around, Baby Ehab will play with permutations. He has $$$n$$$ cubes arranged in a row, with numbers from $$$1$$$ to $$$n$$$ written on them. He'll make exactly $$$j$$$ operations. In each operation, he'll pick up $$$2$$$ cubes and switch their positions.He's wondering: how many different sequences of cubes can I have at the end? Since Baby Ehab is a turbulent person, he doesn't know how many operations he'll make, so he wants the answer for every possible $$$j$$$ between $$$1$$$ and $$$k$$$. | Print $$$k$$$ space-separated integers. The $$$i$$$-th of them is the number of possible sequences you can end up with if you do exactly $$$i$$$ operations. Since this number can be very large, print the remainder when it's divided by $$$10^9+7$$$. | The only line contains $$$2$$$ integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 200$$$) — the number of cubes Baby Ehab has, and the parameter $$$k$$$ from the statement. | standard output | standard input | PyPy 3-64 | Python | 2,500 | train_105.jsonl | 78434fdd87735cbc678c84b3033d3040 | 256 megabytes | ["2 3", "3 2", "4 2"] | 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, k = list(map(int, input().split()))
# a = list(map(int, input().split()))
# i = 0
# while i < n - 1 and k > 0:
# if a[i] > 0:
# a[i] -= 1
# a[-1] += 1
# k -= 1
# else:
# i += 1
# print(*a)
# for _ in range(int(input())):
# def solve():
# n = int(input())
# a = list(map(int, input().split()))
# tot = 0
# for i in range(n):
# tot ^= a[i]
# if tot == 0:
# print('YES')
# return
# res = 0
# for i in range(n):
# res ^= a[i]
# if res == tot:
# l = i
# break
# res = 0
# for i in range(n)[::-1]:
# res ^= a[i]
# if res == tot:
# r = i
# break
# if l < r:
# print('YES')
# else:
# print('NO')
# solve()
# def solve():
# n = int(input())
# a = list(map(int, input().split()))
# if sum(a) % 2:
# print(0)
# return
# b = sorted(a)
# s = set([0])
# for i in range(n):
# news = set()
# for j in s:
# news.add(j)
# news.add(j + a[i])
# s = news
# if sum(a) // 2 not in s:
# print(0)
# return
# for _ in range(40):
# for i in range(n):
# if a[i] % 2 == 1:
# print(1)
# print(i + 1)
# return
# a[i] //= 2
# solve()
mod = 10 ** 9 + 7
N = 410
c = [[0] * N for _ in range(N)]
for i in range(N):
c[i][0] = c[i][i] = 1
for i in range(1, N):
for j in range(1, i):
c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod
n, k = list(map(int, input().split()))
f = [[0] * (k + 1) for _ in range(2 * k + 1)]
for i in range(1, 2 * k + 1):
f[i][0] = 1
for j in range(1, k + 1):
f[i][j] = (f[i - 1][j] + (i - 1) * f[i - 1][j - 1]) % mod
g = [[0] * (k + 1) for _ in range(2 * k + 1)]
for j in range(k + 1):
for i in range(min(n, 2 * j) + 1):
for l in range(i + 1):
if l % 2 == 0:
g[i][j] += c[i][l] * f[i - l][j]
else:
g[i][j] -= c[i][l] * f[i - l][j]
g[i][j] %= mod
ans = [0] * (k + 1)
ans[0] = 1
for i in range(1, k + 1):
w = 1
for j in range(min(n, 2 * i) + 1):
ans[i] += w * g[j][i] % mod
ans[i] %= mod
w *= (n - j) * pow(j + 1, mod - 2, mod) % mod
w %= mod
for i in range(2, k + 1):
ans[i] = (ans[i] + ans[i - 2]) % mod
print(*ans[1:])
| 1619012100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1 4", "3 3", "1 6"] | e65b974a85067500f20b316275dc5821 | NoteIn the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. In the second example, possible assignments for each minimum and maximum are described in picture below. The $$$f$$$ value of valid assignment of this tree is always $$$3$$$. In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. | You have unweighted tree of $$$n$$$ vertices. You have to assign a positive weight to each edge so that the following condition would hold: For every two different leaves $$$v_{1}$$$ and $$$v_{2}$$$ of this tree, bitwise XOR of weights of all edges on the simple path between $$$v_{1}$$$ and $$$v_{2}$$$ has to be equal to $$$0$$$. Note that you can put very large positive integers (like $$$10^{(10^{10})}$$$).It's guaranteed that such assignment always exists under given constraints. Now let's define $$$f$$$ as the number of distinct weights in assignment. In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $$$0$$$. $$$f$$$ value is $$$2$$$ here, because there are $$$2$$$ distinct edge weights($$$4$$$ and $$$5$$$). In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $$$1$$$ and vertex $$$6$$$ ($$$3, 4, 5, 4$$$) is not $$$0$$$. What are the minimum and the maximum possible values of $$$f$$$ for the given tree? Find and print both. | Print two integers — the minimum and maximum possible value of $$$f$$$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. | The first line contains integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the number of vertices in given tree. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$) — it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. It is guaranteed that given graph forms tree of $$$n$$$ vertices. | standard output | standard input | PyPy 3 | Python | 1,800 | train_011.jsonl | a41ce4f441f3b40ccf75e76627d50ab2 | 256 megabytes | ["6\n1 3\n2 3\n3 4\n4 5\n5 6", "6\n1 3\n2 3\n3 4\n4 5\n4 6", "7\n1 2\n2 7\n3 4\n4 7\n5 6\n6 7"] | PASSED | # by the authority of GOD author: manhar singh sachdev #
import os, sys
from io import BytesIO, IOBase
from collections import defaultdict
def main():
n = int(input())
path = defaultdict(set)
parent = [0]*(n+1)
for _ in range(n-1):
a,b = map(int,input().split())
path[a].add(b)
path[b].add(a)
root = -1
z = [0]*(n+1)
for i in path:
if len(path[i])>1:
root = i
else:
x = path[i].pop()
parent[x] += 1
path[i].add(x)
z[i] = 1
st = [root]
ans = 1
while len(st):
if not len(path[st[-1]]):
x = st.pop()
if len(st):
z[st[-1]] |= (3^z[x])
if z[st[-1]] == 3:
ans = 3
break
continue
i = path[st[-1]].pop()
path[i].remove(st[-1])
st.append(i)
ans1 = n-1
for i in parent:
ans1 -= max(0,(i-1))
print(ans,ans1)
# 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")
if __name__ == '__main__':
main() | 1586700300 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["3\n1 2 3\n1 2 3", "1\n1 1 1\n2", "-1"] | 4b49f1b3fca4acb2f5dce25169436cc8 | null | Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all , and h(g(x)) = f(x) for all , or determine that finding these is impossible. | If there is no answer, print one integer -1. Otherwise, on the first line print the number m (1 ≤ m ≤ 106). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m). If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions. | The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n). | standard output | standard input | Python 3 | Python | 1,700 | train_018.jsonl | bc887724d80a34931594f42f6d1c8931 | 512 megabytes | ["3\n1 2 3", "3\n2 2 2", "2\n2 1"] | PASSED | n = int(input())
f = [None] + list(map(int, input().split(' ')))
invalid = False
g = [None] + [0] * n
h = [None]
x_is_f_which = [None] + [0] * n
m = 0
vis = [None] + [False] * n
for i in range(1, n + 1):
x = f[i]
if f[x] != x:
invalid = True
break
if not vis[x]:
vis[x] = True
m = m + 1
h.append(x)
x_is_f_which[x] = m
if invalid:
print('-1')
else:
for i in range(1, n + 1):
g[i] = x_is_f_which[f[i]]
print(m)
def print_list(l):
print(' '.join(list(map(str, l[1:]))))
print_list(g)
print_list(h)
| 1487059500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["0 1\n0 0\n0 1 3 2\n0 0 1 1\n5 3 0 7 2 6 1 4\n-1"] | 4c9c50f9ebe06a3e86c20aee2a0ee797 | NoteThe colouring and the permuted hypercube for the first test case is shown below: The colouring and the permuted hypercube for the second test case is shown below: The permuted hypercube for the third test case is given in the problem statement. However, it can be shown that there exists no way to colour that cube satifying all the conditions. Note that some other permutations like $$$[0, 5, 7, 3, 1, 2, 4, 6]$$$ and $$$[0, 1, 5, 2, 7, 4, 3, 6]$$$ will also give the same permuted hypercube. | Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune and repaint your BMW M3 GTR.The car can be imagined as a permuted $$$n$$$-dimensional hypercube. A simple $$$n$$$-dimensional hypercube is an undirected unweighted graph built recursively as follows: Take two simple $$$(n-1)$$$-dimensional hypercubes one having vertices numbered from $$$0$$$ to $$$2^{n-1}-1$$$ and the other having vertices numbered from $$$2^{n-1}$$$ to $$$2^{n}-1$$$. A simple $$$0$$$-dimensional Hypercube is just a single vertex. Add an edge between the vertices $$$i$$$ and $$$i+2^{n-1}$$$ for each $$$0\leq i < 2^{n-1}$$$. A permuted $$$n$$$-dimensional hypercube is formed by permuting the vertex numbers of a simple $$$n$$$-dimensional hypercube in any arbitrary manner.Examples of a simple and permuted $$$3$$$-dimensional hypercubes are given below: Note that a permuted $$$n$$$-dimensional hypercube has the following properties: There are exactly $$$2^n$$$ vertices. There are exactly $$$n\cdot 2^{n-1}$$$ edges. Each vertex is connected to exactly $$$n$$$ other vertices. There are no self-loops or duplicate edges. Let's denote the permutation used to generate the permuted $$$n$$$-dimensional hypercube, representing your car, from a simple $$$n$$$-dimensional hypercube by $$$P$$$. Before messing up the functionalities of the car, you want to find this permutation so that you can restore the car if anything goes wrong. But the job isn't done yet.You have $$$n$$$ different colours numbered from $$$0$$$ to $$$n-1$$$. You want to colour the vertices of this permuted $$$n$$$-dimensional hypercube in such a way that for each and every vertex $$$u$$$ satisfying $$$0\leq u < 2^n$$$ and for each and every colour $$$c$$$ satisfying $$$0\leq c < n$$$, there is at least one vertex $$$v$$$ adjacent to $$$u$$$ having a colour $$$c$$$. In other words, from each and every vertex, it must be possible to reach a vertex of any colour by just moving to an adjacent vertex. Given the permuted $$$n$$$-dimensional hypercube, find any valid permutation $$$P$$$ and colouring. | For each test case, print two lines. In the first line, output any permutation $$$P$$$ of length $$$2^n$$$ that can be used to transform a simple $$$n$$$-dimensional hypercube to the permuted $$$n$$$-dimensional hypercube given in the input. Two permuted hypercubes are considered the same if they have the same set of edges. If there are multiple answers, output any of them. In the second line, print the colouring. If there is no way to colour the vertices satisfying the conditions, output $$$-1$$$. Otherwise, output a single line containing $$$2^n$$$ space separated integers. The $$$i$$$-th integer must be the colour of the vertex numbered $$$(i-1)$$$ in the permuted $$$n$$$-dimensional hypercube. If there are multiple answers, output any of them. | The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 4096$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n\leq 16$$$). Each of the next $$$n\cdot 2^{n-1}$$$ lines contain two integers $$$u$$$ and $$$v$$$ ($$$0\leq u, v < 2^n$$$) denoting that there is an edge between the vertices numbered $$$u$$$ and $$$v$$$. It is guaranteed that the graph described in the input is a permuted $$$n$$$-dimensional hypercube. Additionally, it is guaranteed that the sum of $$$2^n$$$ over all test cases does not exceed $$$2^{16}=65\,536$$$. | standard output | standard input | PyPy 3 | Python | 2,700 | train_091.jsonl | ae0d50e1348523fabc089358e6773d31 | 256 megabytes | ["3\n1\n0 1\n2\n0 1\n1 2\n2 3\n3 0\n3\n0 1\n0 5\n0 7\n1 2\n1 4\n2 5\n2 6\n3 5\n3 6\n3 7\n4 6\n4 7"] | PASSED | from collections import deque
from sys import stdin
import sys
tt = int(stdin.readline())
for loop in range(tt):
n = int(stdin.readline())
lis = [ [] for i in range(2**n)]
for i in range(n*(2**(n-1))):
u,v = map(int,stdin.readline().split())
lis[u].append(v)
lis[v].append(u)
rp = [0] * (2**n)
d = [float("inf")] * (2**n)
d[0] = 0
q = deque()
for i in range(n):
nexv = lis[0][i]
rp[nexv] = 2**i
d[nexv] = 1
q.append(nexv)
while q:
v = q.popleft()
for nexv in lis[v]:
if d[nexv] == float("inf"):
d[nexv] = d[v] + 1
q.append(nexv)
if d[nexv] > d[v]:
rp[nexv] |= rp[v]
p = [None] * (2**n)
for i in range(2**n):
p[rp[i]] = i
print (*p)
if (2**n) % n == 0:
c = [None] * (2**n)
for i in range(2**n):
now = 0
for j in range(n):
if 2**j & i > 0:
now ^= j
c[p[i]] = now
print (*c)
else:
print (-1) | 1625668500 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3 1 2", "1 3 2", "-1"] | d53d6cd0014576ad93c01c1a685b9eb1 | null | Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. | If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. | The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. | standard output | standard input | Python 2 | Python | 2,200 | train_033.jsonl | eccb0784cafa69f64ab6fe1d5d45a826 | 256 megabytes | ["3 3\n1 -1 -1\n1 2 1\n2 -1 1", "2 3\n1 2 2\n2 5 4", "2 3\n1 2 3\n3 2 1"] | PASSED | n, m = map(int, raw_input().split())
b = [map(int, raw_input().split()) for _ in range(n)]
c = [n - x.count(-1) for x in zip(*b)]
d = []
for r in b:
t = {}
for i, x in enumerate(r):
if x != -1:
if x not in t:
t[x] = set()
t[x].add(i)
d.append([x for i, x in sorted(t.items())][ : : -1])
p = [i for i, x in enumerate(c) if not x]
for v in d:
if v:
for x in v[-1]:
c[x] -= 1
if not c[x]:
p.append(x)
r = []
while p:
x = p.pop()
r.append(x + 1)
for i, v in enumerate(d):
if v:
v[-1].discard(x)
if not v[-1]:
d[i].pop()
if d[i]:
for y in d[i][-1]:
c[y] -= 1
if not c[y]:
p.append(y)
print [-1, ' '.join(map(str, r))][len(r) == m]
| 1361374200 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["? 1 2\n? 1 3\n? 2 3\n! 1 0 2"] | 66e86d612d676068689ae714b453ef32 | NoteIn the first sample, the permutation is $$$[1,0,2]$$$. You start by asking about $$$p_1|p_2$$$ and Ehab replies with $$$1$$$. You then ask about $$$p_1|p_3$$$ and Ehab replies with $$$3$$$. Finally, you ask about $$$p_2|p_3$$$ and Ehab replies with $$$2$$$. You then guess the permutation. | This is an interactive problem!Ehab has a hidden permutation $$$p$$$ of length $$$n$$$ consisting of the elements from $$$0$$$ to $$$n-1$$$. You, for some reason, want to figure out the permutation. To do that, you can give Ehab $$$2$$$ different indices $$$i$$$ and $$$j$$$, and he'll reply with $$$(p_i|p_j)$$$ where $$$|$$$ is the bitwise-or operation.Ehab has just enough free time to answer $$$4269$$$ questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will not change it depending on your queries. Can you guess the permutation? | null | The only line contains the integer $$$n$$$ $$$(3 \le n \le 2048)$$$ — the length of the permutation. | standard output | standard input | Python 3 | Python | 2,700 | train_051.jsonl | 407c9f93c2fa8ff4df50edca364e596e | 256 megabytes | ["3\n1\n3\n2"] | PASSED | from random import sample
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
memo={}
def ask(i,j):
if i>j:i,j=j,i
if (i,j) in memo:return memo[i,j]
print("?",i+1,j+1,flush=True)
res=II()
memo[i,j]=res
return res
n=II()
a,b=0,1
for c in sample(range(2,n),n-2):
ab=ask(a,b)
bc=ask(b,c)
if ab==bc:b=c
if ab>bc:a=c
ab=ask(a,b)
for (i,j),v in memo.items():
if ab&v!=ab:
if i in [a,b]:i=j
if i in [a,b]:continue
ac = ask(a, i)
bc = ask(b, i)
if ac < bc: z = a
else: z = b
break
else:
for c in sample(range(n),n):
if a==c or b==c:continue
ac=ask(a,c)
bc=ask(b,c)
if ac==bc:continue
if ac<bc:z=a
else:z=b
break
ans=[]
for i in range(n):
if i==z:ans.append(0)
else:ans.append(ask(z,i))
print("!",*ans,flush=True)
| 1592060700 | [
"probabilities"
] | [
0,
0,
0,
0,
0,
1,
0,
0
] |
|
3 seconds | ["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"] | b67870dcffa7bad682ef980dacd1f3db | NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$. | Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w < n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist. | For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w < n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,900 | train_110.jsonl | e52d58da3596df5f47871b828d58d894 | 256 megabytes | ["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"] | PASSED | import bisect
import collections
import collections.abc
import itertools
import math
import re
import sys
import functools
import copy
import math
import heapq
import sys
import io
from collections import Counter, deque
from collections import defaultdict as ddict
def create_matrix(rows, cols=None, val=None):
if cols is None:
cols = rows
row = [val] * cols
mat = []
for _ in range(rows):
mat.append(copy.deepcopy(row))
return mat
def bsearch(a, x):
'''
Locate the leftmost value exactly equal to x.
https://docs.python.org/3/library/bisect.html#module-bisect
'''
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def zdict(x=0):
return collections.defaultdict(lambda: x)
def strjoin(xs, glue=' ', conv=str):
return glue.join(map(conv, xs))
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letters = {ch for ch in alphabet}
def to_nums(line):
return [int(x) for x in line.split(" ")]
def read_nums(f):
line = f.readline().strip()
return [int(x) for x in line.split(" ")]
def print_mat(mat, glue=" "):
for row in mat:
print(strjoin(row, glue=glue))
def read_num(f):
line = f.readline().strip()
return int(line)
def read_str(f):
line = f.readline().strip()
return line
def read_pair(f, func=int):
line = f.readline().strip().split(" ")
return (func(line[0]), func(line[1]))
def read_triplet(f, func=int):
line = f.readline().strip().split(" ")
return (func(line[0]), func(line[1]), func(line[2]))
import math
import sys
@functools.lru_cache()
def get_combos(k):
combos = []
for i in range(10):
for j in range(10):
if (i + j) % 9 == k:
combos.append((i, j))
return combos
def solve(s, w, q):
n = len(s)
#modulo = math.pow(10, w)
sums = [0 for _ in range(n)]
mods = {x:[] for x in range(9)}
for i in range(n):
digit = int(s[i])
if i == 0:
sums[i] = digit
else:
sums[i] = (sums[i-1]+digit)%9
for i in range(0, n - w + 1):
if i == 0:
v = sums[i+w-1] % 9
else:
#print(f"{i+w} vs {n}")
v = (sums[i+w-1] - sums[i-1]) % 9
#if len(mods[v])<2:
mods[v].append(i+1)
for _ in range(q):
l, r, k = read_triplet(f)
if l == 1:
mult = sums[r-1] % 9
else:
mult = (sums[r-1] - sums[l-2])%9
l1, l2 = n+1, n+1
for x in range(9):
if mods[x]:
for y in range(9):
if not mods[y]:
continue
cond = ((mult * x) + y) % 9 == k
if not cond:
continue
if x != y:
a, b = mods[x][0], mods[y][0]
elif len(mods[x])>1:
a, b = mods[x][0], mods[x][1]
else:
continue
if a < l1 or (a==l1 and b<l2):
l1, l2 = a, b
if l1 == n+1:
l1, l2 = -1, -1
#print(f"All cands for answer ({l1,l2})= {all_cands}")
print(str(l1) + ' ' + str(l2))
def main():
with f:
t = read_num(f)
for tt in range(t):
#if tt>=2:
# break
s = read_str(f)
w, q = read_pair(f)
solve(s, w, q)
data = """5
1003004
4 1
1 2 1
179572007
4 2
2 7 3
2 7 4
111
2 1
2 2 6
0000
1 2
1 4 0
1 4 1
484
1 5
2 2 0
2 3 7
1 2 5
3 3 8
2 2 6
"""
f = None
#f = io.StringIO(data)
if f is None:
f = sys.stdin
if len(sys.argv) > 1:
f = open(sys.argv[1], 'r')
testcase = None
if __name__ == '__main__':
#sys.setrecursionlimit(300000)
main()
"""
2 4
1 5
1 2
-1 -1
1 2
-1 -1
1 3
1 3
-1 -1
-1 -1
-1 -1
"""
| 1662993300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["2\n4 2", "2\n7 11"] | d50bb59298e109b4ac5f808d24fef5a1 | NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part. | Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement. | In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them. | The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string. | standard output | standard input | Python 3 | Python | 1,700 | train_003.jsonl | 38c46d8ac25f20c7053fb79fe3b1724c | 256 megabytes | ["5 1 2 1\n00100", "13 3 2 3\n1000000010001"] | PASSED | n,a,b,k=map(int,input().split())
A=input()
B=A.split('1')
C=[]
l=1
for i in B:
if len(i)>=b:
for j in range(b-1,len(i),b):
C.append(j+l)
l+=len(i)+1
C=C[:len(C)-a+1]
print(len(C))
print(' '.join(list(map(str,C))))
# Made By Mostafa_Khaled | 1479632700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["0", "1", "-1"] | 3c5e1f11e6af3821ed8c28f15e429def | null | In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. | Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. | The first line contains two integers n, m (1 ≤ n ≤ 3000, ) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). | standard output | standard input | PyPy 2 | Python | 2,100 | train_042.jsonl | 6c3ca46b863c2fac3200e211965bd854 | 256 megabytes | ["5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 2", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n2 4 2", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 1"] | PASSED | from collections import deque
import sys
maxn = 3003
d = [[0] * maxn for i in range(0, maxn)]
adj = [[] for i in range(0, maxn)]
mark = [0] * maxn
def bfs(s) :
for i in range(0, maxn) :
mark[i] = False
q = deque()
q.append(s)
d[s][s] = 0
mark[s] = True
while len(q) > 0 :
v = q[0]
q.popleft()
for u in adj[v] :
if not mark[u] :
mark[u] = True
q.append(u)
d[s][u] = d[s][v] + 1
def main() :
n, m = map(int, raw_input().split())
for i in range(0, m) :
u, v = map(int, raw_input().split())
u -= 1; v -= 1
adj[u].append(v)
adj[v].append(u)
for i in range(0, n) :
bfs(i)
s1, t1, l1 = map(int, raw_input().split())
s2, t2, l2 = map(int, raw_input().split())
s1 -= 1; s2 -= 1; t1 -= 1; t2 -= 1
if d[s1][t1] > l1 or d[s2][t2] > l2 :
print -1
sys.exit()
ans = d[s1][t1] + d[s2][t2]
for i in range(0, n) :
for j in range(0, n) :
if d[i][s1] + d[i][j] + d[j][t1] <= l1 and d[i][s2] + d[i][j] + d[j][t2] <= l2 :
ans = min(ans, d[i][j] + d[i][s1] + d[i][s2] + d[j][t1] + d[j][t2])
if d[i][s1] + d[i][j] + d[j][t1] <= l1 and d[j][s2] + d[i][j] + d[i][t2] <= l2 :
ans = min(ans, d[i][j] + d[j][t1] + d[j][s2] + d[i][s1] + d[i][t2])
print m - ans
main() | 1431016200 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["FastestFinger\nAshishgup\nAshishgup\nFastestFinger\nAshishgup\nFastestFinger\nAshishgup"] | b533572dd6d5fe7350589c7f4d5e1c8c | NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$. | Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves: Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$. Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally. | For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes). | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer — $$$n$$$ ($$$1 \leq n \leq 10^9$$$). | standard output | standard input | PyPy 3 | Python | 1,400 | train_008.jsonl | fd30ce82caffe8b0dfd84efacf3ca154 | 256 megabytes | ["7\n1\n2\n3\n4\n5\n6\n12"] | PASSED | for t in range(int(input())):
n = int(input())
N = n
if n == 1:
winner = 2
elif n == 2 or n % 2 != 0:
winner = 1
else:
numTwo = 0
while n % 2 == 0:
n //= 2
numTwo += 1
numOdd = 0
for i in range(3, int(N ** 0.5 + 2), 2):
while n > 0 and n % i == 0:
n //= i
numOdd += 1
# print(n)
if n > 2:
numOdd += 1
if numOdd == 0 and numTwo > 1:
winner = 2
elif numOdd == 1 and numTwo == 1:
winner = 2
else:
winner = 1
if winner == 1:
print("Ashishgup")
else:
print("FastestFinger") | 1592663700 | [
"number theory",
"math",
"games"
] | [
1,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds | ["5 3 5", "5 3 1 2 1", "-1"] | 790739d10b9c985f2fe47ec79ebfc993 | null | There are $$$n$$$ railway stations in Berland. They are connected to each other by $$$n-1$$$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the $$$n-1$$$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $$$1$$$ to $$$10^6$$$ inclusive.You asked $$$m$$$ passengers some questions: the $$$j$$$-th one told you three values: his departure station $$$a_j$$$; his arrival station $$$b_j$$$; minimum scenery beauty along the path from $$$a_j$$$ to $$$b_j$$$ (the train is moving along the shortest path from $$$a_j$$$ to $$$b_j$$$). You are planning to update the map and set some value $$$f_i$$$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values $$$f_1, f_2, \dots, f_{n-1}$$$, which the passengers' answer is consistent with or report that it doesn't exist. | If there is no answer then print a single integer -1. Otherwise, print $$$n-1$$$ integers $$$f_1, f_2, \dots, f_{n-1}$$$ ($$$1 \le f_i \le 10^6$$$), where $$$f_i$$$ is some valid scenery beauty along the $$$i$$$-th railway section. If there are multiple answers, you can print any of them. | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of railway stations in Berland. The next $$$n-1$$$ lines contain descriptions of the railway sections: the $$$i$$$-th section description is two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are the indices of the stations which are connected by the $$$i$$$-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 5000$$$) — the number of passengers which were asked questions. Then $$$m$$$ lines follow, the $$$j$$$-th line contains three integers $$$a_j$$$, $$$b_j$$$ and $$$g_j$$$ ($$$1 \le a_j, b_j \le n$$$; $$$a_j \ne b_j$$$; $$$1 \le g_j \le 10^6$$$) — the departure station, the arrival station and the minimum scenery beauty along his path. | standard output | standard input | Python 2 | Python | 2,100 | train_023.jsonl | 13a28c65adcf2faca36b2d6064329ba7 | 256 megabytes | ["4\n1 2\n3 2\n3 4\n2\n1 2 5\n1 3 3", "6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 3\n3 4 1\n6 5 2\n1 2 5", "6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 1\n3 4 3\n6 5 3\n1 2 4"] | PASSED | import sys
range = xrange
input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
U = []
for eind in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(2*eind)
coupl[v].append(2*eind + 1)
U.append(u)
U.append(v)
root = 0
bfs = [root]
P = [-1]*n
for node in bfs:
for eind in coupl[node]:
nei = U[eind ^ 1]
P[nei] = eind ^ 1
coupl[nei].remove(eind ^ 1)
bfs.append(nei)
order = [0]*n
for i in range(n):
order[bfs[i]] = i
class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
self.true = list(range(n))
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def merge(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
if order[self.true[b]] < order[self.true[a]]:
self.true[a] = self.true[b]
dsu = DisjointSetUnion(n)
m = inp[ii]; ii += 1
paths = []
for _ in range(m):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
w = inp[ii]; ii += 1
paths.append((w,u,v))
F = [1]*(n - 1)
paths.sort()
while paths:
w = paths[-1][0]
tmp = []
while paths and paths[-1][0] == w:
w,u,v = paths.pop()
u = dsu.true[dsu.find(u)]
v = dsu.true[dsu.find(v)]
if u == v:
print -1
sys.exit()
tmp.append((u,v))
for u,v in tmp:
u = dsu.true[dsu.find(u)]
v = dsu.true[dsu.find(v)]
while u != v:
if order[u] < order[v]:
eind = P[v]
F[eind >> 1] = w
dsu.merge(v, U[eind ^ 1])
v = dsu.true[dsu.find(v)]
else:
eind = P[u]
F[eind >> 1] = w
dsu.merge(u, U[eind ^ 1])
u = dsu.true[dsu.find(u)]
print ' '.join(str(f) for f in F)
| 1580826900 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second | ["20", "15", "35"] | 281b95c3686c94ae1c1e4e2a18b7fcc4 | NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 = - 5 points. This is 35 in total. | There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes. | Output one integer — the answer to the problem. | The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T). | standard output | standard input | PyPy 2 | Python | 1,300 | train_051.jsonl | e2207ce31b44d148d52266f5241ec8eb | 256 megabytes | ["4 5 5 3 5\n1 5 5 4", "5 3 1 1 3\n2 2 2 1 1", "5 5 3 4 5\n1 2 3 4 5"] | PASSED | n, a, b, c, t = map(int, raw_input().split(" "))
ts = map(int, raw_input().split(" "))
total = a*n
if b <= c:
for i in xrange(n):
total += (t-ts[i])*(c-b)
print total
| 1523973900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["0 2 3 1 1", "1 0 1", "0"] | 3c63e2e682d3c8051c3cecc3fa9c4e8c | null | Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save. | Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day. | The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109). | standard output | standard input | PyPy 3 | Python | 1,500 | train_006.jsonl | eab5379db215cc0e687d3b4fc2d138c1 | 256 megabytes | ["5 1 4\n12 6 11 9 1", "3 1 2\n1 2 3", "1 1 1\n1"] | PASSED | import sys
import string
import math
from collections import defaultdict
from functools import lru_cache
from collections import Counter
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def tmi(s):
return tuple(mi(s))
def mf(f, s):
return map(f, s)
def lmf(f, s):
return list(mf(f, s))
def js(lst):
return " ".join(str(d) for d in lst)
def line():
return sys.stdin.readline().strip()
def linesp():
return line().split()
def iline():
return int(line())
def dist(x, y):
return ((x[0] - y[0])**2 + (x[1] - y[1])**2)**0.5
def bin_search(a, b, n):
form = lambda x: math.floor((x/b)*a)
looking = form(n)
hi = n
lo = 0
while lo <= hi:
if lo == hi:
return lo
elif lo == hi - 1:
if form(lo) == looking:
return lo
else:
return hi
mid = (hi + lo) // 2
if form(mid) < looking:
lo = mid
else:
hi = mid
def main(a, b, arr):
div = b / a
final = []
for n in arr:
looking = math.floor((a * n)/b)
ans = math.ceil(b * (looking / a))
final.append(n - ans)
# final.append(n - bin_search(a, b, n))
print(js(final))
if __name__ == "__main__":
_, a, b = mi(line())
arr = lmi(line())
main(a, b, arr)
| 1396798800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1.0000000000", "0.9628442962", "0.7500000000"] | 81492d3b77bc0674102af17f22bf0664 | NoteIn the first sample the best way of candies' distribution is giving them to first three of the senators. It ensures most of votes.It the second sample player should give all three candies to the fifth senator. | Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.The Dark Assembly consists of n senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to 10%. Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If strictly more than half of the senators take a positive decision, the player's proposal is approved. If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to A / (A + B), where A is the sum of levels of all player's characters and B is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved.Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by 10%. It's worth to mention that loyalty cannot exceed 100%. The player can take no more than k sweets to the courtroom. Candies should be given to the senators before the start of voting.Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way. | Print one real number with precision 10 - 6 — the maximal possible probability that the Dark Assembly approves the player's proposal for the best possible distribution of candies among the senators. | The first line contains three integers n, k and A (1 ≤ n, k ≤ 8, 1 ≤ A ≤ 9999). Then n lines follow. The i-th of them contains two numbers — bi and li — the i-th senator's level and his loyalty. The levels of all senators are integers in range from 1 to 9999 (inclusive). The loyalties of all senators are integers in range from 0 to 100 (inclusive) and all of them are divisible by 10. | standard output | standard input | PyPy 3 | Python | 1,800 | train_029.jsonl | f460dd784f0f5bde2a295d542681cd19 | 256 megabytes | ["5 6 100\n11 80\n14 90\n23 70\n80 30\n153 70", "5 3 100\n11 80\n14 90\n23 70\n80 30\n153 70", "1 3 20\n20 20"] | PASSED | #!/usr/bin/env python3
n, k, A = map(int, input().rstrip().split())
senators = []
mx_bribe = 0
for i in range(n):
lvl, loy = map(int, input().rstrip().split())
senators.append((lvl, loy))
mx_bribe += (100 - loy) // 10
bribe = [0] * n
def calc(votes):
bsum, cnt, p = 0, 0, 1.0
for i, s in enumerate(senators):
if votes & (1 << i):
p *= (s[1] + bribe[i]) / 100
cnt += 1
else:
p *= (100 - s[1] - bribe[i]) / 100
bsum += s[0]
if cnt > (n / 2):
return p
else:
return p * A / (A + bsum)
def dfs(cur, rk):
if cur >= n:
if rk > 0:
return 0.0
sm = 0.0
for i in range(1 << n):
sm += calc(i)
return sm
mx = 0.0
for i in range(rk + 1):
if i * 10 + senators[cur][1] > 100:
break
bribe[cur] = i * 10
tmp = dfs(cur+1, rk-i)
mx = max(tmp, mx)
return mx
print(dfs(0, min(k, mx_bribe)))
| 1313247600 | [
"probabilities"
] | [
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds | ["10\n7\n13\n0\n3"] | 8864c6a04fed970fcbc04e220df9d88d | NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E. | There is an infinite 2-dimensional grid. The robot stands in cell $$$(0, 0)$$$ and wants to reach cell $$$(x, y)$$$. Here is a list of possible commands the robot can execute: move north from cell $$$(i, j)$$$ to $$$(i, j + 1)$$$; move east from cell $$$(i, j)$$$ to $$$(i + 1, j)$$$; move south from cell $$$(i, j)$$$ to $$$(i, j - 1)$$$; move west from cell $$$(i, j)$$$ to $$$(i - 1, j)$$$; stay in cell $$$(i, j)$$$. The robot wants to reach cell $$$(x, y)$$$ in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach $$$(x, y)$$$ from $$$(0, 0)$$$? | For each testcase print a single integer — the minimum number of commands required for the robot to reach $$$(x, y)$$$ from $$$(0, 0)$$$ if no command is allowed to be executed two or more times in a row. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — the destination coordinates of the robot. | standard output | standard input | PyPy 2 | Python | 800 | train_001.jsonl | 93a32ff88ab3bdb4b8d11d4c91dfc886 | 256 megabytes | ["5\n5 5\n3 4\n7 1\n0 0\n2 0"] | PASSED | from __future__ import division, print_function
MOD = 998244353
mod = 10**9 + 7
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
def prepare_factorial():
fact = [1]
for i in range(1, 20):
fact.append((fact[-1] * i) % mod)
ifact = [0] * 105
ifact[104] = pow(fact[104], mod - 2, mod)
for i in range(104, 0, -1):
ifact[i - 1] = (i * ifact[i]) % mod
return fact, ifact
# import threading
# threading.stack_size(1<<27)
import sys
# sys.setrecursionlimit(10000)
from bisect import bisect_left, bisect_right, insort
from math import floor, ceil, sqrt, degrees, atan, pi, log, sin, radians, factorial
from heapq import heappop, heapify, heappush
from collections import Counter, defaultdict, deque
# from itertools import permutations
def modinv(n, p):
return pow(n, p - 2, p)
def ncr(n, r, fact, ifact): # for using this uncomment the lines calculating fact and ifact
t = (fact[n] * (ifact[r] * ifact[n-r]) % mod) % mod
return t
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()
"""*****************************************************************************************"""
def GCD(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return (x * y)//(GCD(x, y))
def get_xor(n):
return [n, 1, n+1, 0][n % 4]
def get_n(P): # this function returns the maximum n for which Summation(n) <= Sum
ans = (-1 + sqrt(1 + 8*P))//2
return ans
""" ********************************************************************************************* """
def main():
T = int(input())
while T:
x, y = get_ints()
if x == y:
print(2*x)
else:
ans = min(x, y)*2 + (max(x, y) - min(x, y))*2 - 1
print(ans)
T -= 1
""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO, self).read()
def readline(self):
while self.newlines == 0:
s = self._fill();
self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
if __name__ == '__main__':
main()
# threading.Thread(target=main).start() | 1605796500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2\n1\n-1", "9\n9\n9\n-1\n-1\n-1"] | 2886d6ef13ba1fbc68fb793f28ba0127 | NoteIn the first example, there are 5 tasks: The first task requires you to add $$$1$$$ into $$$a$$$. $$$a$$$ is now $$$\left\{1\right\}$$$. The second task requires you to add $$$2$$$ into $$$a$$$. $$$a$$$ is now $$$\left\{1, 2\right\}$$$. The third task asks you a question with $$$x = 1$$$, $$$k = 1$$$ and $$$s = 3$$$. Taking both $$$1$$$ and $$$2$$$ as $$$v$$$ satisfies $$$1 \mid GCD(1, v)$$$ and $$$1 + v \leq 3$$$. Because $$$2 \oplus 1 = 3 > 1 \oplus 1 = 0$$$, $$$2$$$ is the answer to this task. The fourth task asks you a question with $$$x = 1$$$, $$$k = 1$$$ and $$$s = 2$$$. Only $$$v = 1$$$ satisfies $$$1 \mid GCD(1, v)$$$ and $$$1 + v \leq 2$$$, so $$$1$$$ is the answer to this task. The fifth task asks you a question with $$$x = 1$$$, $$$k = 1$$$ and $$$s = 1$$$. There are no elements in $$$a$$$ that satisfy the conditions, so we report -1 as the answer to this task. | Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.Sadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him.Initally, there is an empty array $$$a$$$. The game consists of $$$q$$$ tasks of two types. The first type asks Katie to add a number $$$u_i$$$ to $$$a$$$. The second type asks Katie to find a number $$$v$$$ existing in $$$a$$$ such that $$$k_i \mid GCD(x_i, v)$$$, $$$x_i + v \leq s_i$$$, and $$$x_i \oplus v$$$ is maximized, where $$$\oplus$$$ denotes the bitwise XOR operation, $$$GCD(c, d)$$$ denotes the greatest common divisor of integers $$$c$$$ and $$$d$$$, and $$$y \mid x$$$ means $$$x$$$ is divisible by $$$y$$$, or report -1 if no such numbers are found.Since you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her! | For each task of type $$$2$$$, output on one line the desired number $$$v$$$, or -1 if no such numbers are found. | The first line contains one integer $$$q$$$ ($$$2 \leq q \leq 10^{5}$$$) — the number of tasks the game wants you to perform. $$$q$$$ lines follow, each line begins with an integer $$$t_i$$$ — the type of the task: If $$$t_i = 1$$$, an integer $$$u_i$$$ follow ($$$1 \leq u_i \leq 10^{5}$$$) — you have to add $$$u_i$$$ to the array $$$a$$$. If $$$t_i = 2$$$, three integers $$$x_i$$$, $$$k_i$$$, and $$$s_i$$$ follow ($$$1 \leq x_i, k_i, s_i \leq 10^{5}$$$) — you must find a number $$$v$$$ existing in the array $$$a$$$ such that $$$k_i \mid GCD(x_i, v)$$$, $$$x_i + v \leq s_i$$$, and $$$x_i \oplus v$$$ is maximized, where $$$\oplus$$$ denotes the XOR operation, or report -1 if no such numbers are found. It is guaranteed that the type of the first task is type $$$1$$$, and there exists at least one task of type $$$2$$$. | standard output | standard input | PyPy 2 | Python | 2,200 | train_064.jsonl | ac811bf2e0c46fdd98a15cd7169787d6 | 512 megabytes | ["5\n1 1\n1 2\n2 1 1 3\n2 1 1 2\n2 1 1 1", "10\n1 9\n2 9 9 22\n2 3 3 18\n1 25\n2 9 9 20\n2 25 25 14\n1 20\n2 26 26 3\n1 14\n2 20 20 9"] | PASSED | import sys
range = xrange
input = raw_input
big = 10**5 + 1
M = 1
while M < big:
M *= 2
mini = [0]
L = [0]
R = [0]
roots = [0]*big
def add(x, i):
bits = []
xx = x + M
while xx != 1:
bits.append(xx&1)
xx >>= 1
if not roots[i]:
roots[i] = len(mini)
mini.append(x)
L.append(0)
R.append(0)
node = roots[i]
mini[node] = min(mini[node], x)
for b in reversed(bits):
nesta = R if b else L
if not nesta[node]:
nesta[node] = len(mini)
mini.append(x)
L.append(0)
R.append(0)
node = nesta[node]
mini[node] = min(mini[node], x)
found = [0]*big
divisors = [[] for _ in range(big)]
for i in range(1, big):
ii = i
while ii < big:
divisors[ii].append(i)
ii += i
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
out = []
q = inp[ii]; ii += 1
for _ in range(q):
t = inp[ii]; ii += 1
if t == 1:
u = inp[ii]; ii += 1
if not found[u]:
found[u] = 1
for d in divisors[u]:
add(u, d)
else:
x = inp[ii]; ii += 1
k = inp[ii]; ii += 1
s = inp[ii]; ii += 1
if x % k != 0:
out.append(-1)
continue
s -= x
node = roots[k]
if not node or mini[node] > s:
out.append(-1)
continue
xbits = []
xx = x + M
while xx > 1:
xbits.append(xx&1)
xx >>= 1
for bit in reversed(xbits):
alt1,alt2 = (L[node],R[node]) if bit else (R[node],L[node])
if alt1 and mini[alt1] <= s:
node = alt1
elif alt2 and mini[alt2] <= s:
node = alt2
else:
break
else:
out.append(mini[node])
continue
out.append(-1)
print '\n'.join(str(x) for x in out)
| 1526308500 | [
"number theory",
"math",
"strings",
"trees"
] | [
0,
0,
0,
1,
1,
0,
1,
1
] |
|
1 second | ["9\n1\n0\n7\n10\n7\n5", "12\n10\n10\n8\n7"] | b8321b0a3fc8c295182a4c2c8d2e9d01 | NoteLet's consider the first sample. The first participant starts at floor s = 2 by the time equal to t = 3. To get to the floor f = 4, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t = 0 on the floor s = 1, enters the elevator immediately, and arrives to the floor f = 2. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts. | And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then — to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti. | Print n lines each containing one integer — the time of the arrival for each participant to the required floor. | The first line contains two space-separated integers n and m (1 ≤ n ≤ 105, 2 ≤ m ≤ 108). Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1 ≤ si, fi ≤ m, 0 ≤ ti ≤ 108), described in the problem statement. | standard output | standard input | Python 2 | Python | 1,300 | train_019.jsonl | 91ca3fe928fddd6a4497a5fa28261b72 | 256 megabytes | ["7 4\n2 4 3\n1 2 0\n2 2 0\n1 2 1\n4 3 5\n1 2 2\n4 2 0", "5 5\n1 5 4\n1 3 1\n1 3 4\n3 1 5\n4 2 5"] | PASSED | n,m = map(int, str(raw_input()).split())
while n:
n-=1
s,f,t = map(int, str(raw_input()).split())
if s==f:
print t
continue
x = 2*(m-1)
result = t-t%x
t %= x
if(t <= s-1):
flag = True
elif(t<= x-s+1):
flag = False
else:
result += x
flag = True
if(s<f and flag==False):
result += x+f-1
elif(s<f and flag):
result += f-1
else:
result += x-f+1
print result
| 1316790000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1.000000000000", "1.714285714286"] | a69b342ef5f6e11f7aa4fee71e149aa2 | NoteIn the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make .In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal . | The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value. | Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6. | The first input line contains two integers n and m (2 ≤ n ≤ 100, ) — the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n, vi ≠ ui) — the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space. It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads. | standard output | standard input | Python 3 | Python | 1,900 | train_005.jsonl | 227b05e69a1f3a53ca8a05b2636cc83c | 256 megabytes | ["4 4\n1 2\n2 4\n1 3\n3 4", "11 14\n1 2\n1 3\n2 4\n3 4\n4 5\n4 6\n5 11\n6 11\n1 8\n8 9\n9 7\n11 7\n1 10\n10 4"] | PASSED | from collections import deque
n, m = [int(i) for i in input().split()]
g = [[] for i in range(n)]
for i in range(m):
u, v = [int(i) - 1 for i in input().split()]
g[u].append(v)
g[v].append(u)
def bfs(s):
d = [-1] * n
ct = [0.0] * n
q = deque()
d[s] = 0
ct[s] = 1.0
q.append(s)
while q:
v = q.popleft()
for u in g[v]:
if d[u] == -1:
q.append(u)
d[u] = d[v] + 1
ct[u] += ct[v]
elif d[u] == d[v] + 1:
ct[u] += ct[v]
return d, ct
ds = []
cts = []
for i in range(n):
d, ct = bfs(i)
ds.append(d)
cts.append(ct)
x = cts[0][n - 1]
r = 1.0
for i in range(1, n - 1):
if ds[0][i] + ds[i][n - 1] == ds[0][n - 1]:
r = max(r, 2.0 * cts[0][i] * cts[i][n - 1] / x)
print('{0:.10f}'.format(r))
| 1343057400 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["12\n33\n75"] | 204e75827b7016eb1f1fbe1d6b60b03d | NoteLet us explain the three test cases in the sample.Test case 1: $$$n = 11$$$: $$$\text{$$$gcdSum$$$}(11) = gcd(11, 1 + 1) = gcd(11,\ 2) = 1$$$.$$$\text{$$$gcdSum$$$}(12) = gcd(12, 1 + 2) = gcd(12,\ 3) = 3$$$.So the smallest number $$$\ge 11$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$12$$$.Test case 2: $$$n = 31$$$: $$$\text{$$$gcdSum$$$}(31) = gcd(31, 3 + 1) = gcd(31,\ 4) = 1$$$.$$$\text{$$$gcdSum$$$}(32) = gcd(32, 3 + 2) = gcd(32,\ 5) = 1$$$.$$$\text{$$$gcdSum$$$}(33) = gcd(33, 3 + 3) = gcd(33,\ 6) = 3$$$.So the smallest number $$$\ge 31$$$ whose $$$gcdSum$$$ $$$> 1$$$ is $$$33$$$.Test case 3: $$$\ n = 75$$$: $$$\text{$$$gcdSum$$$}(75) = gcd(75, 7 + 5) = gcd(75,\ 12) = 3$$$.The $$$\text{$$$gcdSum$$$}$$$ of $$$75$$$ is already $$$> 1$$$. Hence, it is the answer. | The $$$\text{$$$gcdSum$$$}$$$ of a positive integer is the $$$gcd$$$ of that integer with its sum of digits. Formally, $$$\text{$$$gcdSum$$$}(x) = gcd(x, \text{ sum of digits of } x)$$$ for a positive integer $$$x$$$. $$$gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$ — the largest integer $$$d$$$ such that both integers $$$a$$$ and $$$b$$$ are divisible by $$$d$$$.For example: $$$\text{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$.Given an integer $$$n$$$, find the smallest integer $$$x \ge n$$$ such that $$$\text{$$$gcdSum$$$}(x) > 1$$$. | Output $$$t$$$ lines, where the $$$i$$$-th line is a single integer containing the answer to the $$$i$$$-th test case. | The first line of input contains one integer $$$t$$$ $$$(1 \le t \le 10^4)$$$ — the number of test cases. Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(1 \le n \le 10^{18})$$$. All test cases in one test are different. | standard output | standard input | PyPy 3-64 | Python | 800 | train_107.jsonl | b0964708cb42fead0975db53ce72e05a | 256 megabytes | ["3\n11\n31\n75"] | PASSED | import math
def solve():
t = int(input())
while t:
t-=1
n = input()
b = 0
for c in n:
b += int(c)
val = math.gcd(int(n),b)
if val>1:
print(n)
else:
temp = int(n)
while val < 2:
temp += 1
b = 0
for c in str(temp):
b += int(c)
val = math.gcd(temp,b)
print(temp)
solve() | 1617028500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["YES\nNO\nYES\nYES\nNO"] | 080f29d4e2aa5bb9ee26d882362c8cd7 | NoteIn the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): $$$[1, \underline{2}, 3] \rightarrow [\underline{1}, 3] \rightarrow [\underline{3}] \rightarrow [\,].$$$In the second test case, it is impossible to erase the sequence as $$$i$$$ can only be $$$1$$$, and when $$$i=1$$$, $$$a_1 = 2$$$ is divisible by $$$i + 1 = 2$$$. | YouKn0wWho has an integer sequence $$$a_1, a_2, \ldots, a_n$$$. He will perform the following operation until the sequence becomes empty: select an index $$$i$$$ such that $$$1 \le i \le |a|$$$ and $$$a_i$$$ is not divisible by $$$(i + 1)$$$, and erase this element from the sequence. Here $$$|a|$$$ is the length of sequence $$$a$$$ at the moment of operation. Note that the sequence $$$a$$$ changes and the next operation is performed on this changed sequence.For example, if $$$a=[3,5,4,5]$$$, then he can select $$$i = 2$$$, because $$$a_2 = 5$$$ is not divisible by $$$i+1 = 3$$$. After this operation the sequence is $$$[3,4,5]$$$.Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation. | For each test case, print "YES" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower). | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,300 | train_083.jsonl | efc6aeb3d84a71a03ed79c9ccc8df5ec | 256 megabytes | ["5\n3\n1 2 3\n1\n2\n2\n7 7\n10\n384836991 191890310 576823355 782177068 404011431 818008580 954291757 160449218 155374934 840594328\n8\n6 69 696 69696 696969 6969696 69696969 696969696"] | PASSED | import math
#'YES'
t = int(input())
for _ in range(t):
n = int(input())
arr = [int(i) for i in input().split()]
if arr[0] % 2 == 0:
print('NO')
else:
np = 0
lmp = 0
for i in range(n):
cur = i+1
if arr[i] % 2 != 0:
lmp += 1
else:
if arr[i] % (cur+1) != 0:
lmp += 1
else:
start = 0
temp = lmp
while temp > 0 and arr[i] % (cur+1-start) == 0:
temp -= 1
start += 1
if arr[i] % (cur+1-start) == 0:
np = 1
break
lmp += 1
if np:
print('NO')
else:
print('YES')
| 1635604500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["0\n2\n3\n2"] | a9c54d6f952320d75324b30dcb098332 | NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible: invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$); invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$); invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$); invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$). The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value. | A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even? | For each test case, print a line containing a single integer – the minimum possible unhappiness value of a valid party. | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(10^5,\frac{n(n-1)}{2})$$$) — the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots,a_n$$$ ($$$0 \leq a_i \leq 10^4$$$) — the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x,y \leq n$$$, $$$x \neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,300 | train_083.jsonl | 873f1d3eafb66c9d065e98249aa4cca6 | 256 megabytes | ["4\n\n1 0\n\n1\n\n3 1\n\n2 1 3\n\n1 3\n\n5 5\n\n1 2 3 4 5\n\n1 2\n\n1 3\n\n1 4\n\n1 5\n\n2 3\n\n5 5\n\n1 1 1 1 1\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n5 1"] | PASSED | import sys
input = sys.stdin.readline
from collections import defaultdict as dd
t=int(input())
while(t):
t-=1
n,m=list(map(int,input().split()))
l=list(map(int,input().split()))
ct=[0]*(n+1)
l1=[]
for x in range(1,m+1):
a,b=list(map(int,input().split()))
l1.append([a,b])
ct[a]+=1
ct[b]+=1
ans=1000000001
if m%2==0:
ans=0
else:
for x in range(1,n+1):
if ct[x]%2==1:
ans=min(ans,l[x-1])
for x in range(1,m+1):
if ct[l1[x-1][0]]%2==0 and ct[l1[x-1][1]]%2==0:
ans=min(ans,l[l1[x-1][0]-1]+l[l1[x-1][1]-1])
sys.stdout.write(str(ans)+"\n")
#python=TLE | 1658673300 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
4 seconds | ["9\n000\n01", "2\n193\n81\n91"] | 37d906de85f173aca2a9a3559cbcf7a3 | null | There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number. | Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them. | The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct. | standard output | standard input | Python 3 | Python | 1,600 | train_028.jsonl | 350b2bb400a66f5cc1d89a3da85a9218 | 256 megabytes | ["3\n123456789\n100000000\n100123456", "4\n123456789\n193456789\n134567819\n934567891"] | PASSED | def add_subs(num, freq):
used = set()
for l in range(1, len(num) + 1):
for i in range(len(num) - l + 1):
end = i + l
sub = num[i : end]
if sub not in used:
used.add(sub)
if sub not in freq:
freq[sub] = 1
else:
freq[sub] += 1
def count_subs(nums):
freq = {}
for n in nums:
add_subs(n, freq)
return freq
def find_sub(num, freq):
for l in range(1, len(num)):
for i in range(len(num) - l + 1):
end = i + l
sub = num[i : end]
if freq[sub] == 1:
return sub
return num
def main():
n = int(input())
nums = [input() for i in range(n)]
freq = count_subs(nums)
for number in nums:
print(find_sub(number, freq))
main()
| 1505653500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["NO\nYES"] | c686c3592542b70a3b617eb639c0e3f4 | null | In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.Your program should handle the queries of the following two types: "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. | For each query of the second type print "YES" or "NO" on a separate line depending on the answer. | The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. | standard output | standard input | Python 3 | Python | 1,500 | train_019.jsonl | f786c8d298fd53654bdfdb025f863a08 | 256 megabytes | ["5\n1 1 5\n1 5 11\n2 1 2\n1 2 9\n2 1 2"] | PASSED | #Globales
Set, h = [], []
#Metodos
def dfs(a, b, Len, h):
if a == b:
return True
Len[a] = True
for x in h[a]:
if not Len[x] and dfs(x, b, Len, h):
return True
return False
def main():
for i in range(int(input())):
q, x, y = map(int, input().split())
if q == 1:
Set.append((x, y))
h.append([])
for i, partSet in enumerate(Set):
if x in range(partSet[0] + 1, partSet[1]) or y in range(partSet[0] + 1, partSet[1]):
h[-1].append(i)
if partSet[0] in range(x + 1, y) or partSet[1] in range(x + 1, y):
h[i].append(len(Set) - 1)
else:
print('YES' if dfs(x - 1, y - 1, [False] * len(Set), h) else 'NO')
main() #Ejecuta el main
| 1371992400 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["Bob\nBob\nAlice\nAlice\nAlice\nBob\nBob\nBob"] | 581c89736e549300c566e4700b741906 | NoteLet's consider the first test case of the example.Alice has one card with integer $$$6$$$, Bob has two cards with numbers $$$[6, 8]$$$.If Alice is the first player, she has to play the card with number $$$6$$$. Bob then has to play the card with number $$$8$$$. Alice has no cards left, so she loses.If Bob is the first player, then no matter which of his cards he chooses on the first turn, Alice won't be able to play her card on the second turn, so she will lose. | Alice and Bob play a game. Alice has $$$n$$$ cards, the $$$i$$$-th of them has the integer $$$a_i$$$ written on it. Bob has $$$m$$$ cards, the $$$j$$$-th of them has the integer $$$b_j$$$ written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on — the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has $$$4$$$ cards with numbers $$$[10, 5, 3, 8]$$$, and Bob has $$$3$$$ cards with numbers $$$[6, 11, 6]$$$, the game may go as follows: Alice can choose any of her cards. She chooses the card with integer $$$5$$$ and plays it. Bob can choose any of his cards with number greater than $$$5$$$. He chooses a card with integer $$$6$$$ and plays it. Alice can choose any of her cards with number greater than $$$6$$$. She chooses the card with integer $$$10$$$ and plays it. Bob can choose any of his cards with number greater than $$$10$$$. He chooses a card with integer $$$11$$$ and plays it. Alice can choose any of her cards with number greater than $$$11$$$, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions: who wins if Alice is the first player? who wins if Bob is the first player? | For each test case, print two lines. The first line should be Alice if Alice wins when she is the first player; otherwise, the first line should be Bob. The second line should contain the name of the winner if Bob is the first player, in the same format. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of four lines. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of cards Alice has. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the numbers written on the cards that Alice has. The third line contains one integer $$$m$$$ ($$$1 \le m \le 50$$$) — the number of Bob's cards. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 50$$$) — the numbers on Bob's cards. | standard output | standard input | Python 3 | Python | 800 | train_087.jsonl | 64d4ae99e53328c886067f6a1434cde8 | 256 megabytes | ["4\n\n1\n\n6\n\n2\n\n6 8\n\n4\n\n1 3 3 7\n\n2\n\n4 2\n\n1\n\n50\n\n2\n\n25 50\n\n10\n\n1 2 3 4 5 6 7 8 9 10\n\n2\n\n5 15"] | PASSED | r='Alice','Bob'
R=lambda:max(map(int,input().split()))
for _ in[0]*R():R();a=R();R();b=R();print(r[a<b]+'\n'+r[a<=b]) | 1653316500 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["No", "Yes\n5\n1 2 4 5 6", "Yes\n4\n2 4 5 8"] | d5d470f2848e779310e5e54eccca8b4a | NoteIn the second sample, the valid pairs in the output set are (1, 2), (1, 4), (1, 5), (1, 6), (2, 4), (2, 6). Thus, .In the third example, the valid pairs in the output set are (2, 4), (4, 8), (2, 8). Thus, . | Imp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more. Let's define for some set of integers as the number of pairs a, b in , such that: a is strictly less than b; a divides b without a remainder. You are to find such a set , which is a subset of {1, 2, ..., n} (the set that contains all positive integers not greater than n), that . | If there is no answer, print "No". Otherwise, in the first line print "Yes", in the second — an integer m that denotes the size of the set you have found, in the second line print m integers — the elements of the set , in any order. If there are multiple answers, print any of them. | The only line contains two integers n and k . | standard output | standard input | PyPy 2 | Python | 2,400 | train_004.jsonl | 4de4fd5210aa055ad585bfb952f2da02 | 256 megabytes | ["3 3", "6 6", "8 3"] | PASSED | import time,random,os
n,k=map(int,raw_input().split(' '))
t0=time.time()
while time.time()-t0<=0.8:
t=range(1,n+1)
g=[0]*(n+1)
app=[0]*(n+1)
random.shuffle(t)
rm=k
op=[]
for a in t:
su=g[a]
if su>rm:
continue
cur=a+a
while cur<=n and su<=rm:
su=su+app[cur]
cur+=a
if su>rm:
continue
rm-=su
op.append(a)
app[a]=1
cur=a
while cur<=n:
g[cur]+=1
cur+=a
if not rm:
break
if not rm:
print 'Yes'
print len(op)
print ' '.join(map(str,op))
os._exit(0)
print 'No' | 1518023700 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["1\n-1\n3"] | d132158607bbd0541f2232a300e4a1b1 | null | You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation: $$$z = acace$$$ (if we choose subsequence $$$ace$$$); $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$); $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$. | For each testcase, print one integer — the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$. | The first line contains the integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \le |t| \le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 2 | Python | 1,600 | train_023.jsonl | 3405facae75c047108e51810dff6c5f3 | 256 megabytes | ["3\naabce\nace\nabacaba\naax\nty\nyyt"] | PASSED | #!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil, factorial
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
from fractions import Fraction
from functools import reduce
import sys
import os
import re
inf = float('inf')
mod_ = int(1e9) + 7
mod = 998244353
def main():
for _ in range(int(input())):
s = input()
t = input()
position = defaultdict(list)
for i in range(len(s)):
position[s[i]].append(i)
ans, tind, sind = 1, 0, 0
for tind in range(len(t)):
if t[tind] not in position:
print(-1)
break
cind = bisect_left(position[t[tind]], sind)
if cind == len(position[t[tind]]):
sind = position[t[tind]][0] + 1
ans += 1
else:
sind = position[t[tind]][cind] + 1
else:
print(ans)
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(
b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def gcd(x, y):
while y:
x, y = y, x % y
return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
def bootstrap(cont):
call, arg = cont.switch()
while True:
call, arg = cont.switch(to=continulet(
lambda _, f, args: f(*args), call, arg))
cont = continulet(bootstrap)
cont.switch()
main() | 1580308500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1 4 3\n4 1 2\n300000000 300000000 300000000\n999999998 1 1\n1 2 2"] | e0ec0cd81d2ec632ef89d207d80fa8a3 | NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences. | Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$. | For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \dots, b_7$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$). Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement. | standard output | standard input | Python 3 | Python | 800 | train_087.jsonl | 6190165bc56a36f783638350f49bcc01 | 256 megabytes | ["5\n1 3 4 4 5 7 8\n1 2 3 4 5 6 7\n300000000 300000000 300000000 600000000 600000000 600000000 900000000\n1 1 2 999999998 999999999 999999999 1000000000\n1 2 2 3 3 4 5"] | 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 invr():
return(map(int,input().split()))
outp = []
x = inp()
for i in range(x):
lis = inlt()
a = lis[0]
b = lis[1]
if lis[2] == a+b:
output = [a,b,lis[3]]
else:
output = [a,b,lis[2]]
outp.append(output)
for out in outp:
print(out[0],out[1],out[2])
| 1639492500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds | ["2\n6\n9\n10\n20"] | a00e2e79a3914ee11202a799c9bc01e7 | NoteFor first query: n = 6, f = 2. Possible partitions are [1, 5] and [5, 1].For second query: n = 7, f = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning. | Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that ith friend is given ai sweets. He wants to make sure that there should not be any positive integer x > 1, which divides every ai.Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (109 + 7).To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (109 + 7). | For each query, output a single integer in a line corresponding to the answer of each query. | The first line contains an integer q representing the number of queries (1 ≤ q ≤ 105). Each of the next q lines contains two space space-separated integers n, f (1 ≤ f ≤ n ≤ 105). | standard output | standard input | Python 3 | Python | 2,100 | train_042.jsonl | 8b5f7945551a610f438d17246fb5e461 | 256 megabytes | ["5\n6 2\n7 2\n6 3\n6 4\n7 4"] | PASSED | import itertools
import functools
import operator
N = 100001
P = 10**9 + 7
fact = [1]
for i in range(1, N):
fact.append(fact[-1] * i % P)
inv = [0, 1]
for i in range(2, N):
inv.append(P - P // i * inv[P % i] % P)
inv_fact = [1]
for i in range(1, N):
inv_fact.append(inv_fact[-1] * inv[i] % P)
least_div = [-1] * N
primes = []
for p in range(2, N):
if least_div[p] == -1:
primes.append(p)
least_div[p] = p
ldiv = least_div[p]
for mult in primes:
mark = mult * p
if (mult > ldiv) or (mark >= N):
break
least_div[mark] = mult
t = int(input())
def powerset(iterable):
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))
memo_factor = dict()
def factor(n):
if n in memo_factor:
return memo_factor[n]
ret = []
while n != 1:
tmp = least_div[n]
if not(ret and ret[-1] == tmp):
ret.append(tmp)
n //= tmp
memo_factor[n] = ret
return ret
@functools.lru_cache(maxsize = None)
def solve(n, k):
divs = factor(n)
# print(divs)
ret = 0
for subset in powerset(divs):
div = functools.reduce(operator.mul, subset, 1)
# print(div, f(n // div, k))
if n // div >= k:
tmp = fact[n // div - 1] * inv_fact[n // div - k] % P * inv_fact[k - 1] % P
ret += (-1 if len(subset) % 2 == 1 else 1) * tmp
ret %= P
return ret
for _ in range(t):
n, k = map(int, input().split())
print(solve(n, k))
| 1401895800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["9 3 6 12 4 8", "126 42 84 28", "3000000000000000000 1000000000000000000"] | f9375003a3b64bab17176a05764c20e8 | NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$. | Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds: divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$); multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists. | Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists. | The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board. | standard output | standard input | PyPy 3 | Python | 1,400 | train_001.jsonl | fce49720753405c68c5fb134cdfcacd3 | 256 megabytes | ["6\n4 8 6 3 12 9", "4\n42 28 84 126", "2\n1000000000000000000 3000000000000000000"] | PASSED | def f(n, b, c=0):
while n % b == 0:
n //= b
c += 1
return c
n, a = int(input()), [int(i) for i in input().split()]
print(*sorted(a, key = lambda x: (f(x, 2), -f(x, 3))))
| 1567258500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["YES", "NO"] | a457e22fc8ff882c15ac57bca6960657 | NoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p. | As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... | Output YES if the string s contains heidi as a subsequence and NO otherwise. | The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z). | standard output | standard input | Python 3 | Python | 800 | train_008.jsonl | f4fd10e26098f40f8e48955a23fd8bcf | 256 megabytes | ["abcheaibcdi", "hiedi"] | PASSED | x =[i for i in input()]
def charpos(c1,arr):
for i in range(len(arr)):
if arr[i] ==c1:
return i
return -1
temp=0
result =True
for i in "heidi":
temp = charpos(i,x)
x = x[temp:]
if temp==-1:
result=False
break
if result:
print("YES")
else:
print("NO")
| 1495958700 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["0 1 1 2 0 4 \n0 0 1 \n0 1 2 0 2 5 6 2"] | a83aaaa8984d1a6dda1adf10127b7abc | NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct. | Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays: $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$); $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$); $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below. $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change. $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{2}, \textbf{1}, 3, 4, 5, 6]$$$. $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{1}, 4, 5, 6]$$$. $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\textbf{1}, \textbf{4}, \textbf{3}, \textbf{2}, 5, 6]$$$. $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change. $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{5}, \textbf{6}, \textbf{1}, \textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations. | For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \dots, d_n$$$ ($$$d_i \ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them. | The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2\cdot10^3$$$) — the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\cdot10^3$$$. | standard output | standard input | PyPy 3-64 | Python | 1,300 | train_104.jsonl | 180570f023d62d350db9f8510d3b81f6 | 256 megabytes | ["3\n\n6\n\n3 2 5 6 1 4\n\n3\n\n3 1 2\n\n8\n\n5 8 1 3 2 6 4 7"] | PASSED | #!/usr/bin/env pypy3
import io, os, sys
from sys import stdin, stdout
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def input(): return stdin.readline().strip()
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())
from itertools import permutations, chain, combinations, product
from math import factorial, gcd
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from bisect import bisect_left
from functools import lru_cache
### CODE HERE
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i | (i + 1)
if j < len(x):
x[j] += x[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
while idx < len(self.bit):
self.bit[idx] += x
idx |= idx + 1
def query(self, end):
"""calc sum(bit[:end])"""
x = 0
while end:
x += self.bit[end - 1]
end &= end - 1
return x
def findkth(self, k):
"""Find largest idx such that sum(bit[:idx]) <= k"""
idx = -1
for d in reversed(range(len(self.bit).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(self.bit) and k >= self.bit[right_idx]:
idx = right_idx
k -= self.bit[idx]
return idx + 1
class IndexingDelList:
"""
A list with fast index and del operations
Note: del is with indexes of the original
However, get/set are not supported
"""
from collections import defaultdict
def __init__(self, A):
self.ones = FenwickTree([1]*len(A))
self.A = list(A)
self.index_of = dict()
for i, a in enumerate(A):
self.index_of[a] = i
self.total_len = len(A)
def index(self, n):
return self.ones.query(self.index_of[n])
def __getitem__(self, k):
# not implemented, could do some binary search
assert(False)
def __setitem__(self, k, v):
assert(False)
def __len__(self):
return self.total_len
def remove(self, a):
self.total_len -= 1
idx = self.index_of[a]
self.ones.update(idx, -1)
def ans(A):
N = len(A)
A = IndexingDelList([a-1 for a in A])
last = N
ret = []
for n in range(N-1, -1, -1):
r = A.index(n)
gap = (r + len(A) - last + 1) % len(A)
ret += [gap]
last = r
A.remove(n)
print(*ret[::-1])
for _ in range(read_int()):
input()
ans(read_int_list())
| 1646750100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3\n1 6\n2 4\n5 7", "1\n1 2", "1\n2 4"] | a019519539d493201bef69aff31bcd4e | NoteHere are the points and the moves for the ones that get chosen for the moves from the first example: | There are $$$n$$$ points on an infinite plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$ such that $$$x_i > 0$$$ and $$$y_i > 0$$$. The coordinates are not necessarily integer.In one move you perform the following operations: choose two points $$$a$$$ and $$$b$$$ ($$$a \neq b$$$); move point $$$a$$$ from $$$(x_a, y_a)$$$ to either $$$(x_a + 1, y_a)$$$ or $$$(x_a, y_a + 1)$$$; move point $$$b$$$ from $$$(x_b, y_b)$$$ to either $$$(x_b + 1, y_b)$$$ or $$$(x_b, y_b + 1)$$$; remove points $$$a$$$ and $$$b$$$. However, the move can only be performed if there exists a line that passes through the new coordinates of $$$a$$$, new coordinates of $$$b$$$ and $$$(0, 0)$$$. Otherwise, the move can't be performed and the points stay at their original coordinates $$$(x_a, y_a)$$$ and $$$(x_b, y_b)$$$, respectively.The numeration of points does not change after some points are removed. Once the points are removed, they can't be chosen in any later moves. Note that you have to move both points during the move, you can't leave them at their original coordinates.What is the maximum number of moves you can perform? What are these moves?If there are multiple answers, you can print any of them. | In the first line print a single integer $$$c$$$ — the maximum number of moves you can perform. Each of the next $$$c$$$ lines should contain a description of a move: two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the points that are removed during the current move. There should be a way to move points $$$a$$$ and $$$b$$$ according to the statement so that there's a line that passes through the new coordinates of $$$a$$$, the new coordinates of $$$b$$$ and $$$(0, 0)$$$. No removed point can be chosen in a later move. If there are multiple answers, you can print any of them. You can print the moves and the points in the move in the arbitrary order. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains four integers $$$a_i, b_i, c_i, d_i$$$ ($$$1 \le a_i, b_i, c_i, d_i \le 10^9$$$). The coordinates of the $$$i$$$-th point are $$$x_i = \frac{a_i}{b_i}$$$ and $$$y_i = \frac{c_i}{d_i}$$$. | standard output | standard input | PyPy 3 | Python | 2,700 | train_102.jsonl | 5154763a6c9ef29bd686e2df0069fd1a | 256 megabytes | ["7\n4 1 5 1\n1 1 1 1\n3 3 3 3\n1 1 4 1\n6 1 1 1\n5 1 4 1\n6 1 1 1", "4\n2 1 1 1\n1 1 2 1\n2 1 1 2\n1 2 1 2", "4\n182 168 60 96\n78 72 45 72\n69 21 144 63\n148 12 105 6"] | PASSED | import sys
from sys import stdin
import math
from collections import deque
n = int(stdin.readline())
dic = {}
lis = []
for i in range(n):
a,b,c,d = map(int,stdin.readline().split())
A,B,C,D = a+b,b,c,d
siA = C * B
boA = D * A
g = math.gcd(siA,boA)
siA //= g
boA //= g
if (siA,boA) not in dic:
dic[(siA,boA)] = len(dic)
lis.append([])
A,B,C,D = a,b,c+d,d
siB = C * B
boB = D * A
g = math.gcd(siB,boB)
siB //= g
boB //= g
if (siB,boB) not in dic:
dic[(siB,boB)] = len(dic)
lis.append([])
va = dic[(siA,boA)]
vb = dic[(siB,boB)]
lis[va].append( (vb,i) )
lis[vb].append( (va,i) )
ans = []
used = [False] * (3*n)
nexedge = [0] * (3*n)
able = [True] * (3*n)
pedge = [None] * (3*n)
for v in range(len(lis)):
if not able[v]:
continue
stk = [v]
able[v] = False
while stk:
v = stk[-1]
if len(lis[v]) <= nexedge[v]:
elis = []
for nex,ind in lis[v]:
if ind != pedge[v] and not used[ind]:
elis.append(ind)
if pedge[v] != None and not used[pedge[v]]:
elis.append(pedge[v])
for i in range(1,len(elis),2):
ans.append( (elis[i-1]+1,elis[i]+1) )
used[elis[i-1]] = True
used[elis[i]] = True
del stk[-1]
continue
nex,ind = lis[v][nexedge[v]]
nexedge[v] += 1
if able[nex]:
pedge[nex] = ind
able[nex] = False
stk.append(nex)
print (len(ans))
for i in ans:
print (*i) | 1619706900 | [
"geometry",
"trees",
"graphs"
] | [
0,
1,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["NO\nYES\nNO\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO\nYES"] | 3cd56870a96baf8860e9b7e89008d895 | null | You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string $$$s$$$ is a substring of YesYesYes... (Yes repeated many times in a row). | Output $$$t$$$ lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if the specified string $$$s$$$ is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer). | The first line of input data contains the singular $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Each test case is described by a single string of Latin letters $$$s$$$ ($$$1 \le |s| \le 50$$$) — the part of Polycarp's answer that you heard, where $$$|s|$$$ — is the length of the string $$$s$$$. | standard output | standard input | Python 3 | Python | 800 | train_086.jsonl | f6d829173d49c526fb4f0aa9d9533fcb | 256 megabytes | ["12\n\nYES\n\nesYes\n\ncodeforces\n\nes\n\nse\n\nYesY\n\nesYesYesYesYesYesYe\n\nseY\n\nYess\n\nsY\n\no\n\nYes"] | PASSED | number = int(input())
cases = []
for i in range(number):
cases.append(input())
def yesno(c):
if c in "YesYes"*(len(c)//6+2):
return "Yes"
else:
return "NO"
for c in cases:
print(yesno(c))
| 1668782100 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["2", "2"] | ad2c4d07da081505fa251ba8c27028b1 | NoteIn the first example there are two ways: xxo xoo xox ooo oxx oox | Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo 1000000007 (109 + 7). Two cells of the board are adjacent if they share a side. | Print a single integer — the answer to the problem. | The first line contains two integers n, k (1 ≤ n, k ≤ 105) — the size of the board, and the number of cells that has characters initially. Then k lines follows. The i-th line contains two integers and a character: ai, bi, ci (1 ≤ ai, bi ≤ n; ci is either 'o' or 'x'). This line means: there is a character ci in the cell that is located on the intersection of the ai-th row and bi-th column. All the given cells are distinct. Consider that the rows are numbered from 1 to n from top to bottom. Analogically, the columns are numbered from 1 to n from left to right. | standard output | standard input | Python 2 | Python | 2,800 | train_060.jsonl | df038c5e145652e0ae1f133373c0ef04 | 256 megabytes | ["3 2\n1 1 x\n2 2 o", "4 3\n2 4 x\n3 4 x\n3 2 x"] | PASSED | from sys import stdin
def main():
n, k = map(int, stdin.readline().split())
par = [range(n+10), range(n+10)]
def find(i, x):
if par[i][x] == x:
return x
else:
par[i][x] = find(i, par[i][x])
return par[i][x]
def unite(i, x, y):
x, y = find(i, x), find(i, y)
par[i][x] = y
mod = 1000000007
m = (n + 1) / 2
for _ in xrange(k):
l = stdin.readline().split()
r, c, b = int(l[0]) - 1, int(l[1]) - 1, int(l[2] == 'o')
p = (r + c) % 2
if r > m:
r, c = n - 1 - r, n - 1 - c
L, R = c - r, c + r
if L < 0:
L = -L
if R >= n:
R = 2 * (n - 1) - R
unite(p, L+b, R+2)
unite(p, L+1-b, R+3)
c = 0
for p in [0, 1]:
for i in xrange([m, n-m][p]+1):
L, R = p+i+i, p+i+i+1
l, r = find(p, L), find(p, R)
if l == r:
print 0
return
if l == L:
c += 1
print pow(2, c - 2, mod)
main() | 1409061600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["$2,012.00", "$0.00", "($0.00)", "($12,345,678.90)"] | c704c5fb9e054fab1caeab534849901d | NotePay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format. | For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point). To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them? | Print the number given in the input in the financial format by the rules described in the problem statement. | The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs "-" (minus) and "." (decimal point). The number's notation is correct, that is: The number's notation only contains characters from the set {"0" – "9", "-", "."}. The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: "0"). The minus sign (if it is present) is unique and stands in the very beginning of the number's notation If a number is identically equal to 0 (that is, if it is written as, for example, "0" or "0.000"), than it is not preceded by the minus sign. The input data contains no spaces. The number's notation contains at least one decimal digit. | standard output | standard input | Python 3 | Python | 1,200 | train_010.jsonl | 1804266ce908e1129fc309a3998e358d | 256 megabytes | ["2012", "0.000", "-0.00987654321", "-12345678.9"] | PASSED | import math, re, sys, string, operator, functools, fractions, collections
sys.setrecursionlimit(10**7)
RI=lambda x=' ': list(map(int,input().split(x)))
RS=lambda x=' ': input().rstrip().split(x)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
mod=int(1e9+7)
eps=1e-6
pi=math.acos(-1.0)
MAX=100
#################################################
s=RS()[0]
st=0
if s[0]=='-':
st=1
s=s[st:].split('.')
i,f="0","0"
i=s[0]
if len(s)>1:
f=s[1]
i=i[::-1]
f=f[::-1]
ans='$'+(','.join([i[j:j+3] for j in range(0,len(i),3)]))[::-1]
ans+= '.'+f.zfill(2)[::-1][:2]
if st:
ans='('+ans+')'
print(ans)
| 1326380700 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["2", "0", "4"] | d3e972b7652c0c1321c2e8f15dbc264b | NoteIn the first case, the answer is $$$2$$$, as the whole array is good: $$$5 \& 6 = 4 > 5 \oplus 6 = 3$$$.In the third case, the answer is $$$4$$$, and one of the longest good subarrays is $$$[a_2, a_3, a_4, a_5]$$$: $$$1\& 3 \& 3 \&1 = 1 > 1\oplus 3 \oplus 3\oplus 1 = 0$$$. | Bakry got bored of solving problems related to xor, so he asked you to solve this problem for him.You are given an array $$$a$$$ of $$$n$$$ integers $$$[a_1, a_2, \ldots, a_n]$$$.Let's call a subarray $$$a_{l}, a_{l+1}, a_{l+2}, \ldots, a_r$$$ good if $$$a_l \, \& \, a_{l+1} \, \& \, a_{l+2} \, \ldots \, \& \, a_r > a_l \oplus a_{l+1} \oplus a_{l+2} \ldots \oplus a_r$$$, where $$$\oplus$$$ denotes the bitwise XOR operation and $$$\&$$$ denotes the bitwise AND operation.Find the length of the longest good subarray of $$$a$$$, or determine that no such subarray exists. | Print a single integer — the length of the longest good subarray. If there are no good subarrays, print $$$0$$$. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the array. | standard output | standard input | PyPy 2 | Python | 2,400 | train_106.jsonl | 03148d1d3d87d331660d5363e9f713ba | 256 megabytes | ["2\n5 6", "3\n2 4 3", "6\n8 1 3 3 1 2"] | PASSED | from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return list(map(str,input().strip().split(" ")))
def le(): return list(map(int,input().split()))
def rc(): return map(float,input().split())
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def joron(L):
return('\n'.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
boi=int(998244353)
doi=int(1e9+7)
hoi=int(1e6+1e5+5)
poi=int(1009)
y="YES"
n="NO"
def gosa(x, y):
while(y):
x, y = y, x % y
return x
L=[0]*hoi
M=[0]*hoi
N=[0]*hoi
O=[0]*hoi
def bulli(x):
return bin(x).count('1')
def iu():
import sys
import math as my
import functools
input=sys.stdin.readline
from collections import deque, defaultdict
bec=0
m=so()
P=le()
for i in range(1,1+m):
L[i]=P[i-1]
for i in range(20,-1,-1):
M[0]=0
for j in range(1,1<<20):
M[j]=-1
for j in range(1,1+m):
N[j]=(L[j]>>i&1)+N[j-1]
O[j]=O[j]^((N[j]%2)<<i)
z=(N[j]%2)
zz=O[j]
if(-1==zz):
M[zz]=j
else:
if(j-N[j]==M[zz]-N[M[zz]]):
bec=max(j-M[zz],bec)
else:
M[zz]=j
print(bec)
def main():
for i in range(1):
#print("Case #"+str(i+1)+": ",end="")
iu()
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read() | 1633271700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1 1 1 2 -1 1 1 3 1 1"] | 9271c88a3bc3c69855daeda9bb6bbaf5 | null | You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move, you can jump from the position $$$i$$$ to the position $$$i - a_i$$$ (if $$$1 \le i - a_i$$$) or to the position $$$i + a_i$$$ (if $$$i + a_i \le n$$$).For each position $$$i$$$ from $$$1$$$ to $$$n$$$ you want to know the minimum the number of moves required to reach any position $$$j$$$ such that $$$a_j$$$ has the opposite parity from $$$a_i$$$ (i.e. if $$$a_i$$$ is odd then $$$a_j$$$ has to be even and vice versa). | Print $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$, where $$$d_i$$$ is the minimum the number of moves required to reach any position $$$j$$$ such that $$$a_j$$$ has the opposite parity from $$$a_i$$$ (i.e. if $$$a_i$$$ is odd then $$$a_j$$$ has to be even and vice versa) or -1 if it is impossible to reach such a position. | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | standard output | standard input | Python 2 | Python | 1,900 | train_008.jsonl | 65a43994e1db0c200db1350790b7b34e | 256 megabytes | ["10\n4 5 7 6 7 5 4 4 6 4"] | PASSED |
class Solution(object):
def solve(self,array):
"""
:type arr: List[int]
:type start: int
:rtype: bool
"""
from collections import defaultdict,deque
D=defaultdict(list)
self.t_max=float('inf')
for i in range(0,len(array)):
if array[i]+i<len(array):
D[array[i]+i].append(i)
if i-array[i]>=0:
D[i-array[i]].append(i)
close=[self.t_max]*len(array)
Q=deque()
for target in D:
for source in D[target]:
if (array[target]+array[source])%2==1:
close[source]=1
Q.append((source,2))
while(Q):
#print Q
target,step=Q.popleft()
#print "target,step:",target,step
for source in D[target]:
if close[source]<=step:
continue
if (array[target]+array[source])%2==1:
close[source]=1
continue
else:
close[source]=min(close[source],step)
Q.append((source,step+1))
for i in range(0,len(close)):
if close[i]==self.t_max:
close[i]=-1
return close
if __name__=="__main__":
input_len=int(raw_input().strip())
array=map(int,raw_input().split(" "))
T=Solution()
ans= T.solve(array)
for i in range(0,len(ans)-1):
print ans[i],
print ans[-1]
| 1576157700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["8\n2\n11\n1111111110"] | 7a51d536d5212023cc226ef1f6201174 | null | You are given two integers $$$l$$$ and $$$r$$$, where $$$l < r$$$. We will add $$$1$$$ to $$$l$$$ until the result is equal to $$$r$$$. Thus, there will be exactly $$$r-l$$$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example: if $$$l=909$$$, then adding one will result in $$$910$$$ and $$$2$$$ digits will be changed; if you add one to $$$l=9$$$, the result will be $$$10$$$ and $$$2$$$ digits will also be changed; if you add one to $$$l=489999$$$, the result will be $$$490000$$$ and $$$5$$$ digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get $$$r$$$ from $$$l$$$, adding $$$1$$$ each time. | For each test case, calculate the total number of changed digits if you want to get $$$r$$$ from $$$l$$$, adding one each time. | The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$). | standard output | standard input | PyPy 3 | Python | 1,500 | train_097.jsonl | 50a668437258d7b7d8f523c58bcc3909 | 256 megabytes | ["4\n1 9\n9 10\n10 20\n1 1000000000"] | PASSED | import sys
def memoize(f):
st = {}
def _mk_r():
def r(*args):
_k = args
if _k in st:
return st[_k]
c = f(*args)
st[_k] = c
# print(f'{key}{_k} -> {c}')
return c
return r
return _mk_r()
def run():
class _fake_int(object):
def __init__(self):
super().__init__()
self.v = 0
def use(self, c, l) -> slice:
v = self.v
self.v += c
return l[v:v + c]
_stdin, _pos = sys.stdin.read().split(), _fake_int()
def inp(count=1, tp=int):
return map(tp, _pos.use(count, _stdin))
ss = ['9' * i for i in range(20)]
@memoize
def dp(j, i):
a = ss[j]
n = len(a) - i
if n == 1:
return int(a[-1])
elif not n:
return 0
else:
c = int(a[i])
return (dp(n - 1, 0) + n - 1) * c + c + dp(j, i + 1)
def solve(ss=ss):
l, r = inp(2, str)
ss += [l, r]
print(dp(len(ss) - 1, 0) - dp(len(ss) - 2, 0))
t, = inp()
while t != 0:
solve()
t -= 1
run()
| 1623335700 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
4 seconds | ["465\n12\n986128624\n7636394\n57118194"] | d8ba9b38f7b2293452363ccd9c21d748 | null | Calculate the number of permutations $$$p$$$ of size $$$n$$$ with exactly $$$k$$$ inversions (pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$p_i > p_j$$$) and exactly $$$x$$$ indices $$$i$$$ such that $$$p_i > p_{i+1}$$$.Yep, that's the whole problem. Good luck! | For each test case, print one integer — the answer to the problem, taken modulo $$$998244353$$$. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$) — the number of test cases. Each test case consists of one line which contains three integers $$$n$$$, $$$k$$$ and $$$x$$$ ($$$1 \le n \le 998244352$$$; $$$1 \le k \le 11$$$; $$$1 \le x \le 11$$$). | standard output | standard input | PyPy 3 | Python | 2,700 | train_087.jsonl | 1217acb44ea0b3f6015bbb004457aed7 | 512 megabytes | ["5\n\n10 6 4\n\n7 3 1\n\n163316 11 7\n\n136373 11 1\n\n325902 11 11"] | PASSED | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v, w):
return u + v * l1 + w * l2
def g(x):
u = x % l1
v = x % l2 // l1
w = x // l2
return u, v, w
pow2 = [1]
for _ in range(13):
pow2.append(2 * pow2[-1])
sp = set()
for i in pow2:
sp.add(i - 1)
n, l1 = 13, 13
l2 = l1 * l1
l3 = l1 * l2
pn = pow2[n]
dp = [[0] * l3 for _ in range(pn)]
for i in range(n):
dp[pow2[i]][f(0, 0, i)] = 1
for i in range(2, pn):
if i in sp:
continue
dpi = dp[i]
nx = []
c = 0
for j in range(n - 1, -1, -1):
if i & pow2[j]:
c += 1
else:
nx.append((j, c))
for j in range(l3):
if not dpi[j]:
continue
u0, v0, w = g(j)
for k, c in nx:
u, v = u0 + c, v0
if w > k:
v += 1
if max(u, v) < l1:
dp[i ^ pow2[k]][f(u, v, k)] += dpi[j]
cnt = [[] for _ in range(n + 1)]
p = 0
for i in range(1, n + 1):
p += pow2[i - 1]
dpi = dp[p]
for j in range(1, l1):
for k in range(1, l1):
c = 0
for l in range(i):
c += dpi[f(j, k, l)]
if c:
cnt[i].append((j, k, c))
mod = 998244353
l = 200
fact = [1] * (l + 1)
for i in range(1, l + 1):
fact[i] = i * fact[i - 1] % mod
inv = [1] * (l + 1)
inv[l] = pow(fact[l], mod - 2, mod)
for i in range(l - 1, -1, -1):
inv[i] = (i + 1) * inv[i + 1] % mod
dp = [[0] * (3 * l3) for _ in range(l1)]
dp[0][0] = 1
for i in range(2, n + 1):
for j, k, c in cnt[i]:
for l in range(l1 - 2, -1, -1):
dpl = dp[l]
for x in range(3 * l3):
y = dpl[x]
if not y:
continue
u0, v0, w0 = g(x)
u, v, w = u0 + j, v0 + k, w0 + i
m = l + 1
while max(u, v, m) < l1 and w < 3 * l1:
y *= c
y %= mod
dp[m][f(u, v, w)] += y * inv[m - l] % mod
dp[m][f(u, v, w)] %= mod
u, v, w = u + j, v + k, w + i
m += 1
t = int(input())
ans = []
for _ in range(t):
n, k, x = map(int, input().split())
if k < x:
ans0 = 0
ans.append(ans0)
continue
ans0 = 0
for i in range(1, l1):
dpi = dp[i]
for j in range(3 * l1):
if n - j + i < 0 or not dpi[f(k, x, j)]:
continue
c, l = 1, n - j + i
for _ in range(i):
c *= l
c %= mod
l -= 1
ans0 += dpi[f(k, x, j)] * c % mod
ans0 %= mod
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans))) | 1650638100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["5\n2 1 4 7 5 \n4\n1 5\n2 5\n5 4\n3 4"] | ff8219b0e4fd699b1898500664087e90 | NoteOne of the possible structures in the first example: | The Dogeforces company has $$$k$$$ employees. Each employee, except for lower-level employees, has at least $$$2$$$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company. | In the first line, print a single integer $$$k$$$ — the number of employees in the company. In the second line, print $$$k$$$ integers $$$c_1, c_2, \dots, c_k$$$, where $$$c_i$$$ is the salary of the employee with the number $$$i$$$. In the third line, print a single integer $$$r$$$ — the number of the employee who is the head of the company. In the following $$$k-1$$$ lines, print two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le k$$$) — the number of the employee and his direct supervisor. Note that the lower-level employees have numbers from $$$1$$$ to $$$n$$$, and for the rest of the employees, you have to assign numbers from $$$n+1$$$ to $$$k$$$. If there are several correct company structures, you can print any of them. | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 500$$$) — the number of lower-level employees. This is followed by $$$n$$$ lines, where $$$i$$$-th line contains $$$n$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,n}$$$ ($$$1 \le a_{i,j} \le 5000$$$) — salary of the common supervisor of employees with numbers $$$i$$$ and $$$j$$$. It is guaranteed that $$$a_{i,j} = a_{j,i}$$$. Note that $$$a_{i,i}$$$ is equal to the salary of the $$$i$$$-th employee. | standard output | standard input | PyPy 3-64 | Python | 2,300 | train_094.jsonl | c4d7e01d107b6923cdd8b469dc1b7d35 | 256 megabytes | ["3\n2 5 7\n5 1 7\n7 7 4"] | PASSED | import sys
input = sys.stdin.buffer.readline
def findroot(parent, x):
y = x
while y != parent[y]:
y = parent[y]
return y
def process(A):
n = len(A[0])
parent = [i for i in range(n)]
weight = [None for i in range(n)]
L = []
for i in range(n):
w = A[i][i]
weight[i] = w
for j in range(i):
L.append([A[i][j], i, j])
m = len(L)
L.sort()
x = n
graph = []
for i in range(m):
w, I, J = L[i]
I1 = findroot(parent, I)
J1 = findroot(parent, J)
if I1 != J1:
if weight[I1]==w:
graph.append([J1, I1])
parent[J1] = I1
elif weight[J1]==w:
graph.append([I1, J1])
parent[I1] = J1
else:
parent.append(x)
weight.append(w)
parent[I1] = x
parent[J1] = x
graph.append([I1, x])
graph.append([J1, x])
x+=1
n = len(weight)
sys.stdout.write(f'{n}\n')
weight = ' '.join(map(str, weight))
sys.stdout.write(f'{weight}\n')
sys.stdout.write(f'{n}\n')
for a, b in graph:
sys.stdout.write(f'{a+1} {b+1}\n')
k = int(input())
A = []
for i in range(k):
row = [int(x) for x in input().split()]
A.append(row)
process(A) | 1614696300 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["3", "3"] | f3dde329830d8c479b3dab9d5df8baf5 | NoteIn the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4).In the second sample any couple of clients is opposite. | Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of customers."Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1, - 1, 1, - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself. | Print the number of couples of customs with opposite t. The opposite number for x is number - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. | The first line of the input data contains an integer n (1 ≤ n ≤ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 ≤ ti ≤ 10), ti — is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests. | standard output | standard input | Python 3 | Python | 1,200 | train_002.jsonl | bbe0c6853e557bf03be2e99021a7bc1d | 256 megabytes | ["5\n-3 3 0 0 3", "3\n0 0 0"] | PASSED | data = input()
cnt = int(data[0])
t = [int(i) for i in input().split()]
d = dict()
for idx in range(-10, 11):
d[idx] = 0
for r in t:
d[r] += 1
s = 0
for idx in range(1, 11):
s += d[idx] * d[(-idx)]
if d[0] > 1:
for idx in range(1, d[0]):
s += idx
print(s) | 1322233200 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n1", "0", "4\n1 2 3 4"] | 794b0ac038e4e32f35f754e9278424d3 | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | standard output | standard input | Python 3 | Python | 2,300 | train_014.jsonl | df5efee3e21521aba858c9ded9496d96 | 256 megabytes | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | PASSED | n=int(input().strip())
nums=['']+[' '+input().strip() for _ in range(n)]
a=[0]+list(map(int,input().split()))
def send(x):
for i in range(1,n+1):
if nums[x][i]=='1':
a[i]-=1
vis=[0]*(n+1)
while True:
for i in range(1,n+1):
if not vis[i] and not a[i]:
vis[i]=1
send(i)
break
else:
for i in range(1,n+1):
if not a[i]:
print(-1)
exit()
break
ans=[]
for i in range(1,n+1):
if vis[i]:
ans.append(i)
if ans:
print(len(ans))
print(*ans)
else:
print(0)
| 1433595600 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["17\n1\n3\n4", "1"] | b7942cf792c368cc240ed22e91ad406f | NoteIn the first example, the array $$$A$$$ obtained is $$$[1, 2, 3, 3, 4, 4]$$$. We can see that the array is sortable by doing the following operations: Choose index $$$5$$$, then $$$A = [1, 2, 3, 3, 6, 4]$$$. Choose index $$$6$$$, then $$$A = [1, 2, 3, 3, 6, 6]$$$. Choose index $$$4$$$, then $$$A = [1, 2, 3, 4, 6, 6]$$$. Choose index $$$6$$$, then $$$A = [1, 2, 3, 4, 6, 8]$$$. | Let's say Pak Chanek has an array $$$A$$$ consisting of $$$N$$$ positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following: Choose an index $$$p$$$ ($$$1 \leq p \leq N$$$). Let $$$c$$$ be the number of operations that have been done on index $$$p$$$ before this operation. Decrease the value of $$$A_p$$$ by $$$2^c$$$. Multiply the value of $$$A_p$$$ by $$$2$$$. After each operation, all elements of $$$A$$$ must be positive integers.An array $$$A$$$ is said to be sortable if and only if Pak Chanek can do zero or more operations so that $$$A_1 < A_2 < A_3 < A_4 < \ldots < A_N$$$.Pak Chanek must find an array $$$A$$$ that is sortable with length $$$N$$$ such that $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$ is the minimum possible. If there are more than one possibilities, Pak Chanek must choose the array that is lexicographically minimum among them.Pak Chanek must solve the following things: Pak Chanek must print the value of $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$ for that array. $$$Q$$$ questions will be given. For the $$$i$$$-th question, an integer $$$P_i$$$ is given. Pak Chanek must print the value of $$$A_{P_i}$$$. Help Pak Chanek solve the problem.Note: an array $$$B$$$ of size $$$N$$$ is said to be lexicographically smaller than an array $$$C$$$ that is also of size $$$N$$$ if and only if there exists an index $$$i$$$ such that $$$B_i < C_i$$$ and for each $$$j < i$$$, $$$B_j = C_j$$$. | Print $$$Q+1$$$ lines. The $$$1$$$-st line contains an integer representing $$$A_1 + A_2 + A_3 + A_4 + \ldots + A_N$$$. For each $$$1 \leq i \leq Q$$$, the $$$(i+1)$$$-th line contains an integer representing $$$A_{P_i}$$$. | The first line contains two integers $$$N$$$ and $$$Q$$$ ($$$1 \leq N \leq 10^9$$$, $$$0 \leq Q \leq \min(N, 10^5)$$$) — the required length of array $$$A$$$ and the number of questions. The $$$i$$$-th of the next $$$Q$$$ lines contains a single integer $$$P_i$$$ ($$$1 \leq P_1 < P_2 < \ldots < P_Q \leq N$$$) — the index asked in the $$$i$$$-th question. | standard output | standard input | PyPy 3-64 | Python | 2,900 | train_093.jsonl | c09458318e0550d6c5de3b52ccac47e8 | 512 megabytes | ["6 3\n1\n4\n5", "1 0"] | PASSED | ## Fast I/O
import io,os,sys
# Fast input. Use s = input().decode() for strings
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# Fast output
def print(*args, sep = ' ', end = '\n'):
string = sep.join(map(str, args))+end
sys.stdout.write(string)
def debug(*args, sep = ' ', end = '\n'):
string = "Debug: " + sep.join(map(str, args)) + end
sys.stderr.write(string)
# from collections import Counter, defaultdict
# from functools import lru_cache
# from math import floor, ceil, sqrt, gcd
# from sys import stderr
from bisect import bisect
N, Q = map(int, input().split())
somme = 0
act = 1
i = 0
j = 1
sizes = []
while i < N:
if i + j <= N:
i += j
somme += act * j
sizes.append(j)
else:
break
act += 1
if i + j <= N:
i += j
somme += act * j
sizes.append(j)
else:
break
act += 1
j += 1
sizes = sizes[::-1]
k = len(sizes)
sizes.append(0)
for _ in range(N-i):
sizes[k] += 1
k -= 2
somme += (N - i) * act
print(somme)
def lsb(x):
return x & (-x)
def root(x):
l = lsb(x)
return x//l + l.bit_length() - 1
def pos(k):
l = lsb(k)
x = (k//l)>>1
y = l.bit_length() - 1
return x, y
shift = 0
offset = 0
for _ in range(Q):
q = int(input())
while True:
# print("shift", shift)
# print("offset", offset)
k = q - offset
# print("searching", k)
gi1 = 2 * sizes[shift] - 1
if k <= gi1:
# print("in grid")
# k est présent dans la grille
x, y = pos(k)
y += shift
y += 2*x
print(y+1)
break
else:
# print("shifting.")
shift += 1
offset += (gi1 + 1) // 2
#
# @PoustouFlan
# Code:Choke?!
# [ 极客 ]
#
| 1662298500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n3\n3\n10"] | ac4aac095e71cbfaf8b79262d4038095 | null | You are given an array $$$a$$$ of $$$n$$$ integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$. | For each test case output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$. | 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 of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,200 | train_083.jsonl | 23d1f492d2cabafd0e351f6929d223bb | 256 megabytes | ["4\n6\n3 5 1 4 6 6\n3\n1 2 3\n4\n1 3 3 4\n6\n1 6 3 4 5 6"] | PASSED | LENGHT = 4*10**3
PRIME_NUMB = 99999989
PRIME_NUMB2 = 999999937
from enum import Enum, auto
import random
import time
class Situation(Enum):
EMPTY = auto
DELETED = auto
FILLED = auto
class HashTable():
def __init__(self , lenght = LENGHT):
self.lenght = lenght
self.table = [[] for _ in range(lenght)]
def __hash(self, value):
return (value % PRIME_NUMB) % self.lenght
def __hash2(self, value):
return (value % PRIME_NUMB2) % self.lenght
def __insert_linearProbe(self, value , i = 0):
pos = (self.__hash(value) + i) % self.lenght
if len(self.table[pos]) != 0 :
if self.table[pos][0] == value :
self.table[pos].append(value)
elif self.table[pos][0] == Situation.DELETED :
self.table[pos][0] = value
else:
self.__insert_linearProbe(value , i+1)
else:
self.table[pos].append(value)
def __insert_squareProbe(self, value , i =0):
c1 = 5
c2 = 7
pos = (self.__hash(value) + c2*i**2 + c1*i) % self.lenght
if len(self.table[pos]) != 0 :
if self.table[pos][0] == value :
self.table[pos].append(value)
elif self.table[pos][0] == Situation.DELETED :
self.table[pos][0] = value
else:
self.__insert_squareProbe(value , i+1)
else:
self.table[pos].append(value)
def __insert_binaryHash(self, value , i = 0):
pos = (self.__hash(value) + i*self.__hash2(value)) % self.lenght
if len(self.table[pos]) != 0 :
if self.table[pos][0] == value :
self.table[pos].append(value)
elif self.table[pos][0] == Situation.DELETED :
self.table[pos][0] = value
else:
self.__insert_binaryHash(value , i+1)
else:
self.table[pos].append(value)
def __delete_linearProbe(self, value, i= 0):
pos = (self.__hash(value) + i) % self.lenght
v = 0
while v < self.lenght:
if len(self.table[pos]) != 0:
if self.table[pos][0] == Situation.DELETED:
continue
if self.table[pos][0] == value:
self.table[pos].remove(value)
if len(self.table[pos]) == 0:
self.table[pos].append(Situation.DELETED)
break
v = v + 1
raise Exception("this value was not inserted")
def insert(self , value):
self.__insert_linearProbe(value)
def delete(self, value):
self.__delete_linearProbe(value)
# t1 = time.time()
# v = [random.randint(1 , 2*10**5) for _ in range(100000)]
# t = HashTable(v)
# print(t.table)
# t2 = time.time()
# print(f'time : {t2 - t1}')
testCases = int(input())
for i in range(testCases):
cases = 0
n = int(input())
temp = input().split()
# print(temp)
values = [int(temp[i]) - i for i in range(n)]
# print(values)
t = HashTable(5*n)
for i in range(n):
t.insert(values[i])
for i in range(len(t.table)):
cases += (len(t.table[i]) - 1)*(len(t.table[i]))/2
print(int(cases))
# print(t.table)
# print(t.table) | 1620225300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["<RUn.exe O>\n<>\n< 2ne, >\n<two!>\n<.>\n< >", "<firstarg>\n<second>\n<>"] | 6c7858731c57e1b24c7a299a8eeab373 | null | The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters. | In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples. | The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme. | standard output | standard input | PyPy 2 | Python | 1,300 | train_009.jsonl | 64451ed6fca0f307fe206c14c502607f | 256 megabytes | ["\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"", "firstarg second \"\""] | PASSED | s = raw_input().strip()
lexemes = []
quoting = False
chars = []
for pos, ch in enumerate(s):
if ch == '"':
if not quoting:
quoting = True
continue
lexemes.append('<' + ''.join(chars) + '>')
chars = []
quoting = False
continue
if ch == ' ':
if quoting:
chars.append(ch)
elif chars != []:
lexemes.append('<' + ''.join(chars) + '>')
chars = []
continue
chars.append(ch)
if chars != []:
lexemes.append('<' + ''.join(chars) + '>')
print('\n'.join(lexemes))
| 1365796800 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["0.0000000000", "18.0038068653"] | 754df388958709e3820219b14beb7517 | null | You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost (N-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row. | Output the expected number of steps on a line of itself with at least 4 digits after the decimal point. | On the first line you will be given two space separated integers N and M (1 ≤ N, M ≤ 1000). On the second line you will be given another two space separated integers i and j (1 ≤ i ≤ N, 1 ≤ j ≤ M) — the number of the initial row and the number of the initial column. Note that, (1, 1) is the upper left corner of the board and (N, M) is the bottom right corner. | standard output | standard input | Python 3 | Python | 2,400 | train_080.jsonl | f538afd9ecec4411db8ccabdd6c25bfa | 256 megabytes | ["10 10\n10 4", "10 14\n5 14"] | PASSED | n,m = (int(s) for s in input().split())
i,j = (int(s) for s in input().split())
def find(n,m,i,j):
if i==n:
return 0
if m==1:
return 2*(n-i)
e,a,b = [0.]*m,[0]*m,[0]*m
for l in range(n-1,0,-1):
a[0],b[0]=.5,.5*(3+e[0])
for k in range(1,m-1):
a[k] = 1/(3-a[k-1])
b[k] = a[k]*(b[k-1]+4+e[k])
e[m-1] = (3+b[m-2]+e[m-1])/(2-a[m-2])
for k in range(m-2,-1,-1):
e[k]=a[k]*e[k+1]+b[k]
if l == i: return e[j]
print (find(n,m,i,m-j)) | 1280149200 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2.5 seconds | ["4 6"] | 6d0bc28aa0b47c12438a84e57cd8e081 | NoteThe 5-by-5 grid for the first test case looks like this: maytheforcebewithyouhctwo | The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star.The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps. | The only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1. If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists. | The first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format. | standard output | standard input | Python 3 | Python | 2,000 | train_015.jsonl | 8f818b36ff89af69420d5bbcef59514a | 256 megabytes | ["10 5\nsomer\nandom\nnoise\nmayth\neforc\nebewi\nthyou\nhctwo\nagain\nnoise\nsomermayth\nandomeforc\nnoiseebewi\nagainthyou\nnoisehctwo"] | PASSED | n, m = list(map(int, input().strip().split(' ')))
mat1, mat2 = [], []
for i in range(0, n): mat1.append(tuple(input().strip()))
for i in range(0, m): mat2.append(tuple(input().strip()))
ix, jx, flg = -1, -1, 0
matr, matc = [], []
for i in range(0, n-m+1):
si, se = i, i+m
matr.append(hash(tuple(mat1[si:se])))
matcur2 = []
for c2i in range(0, m): matcur2.append(tuple(mat2[c2i][si:se]))
matc.append(hash(tuple(matcur2)))
nx = len(matr)
ix, jx = -1, -1
for ix in range(0, nx):
flg=0
for jx in range(0, nx):
if matr[ix]==matc[jx]:
flg=1
break
if flg==1: break
print(str(ix+1)+" "+str(jx+1)) | 1523689500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["332748119\n332748119", "3", "160955686\n185138929\n974061117"] | ba9c136f84375cd317f0f8b53e3939c7 | NoteIn the first example, if the only visit shows the first picture with a probability of $$$\frac 2 3$$$, the final weights are $$$(1,1)$$$; if the only visit shows the second picture with a probability of $$$\frac1 3$$$, the final weights are $$$(2,2)$$$.So, both expected weights are $$$\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$$$ .Because $$$332748119\cdot 3\equiv 4\pmod{998244353}$$$, you need to print $$$332748119$$$ instead of $$$\frac4 3$$$ or $$$1.3333333333$$$.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $$$w_1$$$ will be increased by $$$1$$$.So, the expected weight is $$$1+2=3$$$.Nauuo is very naughty so she didn't give you any hint of the third example. | The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes $$$n$$$ pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $$$i$$$-th picture has a non-negative weight $$$w_i$$$, and the probability of the $$$i$$$-th picture being displayed is $$$\frac{w_i}{\sum_{j=1}^nw_j}$$$. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $$$1$$$ to its weight; otherwise, she would subtract $$$1$$$ from its weight.Nauuo will visit the website $$$m$$$ times. She wants to know the expected weight of each picture after all the $$$m$$$ visits modulo $$$998244353$$$. Can you help her?The expected weight of the $$$i$$$-th picture can be denoted by $$$\frac {q_i} {p_i}$$$ where $$$\gcd(p_i,q_i)=1$$$, you need to print an integer $$$r_i$$$ satisfying $$$0\le r_i<998244353$$$ and $$$r_i\cdot p_i\equiv q_i\pmod{998244353}$$$. It can be proved that such $$$r_i$$$ exists and is unique. | The output contains $$$n$$$ integers $$$r_1,r_2,\ldots,r_n$$$ — the expected weights modulo $$$998244353$$$. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 2\cdot 10^5$$$, $$$1\le m\le 3000$$$) — the number of pictures and the number of visits to the website. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$a_i$$$ is either $$$0$$$ or $$$1$$$) — if $$$a_i=0$$$ , Nauuo does not like the $$$i$$$-th picture; otherwise Nauuo likes the $$$i$$$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $$$n$$$ positive integers $$$w_1,w_2,\ldots,w_n$$$ ($$$w_i \geq 1$$$) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed $$$998244352-m$$$. | standard output | standard input | PyPy 2 | Python | 2,600 | train_007.jsonl | 3c5cd6958f4986a074603d2532720d03 | 256 megabytes | ["2 1\n0 1\n2 1", "1 2\n1\n1", "3 3\n0 1 1\n4 3 5"] | PASSED | P = 998244353
N, M = map(int, raw_input().split())
A = [int(a) for a in raw_input().split()]
B = [int(a) for a in raw_input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
PO[i] = pow((SU+i)%P, P-2, P)
def calc(L):
su = sum(L)
pl = 0
pd = 0
RE = []
for i in range(len(L)):
a = li + i
b = di - (len(L) - 1 - i)
pd = b * L[i] * PO[a+b-SU]
RE.append((pl+pd)%P)
pl = a * L[i] * PO[a+b-SU]
RE.append(pl%P)
return RE
for i in range(M):
X = calc(X)
ne = 0
po = 0
for i in range(M+1):
po = (po + X[i] * (li + i)) % P
ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P) | 1559909100 | [
"probabilities"
] | [
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds | ["YES", "NO"] | 9ee3d548f93390db0fc2f72500d9eeb0 | NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit. | New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system. | If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO". | The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World. | standard output | standard input | Python 3 | Python | 1,000 | train_011.jsonl | e2da9fc9cbce369cdb16efbe1d988905 | 256 megabytes | ["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"] | PASSED | n, t = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
x = 0
i = 0
while i in range(0, t):
i += a[i]
if i == t-1:
x = 1
break
if x == 1:
print('YES')
else:
print('NO')
| 1419951600 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["1\n0\n2\n4\n4"] | d786585fee251ebfd5c3e8d8b0425791 | NoteIn the first test case, $$$s=1+2+3+4+5=15$$$, only $$$(2,3,4,5)$$$ is a nearly full subsequence among all subsequences, the sum in it is equal to $$$2+3+4+5=14=15-1$$$.In the second test case, there are no nearly full subsequences.In the third test case, $$$s=1+0=1$$$, the nearly full subsequences are $$$(0)$$$ and $$$()$$$ (the sum of an empty subsequence is $$$0$$$). | Luntik came out for a morning stroll and found an array $$$a$$$ of length $$$n$$$. He calculated the sum $$$s$$$ of the elements of the array ($$$s= \sum_{i=1}^{n} a_i$$$). Luntik calls a subsequence of the array $$$a$$$ nearly full if the sum of the numbers in that subsequence is equal to $$$s-1$$$.Luntik really wants to know the number of nearly full subsequences of the array $$$a$$$. But he needs to come home so he asks you to solve that problem!A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements. | For each test case print the number of nearly full subsequences of the array. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain descriptions of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 60$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. | standard output | standard input | Python 3 | Python | 900 | train_106.jsonl | 3cb3e8acfa1c66ce1dffe8a9d346e3ed | 256 megabytes | ["5\n5\n1 2 3 4 5\n2\n1000 1000\n2\n1 0\n5\n3 0 2 1 1\n5\n2 1 0 3 0"] | PASSED | t=int(input())
for k in range(t):
n=int(input())
s=list(map(int,input().split(' ')))
p1=s.count(1)
p2=s.count(0)
print(2**p2*p1) | 1635069900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2\nmasha 1 00123 \nivan 1 00123", "3\nkatya 1 612 \npetr 1 12 \nkarl 1 612", "2\ndasha 2 23 789 \nivan 4 789 123 2 456"] | df7b16d582582e6756cdb2d6d856c873 | null | Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.Vasya also believes that if the phone number a is a suffix of the phone number b (that is, the number b ends up with a), and both numbers are written by Vasya as the phone numbers of the same person, then a is recorded without the city code and it should not be taken into account.The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers x and y, and x is a suffix of y (that is, y ends in x), then you shouldn't print number x. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.Read the examples to understand statement and format of the output better. | Print out the ordered information about the phone numbers of Vasya's friends. First output m — number of friends that are found in Vasya's phone books. The following m lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend. Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order. | First line contains the integer n (1 ≤ n ≤ 20) — number of entries in Vasya's phone books. The following n lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros. | standard output | standard input | PyPy 3 | Python | 1,400 | train_026.jsonl | 620c7e1133a98a8610b8d3a932986028 | 256 megabytes | ["2\nivan 1 00123\nmasha 1 00123", "3\nkarl 2 612 12\npetr 1 12\nkatya 1 612", "4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789"] | PASSED | def cleaner(l):
l = list(set(l))
l.sort()
ans=[]
for i in range(len(l)):
for j in range(0,len(l)):
if l[j].endswith(l[i]) and i!=j:
break
else:
ans+=[l[i]]
return ans
d = dict()
for t in range(int(input())):
l = [x for x in input().split(" ")]
name,x = l[0],[1]
l = l[2:]
if name in d:
d[name]+=l
else:
d[name]=l
keys = d.keys()
print(len(keys))
for k in keys:
l = cleaner(d[k])
print(k,len(l),*l) | 1513424100 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["3\n1\n4"] | ce3f65acc33d624ed977e1d8f3494597 | NoteIn the first example, any edge $$$x \to y$$$ such that $$$x > y$$$ is valid, because there already is a path $$$1 \to 2 \to 3$$$.In the second example only the edge $$$4 \to 1$$$ is valid. There is a path $$$3 \to 4 \to 1 \to 2$$$ if this edge is added.In the third example you can add edges $$$2 \to 1$$$, $$$3 \to 1$$$, $$$4 \to 1$$$, $$$4 \to 2$$$. | You are given a directed acyclic graph with $$$n$$$ vertices and $$$m$$$ edges. For all edges $$$a \to b$$$ in the graph, $$$a < b$$$ holds.You need to find the number of pairs of vertices $$$x$$$, $$$y$$$, such that $$$x > y$$$ and after adding the edge $$$x \to y$$$ to the graph, it has a Hamiltonian path. | For each test case, print one integer: the number of pairs of vertices $$$x$$$, $$$y$$$, $$$x > y$$$, such that after adding the edge $$$x \to y$$$ to the graph, it has a Hamiltonian path. | The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 5$$$): the number of test cases. The next lines contains the descriptions of the test cases. In the first line you are given two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 150\,000$$$, $$$0 \leq m \leq \min(150\,000, \frac{n(n-1)}{2})$$$): the number of vertices and edges in the graph. Each of the next $$$m$$$ lines contains two integers $$$a$$$, $$$b$$$ ($$$1 \leq a < b \leq n$$$), specifying an edge $$$a \to b$$$ in the graph. No edge $$$a \to b$$$ appears more than once. | standard output | standard input | PyPy 3 | Python | 3,500 | train_101.jsonl | 4c32784f824e939589f7e424cf8220fb | 256 megabytes | ["3\n3 2\n1 2\n2 3\n4 3\n1 2\n3 4\n1 4\n4 4\n1 3\n1 4\n2 3\n3 4"] | PASSED | import io,os,sys
read = io.BytesIO(os.read(0, os.fstat(0).st_size))
I = lambda:map(int, read.readline().split())
import time
#I = lambda:map(int, sys.stdin.readline().split())
t, = I()
for _ in range(t):
n, m = I()
# if n > 100:
# print(time.time())
to = [[] for i in range(n)]
fro = [[] for i in range(n)]
for i in range(m):
a, b = I()
a -= 1
b -= 1
to[b].append(a)
fro[a].append(b)
# if n > 100:
# print(time.time())
for i in range(n):
to[i].sort()
fro[i].sort()
# if n > 100:
# print(time.time())
first = None
last = None
for i in range(n - 1):
if len(fro[i]) == 0 or fro[i][0] != i + 1:
if first is None:
first = i
last = i
if first is None:
print(n * (n - 1) // 2)
continue
# if n > 100:
# print(time.time())
y = first
i = first + 1
blue = {y}
red = set()
ruse = []
buse = []
if first == last:
buse.append(y)
while i < n - 1:
#print(i, red, blue)
i += 1
if len(to[i]) == 0:
blue = red = set()
break
if to[i][-1] != i - 1:
newr = set()
newb = set()
else:
newr = red
newb = blue
for guy in to[i]:
if guy < i - 1 and guy in blue:
newr.add(i - 1)
if guy < i - 1 and guy in red:
newb.add(i - 1)
blue = newb
red = newr
if i > last:
if i - 1 in blue:
buse.append(i - 1)
if i - 1 in red:
ruse.append(i - 1)
if len(blue) > 0:
ruse.append(n - 1)
if len(red) > 0:
buse.append(n - 1)
# if n > 100:
# print(time.time())
# print(i, red, blue)
# print(ruse, buse)
i = y
blue = set()
red = {y + 1}
ruse1 = []
buse1 = []
ruse1.append(y + 1)
while i > 0:
i -= 1
if len(fro[i]) == 0:
blue = red = set()
break
if fro[i][0] != i + 1:
newr = set()
newb = set()
else:
newr = red
newb = blue
for guy in fro[i]:
if guy > y + 1:
break
if guy > i + 1 and guy in blue:
newr.add(i + 1)
if guy > i + 1 and guy in red:
newb.add(i + 1)
blue = newb
red = newr
if i + 1 in blue:
buse1.append(i + 1)
if i + 1 in red:
ruse1.append(i + 1)
if len(blue) > 0:
ruse1.append(0)
if len(red) > 0:
buse1.append(0)
# print(ruse1, buse1)
# if n > 100:
# print(time.time())
ruse = set(ruse)
buse = set(buse)
ruse1 = set(ruse1)
buse1 = set(buse1)
both = ruse & buse
both1 = ruse1 & buse1
ruse -= both
buse -= both
ruse1 -= both1
buse1 -= both1
# print(ruse, buse, both, ruse1, buse1, both1)
x = len(ruse1) * (len(both) + len(buse)) + len(buse1) * (len(both) + len(ruse)) + len(both1) * (len(both) + len(ruse) + len(buse))
# print(x)
if first == last:
x -= 1
if y in ruse1 or y in both1:
x -= 1
if y + 1 in buse or y + 1 in both:
x -= 1
print(x)
# if n > 100:
# print(time.time())
# exit() | 1640792100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["2", "7"] | 180c19997a37974199bc73a5d731d289 | NoteThe following image describes the answer for the second sample case: | After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.A substring of a string is a subsequence of consecutive characters of the string. | In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. | In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. | standard output | standard input | PyPy 2 | Python | 1,900 | train_007.jsonl | 7205ab57459670266c0f0fe528f98b31 | 256 megabytes | ["3 2 2\nabc\nab", "9 12 4\nbbaaababb\nabbbabbaaaba"] | PASSED | def main():
n, m, k = map(int, raw_input().split())
dp = [[0] * (m + 1) for _ in xrange(n + 1)]
cnt = [[0] * (m + 1) for _ in xrange(n + 1)]
s, t = raw_input(), raw_input()
for i, c in enumerate(s):
for j in xrange(m):
if t[j] == c:
dp[i + 1][j + 1] = dp[i][j] + 1
for _ in xrange(k):
for i in xrange(n, -1, -1):
for j in xrange(m, - 1, -1):
dij = dp[i][j]
cnt[i][j] = dij + cnt[i - dij][j - dij]
for i in xrange(1, n + 1):
for j in xrange(1, m + 1):
cnt[i][j] = max(cnt[i][j], cnt[i - 1][j], cnt[i][j - 1], cnt[i - 1][j - 1])
print(cnt[n][m])
if __name__ == '__main__':
main()
| 1466181300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds | ["0\n\n\n0\n\n\n1\n\n\n1"] | 26c413fd747041b7501c451e36f92529 | NoteIn the example, the participants made 1, 2, and 3 mistakes respectively, therefore $$$b=1$$$ (the smallest of these numbers). Izzy made 3 mistakes, which were not more than $$$1.3\cdot b + 100=101.3$$$, so these outputs are good enough to pass this test case (as are any other valid outputs). | The popular improv website Interpretation Impetus hosts regular improv contests and maintains a rating of the best performers. However, since improv can often go horribly wrong, the website is notorious for declaring improv contests unrated. It now holds a wager before each improv contest where the participants try to predict whether it will be rated or unrated, and they are now more popular than the improv itself.Izzy and $$$n$$$ other participants take part in each wager. First, they each make their prediction, expressed as 1 ("rated") or 0 ("unrated"). Izzy always goes last, so she knows the predictions of the other participants when making her own. Then, the actual competition takes place and it is declared either rated or unrated.You need to write a program that will interactively play as Izzy. There will be $$$m$$$ wagers held in 2021, and Izzy's goal is to have at most $$$1.3\cdot b + 100$$$ wrong predictions after all those wagers, where $$$b$$$ is the smallest number of wrong predictions that any other wager participant will have after all those wagers. The number $$$b$$$ is not known in advance. Izzy also knows nothing about the other participants — they might somehow always guess correctly, or their predictions might be correlated. Izzy's predictions, though, do not affect the predictions of the other participants and the decision on the contest being rated or not — in other words, in each test case, your program always receives the same inputs, no matter what it outputs. | null | null | standard output | standard input | PyPy 3 | Python | 2,700 | train_099.jsonl | 5c7c5557fc80e0d98dce7f4a17cd4231 | 512 megabytes | ["3 4\n000\n\n1\n100\n\n1\n001\n\n0\n111\n\n1"] | PASSED | import math
from sys import stdout
from typing import List
def get_guesses() -> List[int]:
inp = input()
return [-1 if x == '0' else 1 for x in inp]
def guess(answer: int) -> None:
print(answer)
stdout.flush()
def get_ans() -> int:
true_ans = int(input())
return true_ans
def solve():
n, m = list(map(int, (input().split(" "))))
lr = .01
weights = [.0] * n
weights.append(0.0) # bias
for i in range(m):
g = get_guesses()
g.append(1)
weighted_sum = sum([weights[j] * g[j] for j in range(len(g))])
guess(1 if weighted_sum > 0 else 0)
sig_out = 1 / (1.0 + math.exp(-weighted_sum))
error = sig_out - get_ans()
# Square error
gradient = [g[i] * sig_out * (1 - sig_out) *
error for i in range(len(g))]
weights = [weights[i] - gradient[i] * lr for i in range(len(weights))]
solve()
| 1617523500 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second | ["quailty", "once again", "tokitsukaze", "once again"] | 5e73099c7ec0b82aee54f0841c00f15e | NoteIn the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win.In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the game to end in a draw.In the third example, Tokitsukaze can win by flipping the leftmost five cards up or flipping the rightmost five cards down.The fourth example can be explained in the same way as the second example does. | "Duel!"Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.There are $$$n$$$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $$$k$$$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $$$n$$$ cards face the same direction after one's move, the one who takes this move will win.Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes. | Print "once again" (without quotes) if the total number of their moves can exceed $$$10^9$$$, which is considered a draw. In other cases, print "tokitsukaze" (without quotes) if Tokitsukaze will win, or "quailty" (without quotes) if Quailty will win. Note that the output characters are case-sensitive, and any wrong spelling would be rejected. | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains a single string of length $$$n$$$ that only consists of $$$0$$$ and $$$1$$$, representing the situation of these $$$n$$$ cards, where the color side of the $$$i$$$-th card faces up if the $$$i$$$-th character is $$$1$$$, or otherwise, it faces down and the $$$i$$$-th character is $$$0$$$. | standard output | standard input | Python 2 | Python | 2,300 | train_050.jsonl | 0bb77906a08afd96e4246b8c6077f914 | 256 megabytes | ["4 2\n0101", "6 1\n010101", "6 5\n010101", "4 1\n0011"] | PASSED | import sys
import copy
input = sys.stdin.readline
n,k=map(int,raw_input().split())
C=list(raw_input().strip())
def JUDGE(C):
ANS_one=0
ANS_zero=0
for c in C:
if c=="0":
ANS_zero+=1
else:
break
for c in C[::-1]:
if c=="0":
ANS_zero+=1
else:
break
for c in C:
if c=="1":
ANS_one+=1
else:
break
for c in C[::-1]:
if c=="1":
ANS_one+=1
else:
break
if ANS_zero>=n-k or ANS_one>=n-k:
return 1
else:
return 0
if JUDGE(C)==1:
print("tokitsukaze")
sys.exit()
if k>=n-1:
print("quailty")
sys.exit()
if k<n/2:
print("once again")
sys.exit()
CAN1=copy.copy(C)
CAN2=copy.copy(C)
if C[0]=="0":
for i in range(1,k+1):
CAN1[i]="1"
else:
for i in range(1,k+1):
CAN1[i]="0"
if C[-1]=="0":
for i in range(n-1,n-k-1,-1):
CAN2[i]="1"
else:
for i in range(n-2,n-k-2,-1):
CAN2[i]="0"
if JUDGE(CAN1)==1 and JUDGE(CAN2)==1:
print("quailty")
sys.exit()
else:
print("once again")
sys.exit() | 1562942100 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
3 seconds | ["5.000000000 2.549499369\n4.000000000 0.378324889", "10.204081436 0.000000000\n4.000000000 0.378324889"] | d51aa18439e7afffa11ad181064c0450 | null | Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is directed rightwards in the city's direction, the Oy axis is directed upwards (to the sky). The cannon will make n more shots. The cannon balls' initial speeds are the same in all the shots and are equal to V, so that every shot is characterized by only one number alphai which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π / 4). We disregard the cannon sizes and consider the firing made from the point (0, 0).The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: vx(t) = V·cos(alpha) vy(t) = V·sin(alpha) – g·t x(t) = V·cos(alpha)·t y(t) = V·sin(alpha)·t – g·t2 / 2Think of the acceleration of gravity g as equal to 9.8.Bertown defends m walls. The i-th wall is represented as a vertical segment (xi, 0) - (xi, yi). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (y = 0) and stops. If the ball exactly hits the point (xi, yi), it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end. | Print n lines containing two real numbers each — calculate for every ball the coordinates of its landing point. Your answer should have the relative or absolute error less than 10 - 4. | The first line contains integers n and V (1 ≤ n ≤ 104, 1 ≤ V ≤ 1000) which represent the number of shots and the initial speed of every ball. The second line contains n space-separated real numbers alphai (0 < alphai < π / 4) which represent the angles in radians at which the cannon will fire. The third line contains integer m (1 ≤ m ≤ 105) which represents the number of walls. Then follow m lines, each containing two real numbers xi and yi (1 ≤ xi ≤ 1000, 0 ≤ yi ≤ 1000) which represent the wall’s coordinates. All the real numbers have no more than 4 decimal digits. The walls may partially overlap or even coincide. | standard output | standard input | PyPy 3 | Python | 2,200 | train_078.jsonl | 11b07351bc932b8eba66e1f7ba7309fc | 256 megabytes | ["2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9", "2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9"] | PASSED | import sys
from array import array # noqa: F401
from math import pi, sin, cos
from bisect import bisect_left
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, v = map(int, input().split())
v = float(v)
alpha = [float(input()) for _ in range(n)]
m = int(input())
wall = sorted(tuple(map(float, input().split())) for _ in range(m)) + [(1e9, 1e9)]
max_angle = pi / 4
eps = 1e-9
a = [0.0] * m + [max_angle + eps]
for i in range(m):
ng_angle, ok_angle = 0.0, max_angle + eps
for _ in range(50):
mid_angle = (ok_angle + ng_angle) / 2
t = wall[i][0] / (v * cos(mid_angle))
if (v * sin(mid_angle) * t - 9.8 * t**2 / 2) - eps <= wall[i][1]:
ng_angle = mid_angle
else:
ok_angle = mid_angle
a[i] = max(a[i], ng_angle)
a[i + 1] = max(a[i], a[i + 1])
ans = [''] * n
for i in range(n):
wi = bisect_left(a, alpha[i])
ok, ng = 0.0, 1e7
sin_a = sin(alpha[i])
for _ in range(50):
t = (ok + ng) / 2
if v * sin_a * t - 9.8 * t**2 / 2 >= 0.0:
ok = t
else:
ng = t
x = v * cos(alpha[i]) * ok
if x < wall[wi][0]:
ans[i] = f'{x:.8f} {0:.8f}'
else:
ok, ng = 0.0, 1e7
cos_a = cos(alpha[i])
for _ in range(50):
t = (ok + ng) / 2
if v * cos_a * t <= wall[wi][0]:
ok = t
else:
ng = t
y = v * sin_a * ok - 9.8 * ok**2 / 2
ans[i] = f'{wall[wi][0]:.8f} {y:.8f}'
print('\n'.join(ans))
| 1291737600 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["-1\n1\n11\n110\n190\n9012345679\n-87611785637\n1\n0"] | dbe12a665c374ce3745e20b4a8262eac | NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$. | The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps. | Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer — the answer to the $$$i$$$-th test case — the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$. | The first line of input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \leq x_0 \leq 10^{14}$$$) and $$$n$$$ ($$$0 \leq n \leq 10^{14}$$$) — the coordinate of the grasshopper's initial position and the number of jumps. | standard output | standard input | Python 3 | Python | 900 | train_108.jsonl | 9504ff934304acf48cf21891843eeb48 | 256 megabytes | ["9\n0 1\n0 2\n10 10\n10 99\n177 13\n10000000000 987654321\n-433494437 87178291199\n1 0\n-1 1"] | PASSED | t=int(input())
for _ in range(t):
x,times=map(int,input().split())
x=int(x)
times=int(times)
r=times%4
d=times//4*4+1
for i in range(r):
if x%2==0:
x-=d
else:
x+=d
d+=1
print(x) | 1635863700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds | ["2\n0\n13\n1\n4\n7\n0"] | 60190de3b5ae124d3cdca86fa931f1e0 | NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$. | This is the easy version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ is $$$$$$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$$$$$Here, $$$\lfloor \frac{x}{y} \rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \le p_i \le k$$$ for all $$$1 \le i \le n$$$. | For each test case, print a single integer — the minimum possible cost of an array $$$p$$$ satisfying the condition above. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \ldots \le a_n \le 3000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$. | standard output | standard input | PyPy 3-64 | Python | 1,700 | train_093.jsonl | 4fb78d1af667fb77e7e02376f4ccffcb | 64 megabytes | ["7\n\n5 2\n\n4 5 6 8 11\n\n5 12\n\n4 5 6 8 11\n\n3 1\n\n2 9 15\n\n7 3\n\n2 3 5 5 6 9 10\n\n6 56\n\n54 286 527 1436 2450 2681\n\n3 95\n\n16 340 2241\n\n2 2\n\n1 3"] | PASSED | import os
import sys
from io import BytesIO, IOBase
import sys
import threading
threading.stack_size(250 * 1024 * 1024)
sys.setrecursionlimit(5000)
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())
A = list(set(map(int, input().split())))
n = len(A)
a0 = min(A)
M = [-1] * (10**5 + 1)
for a in A:
p = k
start = 0
while p >= 1:
s = a//p
M[start] = max(M[start], s)
start = s + 1
r = a % p
p = p - ((p - r) + s)//(s + 1)
r = 10**20
m = -10**20
for i in range(a0 + 1):
# if M[i] >= 0:
m = max(m, M[i])
r = min(r, m - i)
print(r)
| 1658154900 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.