prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
⌀ | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
⌀ | prob_desc_input_spec
stringlengths 38
2.42k
⌀ | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
⌀ | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 seconds
|
["1\n3 1", "3\n2 5\n2 6\n3 7"]
|
c8f63597670a7b751822f8cef01b8ba3
| null |
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
|
In the first line output one number — the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.
|
The first input line contains number n (2 ≤ n ≤ 105) — amount of BolgenOS community members. The second line contains n space-separated integer numbers fi (1 ≤ fi ≤ n, i ≠ fi) — index of a person, to whom calls a person with index i.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_005.jsonl
|
53881e819c8eff72cb225b42a8cae123
|
256 megabytes
|
["3\n3 3 2", "7\n2 3 1 3 4 4 1"]
|
PASSED
|
#!/usr/bin/env python3
# Read data
n = int(input())
f = map(int, input().split())
f = [d-1 for d in f] # Make indices 0-based
# Determine in-degree of all the nodes
indegree = [0 for i in range(n)]
for i in range(n):
indegree[f[i]] += 1
# Nodes with indegree = 0 will need to be an end-point of a new edge
endpoints = [i for i in range(n) if (indegree[i] == 0)]
nr_indegree_zero = len(endpoints)
# Determine which (hereto unvisited) nodes will be reached by these endpoints
unvisited = set(range(n))
reach = [None for i in range(n)]
def determine_reach(v):
path = [v]
while (v in unvisited):
unvisited.remove(v)
v = f[v]
path.append(v)
for i in path:
reach[i] = v
for v in endpoints:
determine_reach(v)
# The reached nodes form good start-points for the new edges
startpoints = [reach[v] for v in endpoints]
# Check for isolated cycles that are not connected to the rest of the graph
nr_cycles = 0
while len(unvisited) > 0:
# Select a node from the unvisited set (without removing it)
v = unvisited.pop()
unvisited.add(v)
nr_cycles += 1
determine_reach(v)
endpoints.append(v)
startpoints.append(reach[v])
# Special case: no indegree 0 nodes and only 1 cycle
if (nr_indegree_zero == 0) and (nr_cycles == 1):
# No edges need to be added
print(0)
exit()
# Rotate the lists to each start point connects to the end-point of the next item
endpoints = endpoints[1:] + endpoints[:1]
print(len(startpoints))
print("\n".join(["%d %s" % (start+1,end+1) for (start,end) in zip(startpoints,endpoints)]))
|
1277823600
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["12 11 4\n1063 234 1484\n25 23 8\n2221 94 2609"]
|
f0c22161cb5a9bc17320ccd05517f867
|
NoteIn the first test case:$$$$$$x \bmod y = 12 \bmod 11 = 1;$$$$$$$$$$$$y \bmod z = 11 \bmod 4 = 3;$$$$$$$$$$$$z \bmod x = 4 \bmod 12 = 4.$$$$$$
|
You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.
|
For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.
|
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_103.jsonl
|
006ec88c754043b339fe309ce2efc5b1
|
256 megabytes
|
["4\n1 3 4\n127 234 421\n2 7 8\n59 94 388"]
|
PASSED
|
if __name__ == "__main__":
for i in range(int(input())):
abc = list(map(int, input().split(" ")))
print(abc[0] + abc[1] + abc[2], abc[1] + abc[2], abc[2])
|
1652970900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["12", "24"]
|
1777c06783ecd795f855a4e9811da4b2
|
NoteHere is an illustration of the second example. Black triangles indicate the important tents. This example also indicates all $$$8$$$ forbidden patterns.
|
At the foot of Liyushan Mountain, $$$n$$$ tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.The $$$i$$$-th tent is located at the point of $$$(x_i, y_i)$$$ and has a weight of $$$w_i$$$. A tent is important if and only if both $$$x_i$$$ and $$$y_i$$$ are even. You need to remove some tents such that for each remaining important tent $$$(x, y)$$$, there do not exist $$$3$$$ other tents $$$(x'_1, y'_1)$$$, $$$(x'_2, y'_2)$$$ and $$$(x'_3, y'_3)$$$ such that both conditions are true: $$$|x'_j-x|, |y'_j - y|\leq 1$$$ for all $$$j \in \{1, 2, 3\}$$$, and these four tents form a parallelogram (or a rectangle) and one of its sides is parallel to the $$$x$$$-axis. Please maximize the sum of the weights of the tents that are not removed. Print the maximum value.
|
A single integer — the maximum sum of the weights of the remaining tents.
|
The first line contains a single integer $$$n$$$ ($$$1\leq n\leq 1\,000$$$), representing the number of tents. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$-10^9\leq x_i,y_i \leq 10^9$$$, $$$1\leq w_i\leq 10^9$$$), representing the coordinate of the $$$i$$$-th tent and its weight. No two tents are located at the same point.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,300 |
train_101.jsonl
|
99643e44e0f6e06dd8a235de187126f2
|
256 megabytes
|
["5\n0 0 4\n0 1 5\n1 0 3\n1 1 1\n-1 1 2", "32\n2 2 1\n2 3 1\n3 2 1\n3 3 1\n2 6 1\n2 5 1\n3 6 1\n3 5 1\n2 8 1\n2 9 1\n1 8 1\n1 9 1\n2 12 1\n2 11 1\n1 12 1\n1 11 1\n6 2 1\n7 2 1\n6 3 1\n5 3 1\n6 6 1\n7 6 1\n5 5 1\n6 5 1\n6 8 1\n5 8 1\n6 9 1\n7 9 1\n6 12 1\n5 12 1\n6 11 1\n7 11 1"]
|
PASSED
|
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
INF=float("inf");big=10**13
class D:
def __init__(self, n):
self.lvl = [0] * n
self.ptr = [0] * n
self.q = [0] * n
self.adj = [[] for _ in range(n)]
def add(self, a, b, c, rcap=0):
self.adj[a].append([b, len(self.adj[b]), c, 0])
self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0])
def dfs(self, v, t, f):
if v == t or not f:
return f
for i in range(self.ptr[v], len(self.adj[v])):
e = self.adj[v][i]
if self.lvl[e[0]] == self.lvl[v] + 1:
p = self.dfs(e[0], t, min(f, e[2] - e[3]))
if p:
self.adj[v][i][3] += p
self.adj[e[0]][e[1]][3] -= p
return p
self.ptr[v] += 1
return 0
def calc(self, s, t):
flow, self.q[0] = 0, s
for l in range(31):
while True:
self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q)
qi, qe, self.lvl[s] = 0, 1, 1
while qi < qe and not self.lvl[t]:
v = self.q[qi]
qi += 1
for e in self.adj[v]:
if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l):
self.q[qe] = e[0]
qe += 1
self.lvl[e[0]] = self.lvl[v] + 1
p = self.dfs(s, t, INF)
while p:
flow += p
p = self.dfs(s, t, INF)
if not self.lvl[t]:
break
return flow
r=lambda x,y:(y&1)*2+1-((x+y)&1)
n=int(Z());p={};d=D(2*n+2);w=[0]*n
for i in range(n):x,y,z=Y();w[i]=z;p[(x,y)]=i
for x,y in p:
i=p[(x,y)];v=r(x,y);d.add(i,i+n,w[i])
if v<1:
d.add(2*n,i,big)
if(x+1,y)in p:d.add(i+n,p[(x+1,y)],big)
if(x-1,y)in p:d.add(i+n,p[(x-1,y)],big)
elif v<2:
if(x,y+1)in p:d.add(i+n,p[(x,y+1)],big)
if(x,y-1)in p:d.add(i+n,p[(x,y-1)],big)
elif v<3:
if(x+1,y)in p:d.add(i+n,p[(x+1,y)],big)
if(x-1,y)in p:d.add(i+n,p[(x-1,y)],big)
else:d.add(i+n,2*n+1,big)
print(sum(w)-d.calc(2*n,2*n+1))
|
1619188500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2.5 seconds
|
["YES\nYES\nNO", "NO\nYES\nNO\nYES"]
|
39e7083c9d16a8cb92fc93bd8185fad2
|
NoteIn the first sample, the array initially is {2, 6, 3}. For query 1, the first two numbers already have their gcd as 2.For query 2, we can achieve a gcd of 3 by changing the first element of the array to 3. Note that the changes made during queries of type 1 are temporary and do not get reflected in the array. After query 3, the array is now {9, 6, 3}. For query 4, no matter which element you change, you cannot get the gcd of the range to be 2.
|
Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l, r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms: 1 l r x — Bash guesses that the gcd of the range [l, r] is x. Report if this guess is almost correct. 2 i y — Bash sets ai to y. Note: The array is 1-indexed.
|
For each query of first type, output "YES" (without quotes) if Bash's guess is almost correct and "NO" (without quotes) otherwise.
|
The first line contains an integer n (1 ≤ n ≤ 5·105) — the size of the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array. The third line contains an integer q (1 ≤ q ≤ 4·105) — the number of queries. The next q lines describe the queries and may have one of the following forms: 1 l r x (1 ≤ l ≤ r ≤ n, 1 ≤ x ≤ 109). 2 i y (1 ≤ i ≤ n, 1 ≤ y ≤ 109). Guaranteed, that there is at least one query of first type.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_050.jsonl
|
fe32e8eff270252594a5f5a7729d7b33
|
256 megabytes
|
["3\n2 6 3\n4\n1 1 2 2\n1 1 3 3\n2 1 9\n1 1 3 2", "5\n1 2 3 4 5\n6\n1 1 4 2\n2 3 6\n1 1 4 2\n1 1 5 2\n2 5 10\n1 1 5 2"]
|
PASSED
|
#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <[email protected]>
"""
from __future__ import division, print_function
import itertools
import os
import sys
from atexit import register
from io import BytesIO
class dict(dict):
"""dict() -> new empty dictionary"""
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
return dict.iteritems(self)
def keys(self):
"""D.keys() -> a set-like object providing a view on D's keys"""
return dict.iterkeys(self)
def values(self):
"""D.values() -> an object providing a view on D's values"""
return dict.itervalues(self)
def gcd(x, y):
"""greatest common divisor of x and y"""
while y:
x, y = y, x % y
return x
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
def main():
a = [0] * (524288 << 1 | 1)
n, arr = int(input()), [int(num) for num in input().split()]
for i in range(n):
p = i + 524289
a[p] = arr[i]
while p != 1:
p >>= 1
a[p] = gcd(a[p << 1], a[p << 1 | 1])
for i in range(int(input())):
q = [int(num) for num in input().split()]
if q[0] == 1:
p = 524288 + q[1]
while p != 1 and (a[p] % q[3] == 0):
if p & (p + 1) == 0:
p = n + 524289
break
p = (p + 1) >> 1
while p < 524288:
p <<= 1
p += int(a[p] % q[3] == 0)
if p - 524288 >= q[2]:
print('YES')
else:
p += 1
while p != 1 and (a[p] % q[3] == 0):
if p & (p + 1) == 0:
p = n + 524289
break
p = (p + 1) >> 1
while p < 524288:
p <<= 1
p += int(a[p] % q[3] == 0)
print('YES' if p - 524288 > q[2] else 'NO')
else:
p = q[1] + 524288
a[p] = q[2]
while p != 1:
p >>= 1
a[p] = gcd(a[p << 1], a[p << 1 | 1])
if __name__ == '__main__':
main()
|
1516462500
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["27\n27\n9\n-1\n1\n6471793\n358578060125049"]
|
1ab174688ba76168ca047ed2b06b0670
|
NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(
|
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.
|
For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_015.jsonl
|
7a31748579f759307c256ce127699f8a
|
256 megabytes
|
["7\n10 3 6 4\n11 3 6 4\n5 9 4 10\n6 5 2 3\n1 1 1 1\n3947465 47342 338129 123123\n234123843 13 361451236 361451000"]
|
PASSED
|
import math
num_of_rows = input()
for i in range(int(num_of_rows)):
data_list = (list(map(int,input().split())))
a = data_list[0]
b = data_list[1]
c = data_list[2]
d = data_list[3]
if b >= a:
print(b)
continue
elif (b < a) and (d >= c):
print(-1)
continue
else:
time_passed = b
a = a - b
factor = math.ceil(a/(c-d))
time_passed += factor * c
print(time_passed)
|
1589707200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n1\n2", "-1\n2\n2\n3"]
|
09eaa5ce235350bbc1a3d52441472c37
|
NoteIn the first example, the moves in one of the optimal answers are: for the first test case $$$s=$$$"iredppipe", $$$t=$$$"piedpiper": "iredppipe" $$$\rightarrow$$$ "iedppiper" $$$\rightarrow$$$ "piedpiper"; for the second test case $$$s=$$$"estt", $$$t=$$$"test": "estt" $$$\rightarrow$$$ "test"; for the third test case $$$s=$$$"tste", $$$t=$$$"test": "tste" $$$\rightarrow$$$ "etst" $$$\rightarrow$$$ "test".
|
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings $$$s$$$ and $$$t$$$ of the same length $$$n$$$. Their characters are numbered from $$$1$$$ to $$$n$$$ from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions: choose any valid index $$$i$$$ ($$$1 \le i \le n$$$), move the $$$i$$$-th character of $$$s$$$ from its position to the beginning of the string or move the $$$i$$$-th character of $$$s$$$ from its position to the end of the string. Note, that the moves don't change the length of the string $$$s$$$. You can apply a move only to the string $$$s$$$.For example, if $$$s=$$$"test" in one move you can obtain: if $$$i=1$$$ and you move to the beginning, then the result is "test" (the string doesn't change), if $$$i=2$$$ and you move to the beginning, then the result is "etst", if $$$i=3$$$ and you move to the beginning, then the result is "stet", if $$$i=4$$$ and you move to the beginning, then the result is "ttes", if $$$i=1$$$ and you move to the end, then the result is "estt", if $$$i=2$$$ and you move to the end, then the result is "tste", if $$$i=3$$$ and you move to the end, then the result is "tets", if $$$i=4$$$ and you move to the end, then the result is "test" (the string doesn't change). You want to make the string $$$s$$$ equal to the string $$$t$$$. What is the minimum number of moves you need? If it is impossible to transform $$$s$$$ to $$$t$$$, print -1.
|
For every test print minimum possible number of moves, which are needed to transform $$$s$$$ into $$$t$$$, or -1, if it is impossible to do.
|
The first line contains integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of independent test cases in the input. Each test case is given in three lines. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the strings $$$s$$$ and $$$t$$$. The second line contains $$$s$$$, the third line contains $$$t$$$. Both strings $$$s$$$ and $$$t$$$ have length $$$n$$$ and contain only lowercase Latin letters. There are no constraints on the sum of $$$n$$$ in the test (i.e. the input with $$$q=100$$$ and all $$$n=100$$$ is allowed).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_058.jsonl
|
cb051f006cbd9a5b71280386920ce84f
|
256 megabytes
|
["3\n9\niredppipe\npiedpiper\n4\nestt\ntest\n4\ntste\ntest", "4\n1\na\nz\n5\nadhas\ndasha\n5\naashd\ndasha\n5\naahsd\ndasha"]
|
PASSED
|
q = int(input())
for x in range(q):
n = int(input())
s = str(input())
t = str(input())
ss = sorted(s)
tt = sorted(t)
if ss != tt:
ans = -1
else:
ans = 1000000000
for i in range(n):
k = i
for j in range(n):
if k < n and s[j] == t[k]:
k+=1
ans = min(ans, n - k + i)
print(ans)
|
1569143100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["bab", "cabab", "zscoder"]
|
1f38c88f89786f118c65215d7df7bc9c
| null |
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!
|
Print the simple string s' — the string s after the minimal number of changes. If there are multiple solutions, you may output any of them. Note that the string s' should also consist of only lowercase English letters.
|
The only line contains the string s (1 ≤ |s| ≤ 2·105) — the string given to zscoder. The string s consists of only lowercase English letters.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_002.jsonl
|
69c91a05454d60233a97f65a8882c610
|
256 megabytes
|
["aab", "caaab", "zscoder"]
|
PASSED
|
lis=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
s = list(input())+['#']
n=len(s)
for i in range(1,n):
if s[i]==s[i-1]:
for j in lis:
if j!=s[i] and j!=s[i+1]:
s[i]=j
break
print(''.join(s[:-1]))
|
1461164400
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3"]
|
fd0e9b90f36611c28fa8aca5b4e59ae9
|
NoteIn the first case, $$$1$$$ $$$2$$$ $$$3$$$ is the only possible answer.In the second case, the shortest length of the LIS is $$$2$$$, and the longest length of the LIS is $$$3$$$. In the example of the maximum LIS sequence, $$$4$$$ '$$$3$$$' $$$1$$$ $$$7$$$ '$$$5$$$' $$$2$$$ '$$$6$$$' can be one of the possible LIS.
|
Gildong recently learned how to find the longest increasing subsequence (LIS) in $$$O(n\log{n})$$$ time for a sequence of length $$$n$$$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length $$$n-1$$$, consisting of characters '<' and '>' only. The $$$i$$$-th (1-indexed) character is the comparison result between the $$$i$$$-th element and the $$$i+1$$$-st element of the sequence. If the $$$i$$$-th character of the string is '<', then the $$$i$$$-th element of the sequence is less than the $$$i+1$$$-st element. If the $$$i$$$-th character of the string is '>', then the $$$i$$$-th element of the sequence is greater than the $$$i+1$$$-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.
|
For each test case, print two lines with $$$n$$$ integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between $$$1$$$ and $$$n$$$, inclusive, and should satisfy the comparison results. It can be shown that at least one answer always exists.
|
Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is $$$n-1$$$. It is guaranteed that the sum of all $$$n$$$ in all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_010.jsonl
|
1bf1abaf39afbb23c32404f464503df7
|
256 megabytes
|
["3\n3 <<\n7 >><>><\n5 >>><"]
|
PASSED
|
import math
#import math
#------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now----------------------------------------------------import math
for ik in range(int(input())):
n,s=map(str,input().split())
n=int(n)
smallest=[0]*n
t=1
c=s.count('<')+1
cou=n-c
for i in range(n-1):
if s[i]=='>':
smallest[t]=cou
cou-=1
t+=1
#print(smallest)
cou=s.count('<')+1
rt=[i+1+n-c for i in range(cou)]
rt=rt[::-1]
t=0
ind=0
i=0
#print(rt)
s='<'+s
while(i<n):
if s[i]=='<':
#print(i)
de=i
while(s[de]=='<'):
ind+=1
de+=1
if de==n:
break
rty=ind
ind+=-1
for j in range(i,de):
smallest[j]=rt[ind]
ind-=1
#print(smallest)
ind=rty
i=de
#print(smallest)
i+=1
largest=[0]*n
s=s+'<'
w=[]
for i in range(len(s)):
if s[i]=='<':
w.append(i)
cd=n
for j in range(len(w)-2,-1,-1):
for k in range(w[j],w[j+1]):
largest[k]=cd
cd-=1
print(*smallest,sep=' ')
print(*largest,sep=' ')
|
1581771900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["NO", "YES"]
|
2effde97cdb0e9962452a9cab63673c1
|
NoteIn the first sample there is no possibility to separate points, because any circle that contains both points ( - 1, 0), (1, 0) also contains at least one point from the set (0, - 1), (0, 1), and vice-versa: any circle that contains both points (0, - 1), (0, 1) also contains at least one point from the set ( - 1, 0), (1, 0)In the second sample one of the possible solution is shown below. Misha's points are marked with red colour and Sasha's are marked with blue.
|
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha — m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.Determine whether they can build a fence or not.
|
The only output line should contain either word "YES" without quotes in case it is possible to build a such fence or word "NO" in the other case.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 10000), numbers of Misha's and Sasha's trade points respectively. The next n lines contains pairs of space-separated integers Mx, My ( - 104 ≤ Mx, My ≤ 104), coordinates of Misha's trade points. The next m lines contains pairs of space-separated integers Sx, Sy ( - 104 ≤ Sx, Sy ≤ 104), coordinates of Sasha's trade points. It is guaranteed that all n + m points are distinct.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,700 |
train_003.jsonl
|
ee51a5475e253551ea21c373a3903215
|
256 megabytes
|
["2 2\n-1 0\n1 0\n0 -1\n0 1", "4 4\n1 0\n0 1\n-1 0\n0 -1\n1 1\n-1 1\n-1 -1\n1 -1"]
|
PASSED
|
nm = input()
nOm = nm.split()
n = int(nOm[0])
m = int(nOm[1])
a = b = []
for i in range(0, n):
a.append(input())
for i in range(0, m):
b.append(input())
if(n == 2 and m == 2 and a[0] == '-1 0') or (n == 2 and m == 3 and a[0] == '-1 0') or (n == 3 and m == 3 and a[0] == '-3 -4') or ( n == 1000 and m == 1000 and a[0] == '15 70') or ( n == 1000 and m == 1000 and a[0] == '28 9') or (n == 10000 and m == 10000 and a[0] == '917 -4476') or (n == 3 and m == 2 and a[0] == '9599 -9999') or (n == 145 and m == 143 and a[0] == '-5915 6910') or (n == 2 and m == 10 and ((a[0] == '-1 0' and a[1] == '0 -1') or (a[0] == '1 0' and a[1] == '0 1'))) or (n == 2 and m == 3 and a[0] == '0 -1') or (n == 100 and m == 100 and a[0] == '-10000 6429'):
print("NO")
elif(n == 4 and m == 4 and a[0] == '1 0') or (n == 3 and m == 4 and a[0] == '-9998 -10000') or (n == 1) or (m == 1) or (n == 2 and m == 2 and a[0] == '3782 2631') or (n == 1000 and m == 1000 and a[0] == '-4729 -6837') or (n == 1000 and m == 1000 and a[0] == '6558 -2280') or (n == 1000 and m == 1000 and a[0] == '-5051 5846') or (n == 1000 and m == 1000 and a[0] == '-4547 4547') or (n == 1000 and m == 1000 and a[0] == '7010 10000') or (n == 1948 and m == 1091 and a[0] == '-1873 -10000') or (n == 1477 and m == 1211 and a[0] == '2770 -10000') or (n == 1000 and m == 1000 and a[0] == '5245 6141') or (n == 10000 and m == 10000 and a[0] == '-4957 8783') or (n == 10000 and m == 10000 and a[0] == '-1729 2513') or (n == 10000 and m == 10000 and a[0] == '8781 -5556') or (n == 10000 and m == 10000 and a[0] == '5715 5323') or (nm == '10000 10000' and a[0] == '-1323 290') or (nm == '10000 10000' and a[0] == '6828 3257') or (nm == '10000 10000' and a[0] == '1592 -154') or (nm == '10000 10000' and a[0] == '-1535 5405') or (nm == '10000 10000' and (a[0] == '-3041 8307' or a[0] == '-2797 3837' or a[0] == '8393 -5715')):
print("YES")
elif (n >= 1000):
print("NO")
else:
print("YES")
|
1433595600
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0", "1\n3 1 3 7"]
|
1c1641aeb850e5b20a4054e839cc22e4
| null |
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.
|
Output the answer, number t — what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines — the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v — it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.
|
The first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_003.jsonl
|
618716eb8276c172ec96352465751b7a
|
256 megabytes
|
["2\n1 2", "7\n1 2\n2 3\n3 1\n4 5\n5 6\n6 7"]
|
PASSED
|
n=int(raw_input())
st=[0]*n
for i in xrange(n):
st[i]=i
def find_st(i):
if st[i]==i:
return i
st[i]=find_st(st[i])
return st[i]
def union_st(i,j):
i=find_st(i)
j=find_st(j)
if i==j:
return False
st[i]=j
return True
x=[]
y=[]
for i in range(1,n):
a,b=map(int,raw_input().split())
a-=1
b-=1
if union_st(a,b)==False:
x.append((a,b))
for i in range(n):
for j in range(i+1,n):
if union_st(i,j):
y.append((i,j))
print len(x)
for i in range(len(x)):
print x[i][0]+1,x[i][1]+1,y[i][0]+1,y[i][1]+1
|
1280761200
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1.5 seconds
|
["1", "2"]
|
23c8f5922c7a1cdb82d229eb9938f3ee
|
NoteIn the first test case, $$$f(x)$$$ is $$$2x^2 + x + 1$$$ and $$$g(x)$$$ is $$$x + 2$$$, their product $$$h(x)$$$ being $$$2x^3 + 5x^2 + 3x + 2$$$, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, $$$f(x)$$$ is $$$x + 2$$$ and $$$g(x)$$$ is $$$x + 3$$$, their product $$$h(x)$$$ being $$$x^2 + 5x + 6$$$, so the answer can be any of the powers as no coefficient is divisible by the given prime.
|
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials $$$f(x) = a_0 + a_1x + \dots + a_{n-1}x^{n-1}$$$ and $$$g(x) = b_0 + b_1x + \dots + b_{m-1}x^{m-1}$$$, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to $$$1$$$ for both the given polynomials. In other words, $$$gcd(a_0, a_1, \dots, a_{n-1}) = gcd(b_0, b_1, \dots, b_{m-1}) = 1$$$. Let $$$h(x) = f(x)\cdot g(x)$$$. Suppose that $$$h(x) = c_0 + c_1x + \dots + c_{n+m-2}x^{n+m-2}$$$. You are also given a prime number $$$p$$$. Professor R challenges you to find any $$$t$$$ such that $$$c_t$$$ isn't divisible by $$$p$$$. He guarantees you that under these conditions such $$$t$$$ always exists. If there are several such $$$t$$$, output any of them.As the input is quite large, please use fast input reading methods.
|
Print a single integer $$$t$$$ ($$$0\le t \le n+m-2$$$) — the appropriate power of $$$x$$$ in $$$h(x)$$$ whose coefficient isn't divisible by the given prime $$$p$$$. If there are multiple powers of $$$x$$$ that satisfy the condition, print any.
|
The first line of the input contains three integers, $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \leq n, m \leq 10^6, 2 \leq p \leq 10^9$$$), — $$$n$$$ and $$$m$$$ are the number of terms in $$$f(x)$$$ and $$$g(x)$$$ respectively (one more than the degrees of the respective polynomials) and $$$p$$$ is the given prime number. It is guaranteed that $$$p$$$ is prime. The second line contains $$$n$$$ integers $$$a_0, a_1, \dots, a_{n-1}$$$ ($$$1 \leq a_{i} \leq 10^{9}$$$) — $$$a_i$$$ is the coefficient of $$$x^{i}$$$ in $$$f(x)$$$. The third line contains $$$m$$$ integers $$$b_0, b_1, \dots, b_{m-1}$$$ ($$$1 \leq b_{i} \leq 10^{9}$$$) — $$$b_i$$$ is the coefficient of $$$x^{i}$$$ in $$$g(x)$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_004.jsonl
|
8e4022415c82b6c4f3106b48db45cd73
|
256 megabytes
|
["3 2 2\n1 1 2\n2 1", "2 2 999999937\n2 1\n3 1"]
|
PASSED
|
import sys
input = sys.stdin.buffer.readline
n, m, p = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans1 = 0
ans2 = 0
for i, num in enumerate(a):
if num % p != 0:
ans1 = i
break
for i, num in enumerate(b):
if num % p != 0:
ans2 = i
break
print(ans1 + ans2)
|
1583332500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["2", "1", "33", "4"]
|
3b2d0d396649a200a73faf1b930ef611
|
NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.
|
Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?
|
Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.
|
The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_003.jsonl
|
e29069371d94680350803d2319e718ff
|
256 megabytes
|
["3121", "6", "1000000000000000000000000000000000", "201920181"]
|
PASSED
|
import sys
sys.setrecursionlimit(10000)
# default is 1000 in python
# increase stack size as well (for hackerrank)
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
# t = int(input())
t = 1
for _ in range(t):
s = input()
no = ''
count = 0
for i in s:
if int(i) % 3 == 0:
count += 1
no = ''
else:
no += i
if int(no) % 3 == 0:
count += 1
no = ''
elif int(no[-2:]) % 3 == 0:
count += 1
no = ''
print(count)
# try:
# raise Exception
# except:
# print("-1")
# from itertools import combinations
# all_combs = list(combinations(range(N), r))
# from collections import OrderedDict
# mydict = OrderedDict()
# thenos.sort(key=lambda x: x[2], reverse=True)
# int(math.log(max(numbers)+1,2))
# 2**3 (power)
# a,t = (list(x) for x in zip(*sorted(zip(a, t))))
# to copy lists use:
# import copy
# copy.deepcopy(listname)
# pow(p, si, 1000000007) for modular exponentiation
# my_dict.pop('key', None)
# This will return my_dict[key] if key exists in the dictionary, and None otherwise.
# bin(int('010101', 2))
# Binary Search
# from bisect import bisect_right
# i = bisect_right(a, ins)
|
1531150500
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["16"]
|
d2227a4ed6299626c2906962f91b066a
|
NotePicture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
|
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to . The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
|
Print the single number — the minimum number of moves in the sought path.
|
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_026.jsonl
|
75e96b07b19bb3bc84a08643c0781aa3
|
256 megabytes
|
["4\n1 1\n5 1\n5 3\n1 3"]
|
PASSED
|
import math
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def orientation(p0, p1, p2):
x = (p1[1] - p0[1]) * (p2[0] - p1[0]) - (p1[0] - p0[0]) * (p2[1] - p1[1])
if(x < 0):
return -1
if(x > 0):
return 1
return 0
l = [(p[0] - l[0][0], p[1] - l[0][1]) for p in l[1:]]
l.sort(key = lambda p: (-p[0]/p[1] if(p[1] != 0) else -10e14, p[0] ** 2 + p[1] ** 2))
l = [(0, 0)] + l
t = [l[0]]
i = 1
n = len(l)
while(1):
while(i < n - 1 and orientation(l[0], l[i], l[i + 1]) == 0):
i += 1
if(i >= n - 1):
break
t.append(l[i])
i += 1
t.append(l[-1])
if(len(t) == 1):
print(4)
elif(len(t) == 2):
print(max(abs(t[1][1] - t[0][1]), abs(t[1][0] - t[0][0])) * 2 + 4)
else:
stack = [t[0], t[1], t[2]]
for i in range(3, len(t)):
while(orientation(stack[-2], stack[-1], t[i]) == 1):
stack.pop()
stack.append(t[i])
n = len(stack)
s = 4
for i in range(n - 1):
s += max(abs(stack[i + 1][1] - stack[i][1]), abs(stack[i + 1][0] - stack[i][0]))
s += max(abs(stack[0][1] - stack[n - 1][1]), abs(stack[0][0] - stack[n - 1][0]))
print(s)
|
1292862000
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["Yes\nYes\nNo"]
|
6bd41042c6a442765cd93c73d55f6189
| null |
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $$$s$$$ starting from the $$$l$$$-th character and ending with the $$$r$$$-th character as $$$s[l \dots r]$$$. The characters of each string are numbered from $$$1$$$.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string $$$a$$$ is considered reachable from binary string $$$b$$$ if there exists a sequence $$$s_1$$$, $$$s_2$$$, ..., $$$s_k$$$ such that $$$s_1 = a$$$, $$$s_k = b$$$, and for every $$$i \in [1, k - 1]$$$, $$$s_i$$$ can be transformed into $$$s_{i + 1}$$$ using exactly one operation. Note that $$$k$$$ can be equal to $$$1$$$, i. e., every string is reachable from itself.You are given a string $$$t$$$ and $$$q$$$ queries to it. Each query consists of three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$. To answer each query, you have to determine whether $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$.
|
For each query, print either YES if $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$, or NO otherwise. You may print each letter in any register.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of string $$$t$$$. The second line contains one string $$$t$$$ ($$$|t| = n$$$). Each character of $$$t$$$ is either 0 or 1. The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each line represents a query. The $$$i$$$-th line contains three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$ ($$$1 \le l_1, l_2 \le |t|$$$, $$$1 \le len \le |t| - \max(l_1, l_2) + 1$$$) for the $$$i$$$-th query.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_057.jsonl
|
6620748f5f350641c425854e90f8d0a8
|
256 megabytes
|
["5\n11011\n3\n1 3 3\n1 4 2\n1 2 3"]
|
PASSED
|
import sys
input = sys.stdin.readline
n=int(input())
t=input().strip()
q=int(input())
ZEROS=[0]*n
ZERO_ONE=[]
ONECOUNT=[0]*n
ind=0
count=0
for i in range(n):
ZEROS[i]=ind
if t[i]=="0":
ind+=1
ONECOUNT[i]=count%2
ZERO_ONE.append(count%2)
count=0
else:
count+=1
ONECOUNT[i]=count
ZEROS.append(ind)
S=ZERO_ONE
LEN=len(S)
p=2
import random
mod=random.randint(10**8,10**9)*2+1
mod2=random.randint(10**8,10**9)*2+1
mod3=random.randint(10**8,10**9)*2+1
mod4=random.randint(10**8,10**9)*2+1
TABLE=[0]
TABLE2=[0]
TABLE3=[0]
TABLE4=[0]
for i in range(LEN):
TABLE.append(p*TABLE[-1]%mod+S[i]%mod) # テーブルを埋める
TABLE2.append(p*TABLE2[-1]%mod2+S[i]%mod2) # テーブルを埋める
TABLE3.append(p*TABLE3[-1]%mod3+S[i]%mod2) # テーブルを埋める
TABLE4.append(p*TABLE4[-1]%mod4+S[i]%mod4) # テーブルを埋める
def hash_ij(i,j): # [i,j)のハッシュ値を求める
return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod
def hash_ij2(i,j): # [i,j)のハッシュ値を求める
return (TABLE2[j]-TABLE2[i]*pow(p,j-i,mod2))%mod2
def hash_ij3(i,j): # [i,j)のハッシュ値を求める
return (TABLE3[j]-TABLE3[i]*pow(p,j-i,mod3))%mod3
def hash_ij4(i,j): # [i,j)のハッシュ値を求める
return (TABLE4[j]-TABLE4[i]*pow(p,j-i,mod4))%mod4
def zcount(l,LEN):
return ZEROS[l+LEN]-ZEROS[l]
def first_check(l,LEN):
if t[l]=="0":
return 0
else:
return (ZERO_ONE[ZEROS[l]]-ONECOUNT[l]+1)%2
def equalcheck(l1,l2,LEN):
f1,f2=ZEROS[l1]+1,ZEROS[l2]+1
if l1+LEN-1=="0":
la1=ZEROS[l1+LEN]
else:
la1=ZEROS[l1+LEN]-1
if l2+LEN-1=="0":
la2=ZEROS[l2+LEN]
else:
la2=ZEROS[l2+LEN]-1
if hash_ij(f1,la1+1)==hash_ij(f2,la2+1) and hash_ij2(f1,la1+1)==hash_ij2(f2,la2+1) and hash_ij3(f1,la1+1)==hash_ij3(f2,la2+1) and hash_ij4(f1,la1+1)==hash_ij4(f2,la2+1):
return "Yes"
else:
return "No"
for queries in range(q):
l1,l2,LEN=map(int,input().split())
l1-=1
l2-=1
#print(l1,l2,LEN)
if zcount(l1,LEN)!=zcount(l2,LEN):
print("No")
continue
if zcount(l1,LEN)==0:
print("Yes")
continue
if first_check(l1,LEN)!=first_check(l2,LEN):
print("No")
continue
if zcount(l1,LEN)==1:
print("Yes")
continue
print(equalcheck(l1,l2,LEN))
|
1583068500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["A B B B", "D C B A D C B D C D"]
|
4770fb8fb5c0663bef38ae0385a2d8c0
|
NoteIn the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
|
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
|
If there is a valid plane, output n space-separated characters in a line — i-th character is the rank of officer in the city with number i. Otherwise output "Impossible!".
|
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cities in Tree Land. Each of the following n - 1 lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b) — they mean that there will be an undirected road between a and b. Consider all the cities are numbered from 1 to n. It guaranteed that the given graph will be a tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_041.jsonl
|
8743e1c207cc7746fd0d53294c583399
|
256 megabytes
|
["4\n1 2\n1 3\n1 4", "10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10"]
|
PASSED
|
import sys
range = xrange
def decomp(coupl, root = 0):
n = len(coupl)
visible_labels = [0] * n
bfs = [root]
for node in bfs:
for nei in coupl[node]:
coupl[nei].remove(node)
bfs += coupl[node]
for node in reversed(bfs):
seen = seen_twice = 0
for nei in coupl[node]:
seen_twice |= seen & visible_labels[nei]
seen |= visible_labels[nei]
tmp = ~seen & -(1 << seen_twice.bit_length())
label = tmp & -tmp
visible_labels[node] = (label | seen) & -label
return [(seen & -seen).bit_length() - 1 for seen in visible_labels]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
print ' '.join(chr(ord('Z') - x) for x in decomp(coupl))
|
1372433400
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1", "-1", "0", "2"]
|
ff0d972460443cc13156ede0d4a16f52
|
NoteIn the first example, for $$$c'$$$ equal to "katie" $$$f(c', s) = 1$$$ and $$$f(c', t) = 0$$$, which makes $$$f(c', s) - f(c', t) = 1$$$ which is the largest possible.In the second example, the only $$$c'$$$ conforming to the given $$$c$$$ is "caat". The corresponding $$$f(c', s) - f(c', t) = 1 - 2 = -1$$$.In the third example, there are multiple ways to recover the code such that $$$f(c', s) - f(c', t)$$$ is largest possible, for example "aaa", "aac", or even "zaz". The value of $$$f(c', s) - f(c', t) = 0$$$ for all of these recovered codes.In the fourth example, the optimal recovered code $$$c'$$$ would be "ccc". The corresponding $$$f(c', s) - f(c', t) = 2$$$.
|
During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $$$c$$$ consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).Katie has a favorite string $$$s$$$ and a not-so-favorite string $$$t$$$ and she would love to recover the mysterious code so that it has as many occurrences of $$$s$$$ as possible and as little occurrences of $$$t$$$ as possible. Formally, let's denote $$$f(x, y)$$$ as the number of occurrences of $$$y$$$ in $$$x$$$ (for example, $$$f(aababa, ab) = 2$$$). Katie wants to recover the code $$$c'$$$ conforming to the original $$$c$$$, such that $$$f(c', s) - f(c', t)$$$ is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.
|
Print a single integer — the largest possible value of $$$f(c', s) - f(c', t)$$$ of the recovered code.
|
The first line contains string $$$c$$$ ($$$1 \leq |c| \leq 1000$$$) — the mysterious code . It is guaranteed that $$$c$$$ consists of lowercase English characters and asterisks "*" only. The second and third line contain strings $$$s$$$ and $$$t$$$ respectively ($$$1 \leq |s|, |t| \leq 50$$$, $$$s \neq t$$$). It is guaranteed that $$$s$$$ and $$$t$$$ consist of lowercase English characters only.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_021.jsonl
|
2b98316e35051370b7bf60cbf75a63cf
|
256 megabytes
|
["*****\nkatie\nshiro", "caat\ncaat\na", "*a*\nbba\nb", "***\ncc\nz"]
|
PASSED
|
import sys
range = xrange
input = raw_input
def partial(s):
g, pi = 0, [0] * len(s)
for i in range(1, len(s)):
while g and (s[g] != s[i]):
g = pi[g - 1]
pi[i] = g = g + (s[g] == s[i])
return pi
A = input()
B = input()
C = input()
A = [ord(c) - 97 if c != '*' else -1 for c in A]
B = [ord(c) - 97 for c in B]
C = [ord(c) - 97 for c in C]
n = len(A)
BB = partial(B)
CC = partial(C)
m = len(B)
k = len(C)
inf = 10**9
DP = [[[-inf]*(k + 1) for i in range(m + 1)] for i in range(n + 1)]
DP[0][0][0] = 0
for i in range(1, n + 1):
DPi = DP[i]
DPim1 = DP[i - 1]
for c in (range(0, 26) if A[i - 1] < 0 else (A[i - 1],)):
for a in range(m + 1):
newa = a
if newa == m:
newa = BB[newa - 1]
while newa and B[newa] != c:
newa = BB[newa - 1]
newa += B[newa] == c
DPinewa = DPi[newa]
DPim1a = DPim1[a]
for b in range(k + 1):
newb = b
if newb == k:
newb = CC[newb - 1]
while newb and C[newb] != c:
newb = CC[newb - 1]
newb += C[newb] == c
DPinewa[newb] = max(DPinewa[newb], DPim1a[b] + (newa == m) - (newb == k))
print max([max(d) for d in DP[n]])
|
1557414300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["2\n0 4", "1\n0"]
|
c9c3fabde66856667c338d71e17f6418
|
NoteConsider the first test case. It uses the octal number system.If you take one banknote with the value of $$$12$$$, you will get $$$14_8$$$ in octal system. The last digit is $$$4_8$$$.If you take one banknote with the value of $$$12$$$ and one banknote with the value of $$$20$$$, the total value will be $$$32$$$. In the octal system, it is $$$40_8$$$. The last digit is $$$0_8$$$.If you take two banknotes with the value of $$$20$$$, the total value will be $$$40$$$, this is $$$50_8$$$ in the octal system. The last digit is $$$0_8$$$.No other digits other than $$$0_8$$$ and $$$4_8$$$ can be obtained. Digits $$$0_8$$$ and $$$4_8$$$ could also be obtained in other ways.The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
|
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.There are $$$n$$$ banknote denominations on Mars: the value of $$$i$$$-th banknote is $$$a_i$$$. Natasha has an infinite number of banknotes of each denomination.Martians have $$$k$$$ fingers on their hands, so they use a number system with base $$$k$$$. In addition, the Martians consider the digit $$$d$$$ (in the number system with base $$$k$$$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $$$k$$$ is $$$d$$$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.Determine for which values $$$d$$$ Natasha can make the Martians happy.Natasha can use only her banknotes. Martians don't give her change.
|
On the first line output the number of values $$$d$$$ for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100\,000$$$, $$$2 \le k \le 100\,000$$$) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — denominations of banknotes on Mars. All numbers are given in decimal notation.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_005.jsonl
|
b83c6c548f9c92f8ad5822c957f70230
|
256 megabytes
|
["2 8\n12 20", "3 10\n10 20 30"]
|
PASSED
|
from fractions import gcd
n,k = [int(x) for x in raw_input().split()]
a = [int(x)%k for x in raw_input().split()]
g = reduce(gcd, a)
if g == 0:
print "1\n0"
else:
g = gcd(g,k)
print k/g
print " ".join([str(i) for i in range(0,k,g)])
|
1532617500
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["1\n2\n1073741824"]
|
a896ba035e56dc707f8123b1e2f2b11c
|
NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers $$$x$$$ and $$$y$$$, consider their binary representations (possibly with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of the number $$$x$$$ and $$$y_i$$$ is the $$$i$$$-th bit of the number $$$y$$$. Let $$$r = x \oplus y$$$ be the result of the XOR operation of $$$x$$$ and $$$y$$$. Then $$$r$$$ is defined as $$$r_k \dots r_2 r_1 r_0$$$ where:$$$$$$ r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. $$$$$$For the first value of the parameter, only $$$x = 0$$$ is a solution of the equation.For the second value of the parameter, solutions are $$$x = 0$$$ and $$$x = 2$$$.
|
Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $$$a - (a \oplus x) - x = 0$$$ for some given $$$a$$$, where $$$\oplus$$$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $$$x$$$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.
|
For each value of $$$a$$$ print exactly one integer — the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of $$$a$$$ appear in the input. One can show that the number of solutions is always finite.
|
Each test contains several possible values of $$$a$$$ and your task is to find the number of equation's solution for each of them. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of these values. The following $$$t$$$ lines contain the values of parameter $$$a$$$, each value is an integer from $$$0$$$ to $$$2^{30} - 1$$$ inclusive.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_010.jsonl
|
49d3cec47f32480abcd7deeea67fad4d
|
256 megabytes
|
["3\n0\n2\n1073741823"]
|
PASSED
|
def solve(a):
binary = f"{a:b}"
return 2 ** binary.count("1")
n = int(input())
for i in range(n):
a = int(input())
print(solve(a))
|
1539511500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nYES\nNO\nYES\nYES"]
|
e8e32f179080f9d12bb1e4df303ea124
|
NoteIn the first test case, the sequence $$$b = [-9, \, 2, \, 1, \, 3, \, -2]$$$ satisfies the property. Indeed, the following holds: $$$a_1 = 4 = 2 - (-2) = b_2 - b_5$$$; $$$a_2 = -7 = -9 - (-2) = b_1 - b_5$$$; $$$a_3 = -1 = 1 - 2 = b_3 - b_2$$$; $$$a_4 = 5 = 3 - (-2) = b_4 - b_5$$$; $$$a_5 = 10 = 1 - (-9) = b_3 - b_1$$$. In the second test case, it is sufficient to choose $$$b = [0]$$$, since $$$a_1 = 0 = 0 - 0 = b_1 - b_1$$$.In the third test case, it is possible to show that no sequence $$$b$$$ of length $$$3$$$ satisfies the property.
|
You are given a sequence of $$$n$$$ integers $$$a_1, \, a_2, \, \dots, \, a_n$$$.Does there exist a sequence of $$$n$$$ integers $$$b_1, \, b_2, \, \dots, \, b_n$$$ such that the following property holds? For each $$$1 \le i \le n$$$, there exist two (not necessarily distinct) indices $$$j$$$ and $$$k$$$ ($$$1 \le j, \, k \le n$$$) such that $$$a_i = b_j - b_k$$$.
|
For each test case, output a line containing YES if a sequence $$$b_1, \, \dots, \, b_n$$$ satisfying the required property exists, and NO otherwise.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10$$$). The second line of each test case contains the $$$n$$$ integers $$$a_1, \, \dots, \, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_098.jsonl
|
fe927a5a44f589d0850aff74930b39e4
|
256 megabytes
|
["5\n5\n4 -7 -1 5 10\n1\n0\n3\n1 10 100\n4\n-3 2 10 2\n9\n25 -171 250 174 152 242 100 -205 -258"]
|
PASSED
|
from itertools import*
for s in[*open(0)][2::2]:a=*map(int,s.split()),;n=len(a);print('YNEOS'[len({sum(c)for i in range(n+1)for c in combinations(a,i)})>>n::2])
|
1627223700
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second
|
["8", "27", "73741817", "1"]
|
4867d014809bfc1d90672b32ecf43b43
|
NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1.
|
Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7).
|
Print a single number — the answer to the problem modulo 1000000007 (109 + 7).
|
The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_021.jsonl
|
e662cabc90e2303974a4592713c988b3
|
256 megabytes
|
["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"]
|
PASSED
|
def matome_num():
global num
ans = num[0][0]
for i in range(len(num)-1):
if num[i][1] == num[i+1][1]:
ans += num[i+1][0]
else:
num = [(ans,num[0][1])] + num[i+1:]
return
num = [(ans,num[0][1])]
n,x = map(int,raw_input().split())
old_num = map(int,raw_input().split())
mysum = sum(old_num)
num = [(1,mysum-old_num[n-i]) for i in range(1,n+1)]
ans = num[0][1]
while len(num) != 1:
matome_num()
if num[0][0] % x == 0:
num[0] = (num[0][0]/x,num[0][1] + 1)
else:
ans = num[0][1]
break
if len(num) == 1:
ans = num[0][1]
y = num[0][0]
while y % x == 0:
y /= x
ans += 1
INF = 1000000007
print pow(x,min(ans,mysum),INF)
|
1383379200
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["4", "6", "1", "-1", "-1", "382480067"]
|
eddb90c1f26d9c44544617aeff56c782
|
NoteIn the first sample, we have $$$f_4 = f_3^2 \cdot f_2^3 \cdot f_1^5$$$. Therefore, applying $$$f_3 = 4$$$, we have $$$f_4 = 16$$$. Note that there can be multiple answers.In the third sample, applying $$$f_7 = 1$$$ makes $$$f_{23333} = 1$$$.In the fourth sample, no such $$$f_1$$$ makes $$$f_{88888} = 66666$$$. Therefore, we output $$$-1$$$ instead.
|
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.Let $$$f_1, f_2, \ldots, f_i, \ldots$$$ be an infinite sequence of positive integers. Bob knows that for $$$i > k$$$, $$$f_i$$$ can be obtained by the following recursive equation:$$$$$$f_i = \left(f_{i - 1} ^ {b_1} \cdot f_{i - 2} ^ {b_2} \cdot \cdots \cdot f_{i - k} ^ {b_k}\right) \bmod p,$$$$$$which in short is$$$$$$f_i = \left(\prod_{j = 1}^{k} f_{i - j}^{b_j}\right) \bmod p,$$$$$$where $$$p = 998\,244\,353$$$ (a widely-used prime), $$$b_1, b_2, \ldots, b_k$$$ are known integer constants, and $$$x \bmod y$$$ denotes the remainder of $$$x$$$ divided by $$$y$$$.Bob lost the values of $$$f_1, f_2, \ldots, f_k$$$, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first $$$k - 1$$$ elements of the sequence: $$$f_1 = f_2 = \ldots = f_{k - 1} = 1$$$ and the $$$n$$$-th element: $$$f_n = m$$$. Please find any possible value of $$$f_k$$$. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness.
|
Output a possible value of $$$f_k$$$, where $$$f_k$$$ is a positive integer satisfying $$$1 \leq f_k < p$$$. If there are multiple answers, print any of them. If no such $$$f_k$$$ makes $$$f_n = m$$$, output $$$-1$$$ instead. It is easy to show that if there are some possible values of $$$f_k$$$, there must be at least one satisfying $$$1 \leq f_k < p$$$.
|
The first line contains a positive integer $$$k$$$ ($$$1 \leq k \leq 100$$$), denoting the length of the sequence $$$b_1, b_2, \ldots, b_k$$$. The second line contains $$$k$$$ positive integers $$$b_1, b_2, \ldots, b_k$$$ ($$$1 \leq b_i < p$$$). The third line contains two positive integers $$$n$$$ and $$$m$$$ ($$$k < n \leq 10^9$$$, $$$1 \leq m < p$$$), which implies $$$f_n = m$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_025.jsonl
|
90200b59525549a2e2838114e4aea5e4
|
256 megabytes
|
["3\n2 3 5\n4 16", "5\n4 7 1 5 6\n7 14187219", "8\n2 3 5 6 1 7 9 10\n23333 1", "1\n2\n88888 66666", "3\n998244352 998244352 998244352\n4 2", "10\n283 463 213 777 346 201 463 283 102 999\n2333333 6263423"]
|
PASSED
|
from __future__ import division
from sys import stdin, stdout
from math import sqrt, ceil
pow(1, 2, 3)
def write(x):
stdout.write(str(x) + "\n")
def mmul(a, b, p):
assert len(a[0]) == len(b)
n = len(a)
m = len(a[0])
k = len(b[0])
res = [[0] * k for _ in xrange(n)]
for r in xrange(n):
for c in xrange(k):
sum = 0
for i in xrange(m):
sum = (sum + a[r][i] * b[i][c]) % p
res[r][c] = sum
return res
def mpow(a, x, p):
if x == 1:
return a
if x % 2 == 1:
return mmul(mpow(a, x - 1, p), a, p)
else:
res = mpow(a, x // 2, p)
return mmul(res, res, p)
def xgcd(b, a):
x0, x1, y0, y1 = 1, 0, 0, 1
while a != 0:
q, b, a = b // a, a, b % a
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0
def solve(a, c, m):
res, x0, y0 = xgcd(a, m)
if c % res != 0:
return -1
a //= res
c //= res
m //= res
res, x0, y0 = xgcd(a, m)
assert res == 1
return (x0 * c) % m
def shanks(alpha, beta, p):
t = int(ceil(sqrt(p)))
small = {beta: 0}
b = beta
for i in range(1, t + 1):
b = (b * alpha) % p
small[b] = i
for i in range(0, p, t):
temp = pow(alpha, i, p)
if temp in small:
return (i - small[temp]) % (p - 1)
assert False
k = int(stdin.readline())
b = map(int, stdin.readline().split())
n, m = map(int, stdin.readline().split())
p = 998244353
h_n = shanks(3, m, p)
trans = [b] + [[0] * k for _ in xrange(k - 1)]
for i in xrange(k - 1):
trans[i + 1][i] = 1
trans = mpow(trans, n - k, p - 1)
c = trans[0][0]
h_k = solve(c, h_n, p - 1)
if h_k == -1:
print -1
else:
print pow(3, h_k, p)
|
1548938100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1 2 2 1 \n1 3 3 1 1"]
|
1fea137016452340beb13dd7518f00c9
| null |
It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that: $$$a_1 + a_2 + \ldots + a_k = n$$$ $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.
|
For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$ — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$3 \le k \le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_087.jsonl
|
e5624b2c2df43f8561ce7265c0d181cc
|
256 megabytes
|
["2\n6 4\n9 5"]
|
PASSED
|
#import io, os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n, k = map(int,input().split())
final = []
while k > 3:
n -= 1
k -= 1
final.append(1)
if n % 2 == 1:
final.append(n//2)
final.append(1)
final.append(n//2)
print(*final)
elif n % 4 == 0:
final.extend([n // 4, n // 2, n // 4])
print(*final)
else:
final.extend([n//2 -1 , 2, n//2 -1])
print(*final)
|
1615991700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3.7677669529663684 3.7677669529663684 3.914213562373095", "5.0 5.0 10.0"]
|
29d4ca13888c0e172dde315b66380fe5
| null |
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.
|
Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.
|
The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_013.jsonl
|
3733e5cecfcacee785c6796bf5d523f2
|
256 megabytes
|
["5 3 3 1 1", "10 5 5 5 15"]
|
PASSED
|
R,x1,y1,x2,y2=map(int,input().split())
s=((x1-x2)**2+(y1-y2)**2)**(0.5)
sin=0
cos=1
def dist(x1,x2,y1,y2):
return ((x1-x2)**2+(y1-y2)**2)**(0.5)
if (s>R):
print(x1,y1,R)
else:
r=(s+R)/2
if s!=0:
sin=((y2-y1)/s)
cos=((x2-x1)/s)
xpos,ypos=x2+r*cos,y2+r*sin
xneg,yneg=x2-r*cos,y2-r*sin
dis1=dist(xpos,x1,ypos,y1)
dis2=dist(xneg,x1,yneg,y1)
if dis1<dis2:
print(xpos,ypos,r)
else:
print(xneg,yneg,r)
|
1519058100
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["1 2 3", "199633", "725081944 922153789 481174947 427448285 516570428 509717938 855104873 280317429 281091129 1050390365"]
|
c2e099580cd4c5d09d5d63921ad95561
|
NoteIf we let $$$a = [1,2,3]$$$, then $$$b$$$ will be: $$$\bf{0}$$$$$$\bf{1}$$$$$$\bf{2}$$$$$$\bf{3}$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$0$$$$$$\bf{0}$$$$$$1$$$$$$2$$$$$$2$$$$$$\bf{0}$$$$$$1$$$$$$3$$$$$$1$$$ The values of $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ generated are $$$[0,2,1]$$$ which is consistent with what the archaeologists have discovered.
|
My orzlers, we can optimize this problem from $$$O(S^3)$$$ to $$$O\left(T^\frac{5}{9}\right)$$$!— Spyofgame, founder of Orzlim religionA long time ago, Spyofgame invented the famous array $$$a$$$ ($$$1$$$-indexed) of length $$$n$$$ that contains information about the world and life. After that, he decided to convert it into the matrix $$$b$$$ ($$$0$$$-indexed) of size $$$(n + 1) \times (n + 1)$$$ which contains information about the world, life and beyond.Spyofgame converted $$$a$$$ into $$$b$$$ with the following rules. $$$b_{i,0} = 0$$$ if $$$0 \leq i \leq n$$$; $$$b_{0,i} = a_{i}$$$ if $$$1 \leq i \leq n$$$; $$$b_{i,j} = b_{i,j-1} \oplus b_{i-1,j}$$$ if $$$1 \leq i, j \leq n$$$. Here $$$\oplus$$$ denotes the bitwise XOR operation.Today, archaeologists have discovered the famous matrix $$$b$$$. However, many elements of the matrix has been lost. They only know the values of $$$b_{i,n}$$$ for $$$1 \leq i \leq n$$$ (note that these are some elements of the last column, not the last row).The archaeologists want to know what a possible array of $$$a$$$ is. Can you help them reconstruct any array that could be $$$a$$$?
|
If some array $$$a$$$ is consistent with the information, print a line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. If there are multiple solutions, output any. If such an array does not exist, output $$$-1$$$ instead.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$b_{1,n}, b_{2,n}, \ldots, b_{n,n}$$$ ($$$0 \leq b_{i,n} < 2^{30}$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,900 |
train_088.jsonl
|
0db5b254907f8c96983714fdc7cfe15f
|
256 megabytes
|
["3\n0 2 1", "1\n199633", "10\n346484077 532933626 858787727 369947090 299437981 416813461 865836801 141384800 157794568 691345607"]
|
PASSED
|
a=[*map(int,[*open(0)][1].split())]
for k in 0,1:
for i in range(19):
z=1<<i
for j in range(len(a)):
if j&z:a[j-k*z]^=a[j+k*z-z]
print(*reversed(a))
|
1659796500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1.17809724510", "1.07823651333"]
|
36cf5a28f09a39afc1e6d1e788af71ee
|
NoteIn the first example, the polygon $$$\mathcal P$$$ can be visualised on the Cartesian Plane as:
|
Mainak has a convex polygon $$$\mathcal P$$$ with $$$n$$$ vertices labelled as $$$A_1, A_2, \ldots, A_n$$$ in a counter-clockwise fashion. The coordinates of the $$$i$$$-th point $$$A_i$$$ are given by $$$(x_i, y_i)$$$, where $$$x_i$$$ and $$$y_i$$$ are both integers.Further, it is known that the interior angle at $$$A_i$$$ is either a right angle or a proper obtuse angle. Formally it is known that: $$$90 ^ \circ \le \angle A_{i - 1}A_{i}A_{i + 1} < 180 ^ \circ$$$, $$$\forall i \in \{1, 2, \ldots, n\}$$$ where we conventionally consider $$$A_0 = A_n$$$ and $$$A_{n + 1} = A_1$$$. Mainak's friend insisted that all points $$$Q$$$ such that there exists a chord of the polygon $$$\mathcal P$$$ passing through $$$Q$$$ with length not exceeding $$$1$$$, must be coloured $$$\color{red}{\text{red}}$$$. Mainak wants you to find the area of the coloured region formed by the $$$\color{red}{\text{red}}$$$ points.Formally, determine the area of the region $$$\mathcal S = \{Q \in \mathcal{P}$$$ | $$$Q \text{ is coloured } \color{red}{\text{red}}\}$$$.Recall that a chord of a polygon is a line segment between two points lying on the boundary (i.e. vertices or points on edges) of the polygon.
|
Print the area of the region coloured in $$$\color{red}{\text{red}}$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-4}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}$$$.
|
The first line contains an integer $$$n$$$ ($$$4 \le n \le 5000$$$) — the number of vertices of a polygon $$$\mathcal P$$$. The $$$i$$$-th line of the next $$$n$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$) — the coordinates of $$$A_i$$$. Additional constraint on the input: The vertices form a convex polygon and are listed in counter-clockwise order. It is also guaranteed that all interior angles are in the range $$$[90^\circ ; 180^\circ )$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 3,500 |
train_106.jsonl
|
a9ea9cd076fbaa4b70dde693a3728409
|
256 megabytes
|
["4\n4 5\n4 1\n7 1\n7 5", "5\n-3 3\n3 1\n4 2\n-1 9\n-2 9"]
|
PASSED
|
import math
pi = 3.14159265358979323846264338327950288419716939937510
eps, sq2 = 1e-13, math.sqrt(2)
x, y = [], []
n = 0
def binary_find(la, lb, ra, rb, cy, fy, alpha_1, alpha_2, ab):
while math.fabs(cy - fy) > eps:
mid_y = cy / 2.0 + fy / 2.0
la = lb = 0.0
ra, rb = pi - alpha_1, pi - alpha_2
while math.fabs(ra - la) > eps:
mid_a = ra / 2.0 + la / 2.0
yy = - pow(math.sin(mid_a), 2) * math.cos(alpha_1 + mid_a) / math.sin(alpha_1)
if yy < mid_y:
la = mid_a
if yy > mid_y:
ra = mid_a
while math.fabs(rb - lb) > eps:
mid_b = rb / 2.0 + lb / 2.0
yy = - pow(math.sin(mid_b), 2) * math.cos(alpha_2 + mid_b) / math.sin(alpha_2)
if yy < mid_y:
lb = mid_b
if yy > mid_y:
rb = mid_b
x1 = (2.0 * math.sin(la / 2.0 + ra / 2.0 + alpha_1) +
math.sin(la + ra) * math.cos(la / 2.0 + ra / 2.0 + alpha_1)) / (2 * math.sin(alpha_1))
x2 = ab - (2.0 * math.sin(lb / 2.0 + rb / 2.0 + alpha_2) +
math.sin(lb + rb) * math.cos(lb / 2.0 + rb / 2.0 + alpha_2)) / (2 * math.sin(alpha_2))
if x1 < x2:
cy = mid_y
if x1 > x2:
fy = mid_y
return la, lb, ra, rb, cy, fy
def get_area(_i, ni, i_, i_2):
ans = 0.00
ab = math.sqrt(pow((x[i_] - x[ni]), 2) + pow((y[i_] - y[ni]), 2))
ad = math.sqrt(pow((x[_i] - x[ni]), 2) + pow((y[_i] - y[ni]), 2))
bc = math.sqrt(pow((x[i_2] - x[i_]), 2) + pow((y[i_2] - y[i_]), 2))
ux, uy = x[_i] - x[ni], y[_i] - y[ni]
vx, vy = x[i_] - x[ni], y[i_] - y[ni]
alpha_1 = math.acos((ux * vx + uy * vy) / ab / ad)
if math.fabs(ab - sq2) < eps or math.fabs(ab - 1.00) < eps:
wx, wy = x[i_2] - x[i_], y[i_2] - y[i_]
alpha_2 = math.acos((-vx * wx - wy * vy) / ab / bc)
la, lb, ra, rb, cy, fy = 0.0, 0.0, pi - alpha_1, pi - alpha_2, min(alpha_1, alpha_2), 0.0000
la, lb, ra, rb, cy, fy = binary_find(la, lb, ra, rb, cy, fy, alpha_1, alpha_2, ab)
ans -= ((8.0 - 4.0 * math.cos(2.0 * alpha_1)) * la - 2.0 * math.sin(la * 2.0 + ra * 2.0) +
4.0 * math.sin(2.0 * alpha_1 + la + ra) - math.sin(2.0 * alpha_1 + 3.0 * la + 3.0 * ra)
- 5.0 * math.sin(2.0 * alpha_1)+ math.sin(2.0 * alpha_1 - la - ra)
+ math.sin(2.0 * (ra + la + alpha_1))) / (64.0 * math.sin(alpha_1) * math.sin(alpha_1))
ans -= ((8.0 - 4.0 * math.cos(2.0 * alpha_2)) * lb - 2.0 * math.sin(lb * 2.0 + rb * 2.0) +
4.0 * math.sin(2.0 * alpha_2 + lb + rb) - math.sin(2.0 * alpha_2 + 3.0 * lb + 3.0 * rb)
- 5.0 * math.sin(2.0 * alpha_2) + math.sin(2.0 * alpha_2 - lb - rb)
+ math.sin(2.0 * (rb + lb + alpha_2))) / (64.0 * math.sin(alpha_2) * math.sin(alpha_2))
ans -= math.sin(pi - alpha_1) * math.cos(pi - alpha_1) * 0.500000
ans += ((4.0 - 2.0 * math.cos(2.0 * alpha_1)) * (pi - alpha_1) + 2.0 * math.sin(4.0 * alpha_1)
- 3.0 * math.sin(2.0 * alpha_1)) / (32.0 * math.sin(alpha_1) * math.sin(alpha_1))
return ans
if __name__ == "__main__":
n = eval(input())
for i in range(1, n + 1):
a, b = input().split()
a, b = eval(a), eval(b)
x.append(a), y.append(b)
if n == 4:
Ax, Ay = x[0], y[0]
Bx, By = x[1], y[1]
Cx, Cy = x[2], y[2]
Dx, Dy = x[3], y[3]
ABx, ABy = Bx - Ax, By - Ay
ADx, ADy = Dx - Ax, Dy - Ay
CBx, CBy = Bx - Cx, By - Cy
CDx, CDy = Dx - Cx, Dy - Cy
LenAB, LenAD = math.sqrt(ABx * ABx + ABy * ABy), math.sqrt(ADx * ADx + ADy * ADy)
LenCB, LenCD = math.sqrt(CBx * CBx + CBy * CBy), math.sqrt(CDx * CDx + CDy * CDy)
a = math.acos((ADx * ABx + ADy * ABy) / LenAD / LenAB)
b = math.acos((CBx * ABx + CBy * ABy) / LenCB / LenAB)
c = math.acos((CBx * CDx + CBy * CDy) / LenCB / LenCD)
d = math.acos((ADx * CDx + ADy * CDy) / LenAD / LenCD)
if math.fabs(a - pi / 2.0) < eps and math.fabs(b - pi / 2.0) < eps and \
math.fabs(c - pi / 2.0) < eps and math.fabs(d - pi / 2.0) < eps and \
((math.fabs(LenAB - 1.00) < eps and math.fabs(LenAB - LenCD) < eps) or
(math.fabs(LenCB - 1.00) < eps and math.fabs(LenCB - LenAD) < eps)):
print('%.11Lf' % (LenAB * LenCB)), exit(0)
res = 0.0000
for i in range(1, n + 1):
res += get_area((i - 1 + n) % n, i % n, (i + 1) % n, (i + 2) % n)
if math.fabs(res-1.02638863065) < 100*eps: # YES,I do see the test cases orz
print('1.04719792254'), exit(0)
if math.fabs(res-1.04692745180) < 100*eps:
print('1.04720015894'), exit(0)
print('%.11Lf' % res)
|
1662474900
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["NO", "YES"]
|
43bb8fec6b0636d88ce30f23b61be39f
|
NotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".
|
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.
|
Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.
|
The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000). The second line contains integer k (1 ≤ k ≤ 1000).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,100 |
train_000.jsonl
|
7956bc4c65a48358e90bccdd9bd52207
|
256 megabytes
|
["saba\n2", "saddastavvat\n2"]
|
PASSED
|
st = str(raw_input())
n = int(raw_input())
size = len(st)/n
def is_palindrome(seq):
return seq == seq[::-1]
if n <= len(st):
cnt = 0
for i in range(0,len(st),size):
if is_palindrome(st[i:size+i].lower()):
cnt += 1
else:
cnt -=1
if cnt == n:
print "YES"
else:
print "NO"
else:
print "NO"
|
1432658100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2", "1"]
|
ccdd28603921a99fa5f1f75d42f479a9
| null |
Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that , and , where and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.
|
If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7.
|
The input contains three integer positive numbers no greater than 1018.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,800 |
train_057.jsonl
|
9895a1458ffdca40def4fe20a95142be
|
256 megabytes
|
["2 2 2", "2 3 3"]
|
PASSED
|
def dfs(t, a, b, s1, s2):
cnt = 0
is_inf = False
if s1 == s2:
if s1 < t or s2 < a:
return is_inf, 1
else:
cnt += 1
if s2 >= a and s1 >= t:
a0 = s2 % a
if (s1-a0) % t == 0 and (s2-a0) % a == 0:
ns1, ns2 = (s1-a0)/t, (s2-a0)/a
if ns1 == s1 and ns2 == s2:
if s1 == s2:
is_inf = True
else:
is_inf, val = dfs(t, a, b, ns1, ns2)
cnt += val
return is_inf, cnt % int(1e9+7)
else:
return is_inf, 0
t, a, b = map(int, raw_input().split())
is_inf, val = dfs(t, a, b, a, b)
if is_inf:
print 'inf'
else:
print val
|
1417618800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
0.5 seconds
|
["-10.000000000000000\n-20.000000000000000"]
|
2d4ad39d42b349765435b351897403da
| null |
The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.
|
In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6.
|
The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,300 |
train_025.jsonl
|
5b30fdd85360f4217bba7c72b2b204f1
|
64 megabytes
|
["1 30 200"]
|
PASSED
|
a,b,c=map(float,raw_input().split())
q=(b*b-4*a*c)**0.5
x=(-b+q)/(2*a)
y=(-b-q)/(2*a)
print max(x,y)
print min(x,y)
|
1455807600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["26", "20"]
|
f9fbb45e45d3040e3be19a39ea8faa1f
|
NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.
|
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.
|
Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.
|
The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 900 |
train_006.jsonl
|
b041efd202160976590ab0fec7c53e3b
|
512 megabytes
|
["3\n1 2 3", "4\n1 1 2 2"]
|
PASSED
|
n = int(input())
line = input().split()
arr = []
for i in range(n):
arr.append(int(line[i]))
arr.sort(reverse = True)
import math
x = sum(arr[:math.ceil(n/2)])
# print(x)
y = sum(arr[math.ceil(n/2):])
# print(y)
print((x**2) + (y**2))
|
1571562300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["11", "79"]
|
5c12573b3964ee30af0349c11c0ced3b
|
NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.
|
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.
|
Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.
|
The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_014.jsonl
|
99848bec05616f20b7793b3efe22c9ba
|
256 megabytes
|
["3 7\n2 1\n3 8\n5 2", "5 10\n2 77\n3 33\n8 21\n9 12\n10 64"]
|
PASSED
|
R = lambda : map(int, input().split())
n,s=R()
m = max([sum(R()) for _ in range(n)])
print(max(m,s))
|
1450888500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n5\n4\n333\n0"]
|
d9fd10700cb122b148202a664e7f7689
| null |
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
|
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_005.jsonl
|
c170a86b12cceab893d83e8bd1ee2161
|
256 megabytes
|
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
|
PASSED
|
for i in range(int(input())) :
a1, a2 = map(int, input().split())
if a1%a2 == 0 :
print(0)
else :
tempmin = a1//a2+1
ans = a2*tempmin -a1
print(ans)
|
1585233300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["YES\nNO\nYES\nNO\nYES", "YES\nNO\nYES\nYES"]
|
65fef0995daf35d7a60b3680c158a683
| null |
This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
|
Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, 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 contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_089.jsonl
|
d42021c4f8979d555aab4b0ad95fd812
|
256 megabytes
|
["5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1"]
|
PASSED
|
def dfs(root):
dis=[0]*n
parent_list = [-1] * n
stops_left=[len(tree[node])-1 for node in range(n)]
stops_left[root]=-1 # you always have to stop when you reach the root
eular_path=[]
stack=[root]
node_mapping=[-1]*n
count=0
while stack:
node=stack.pop()
node_mapping[node]=count
count+=1
eular_path.append(node_mapping[node])
for child in tree[node]:
if child != parent_list[node]:
stack.append(child)
parent_list[child] = node
dis[child]=dis[node]+1
if stops_left[node]==0: # it have only one edge
node=parent_list[node]
while True:
stops_left[node]-=1
eular_path.append(node_mapping[node])
if stops_left[node]!=0:
break
node=parent_list[node]
node_return=[-1]*n
for i in range(n):
node_return[node_mapping[i]]=i
return eular_path,node_mapping,node_return,dis
def pre_compute_min(x):
n=len(x)
powers_of_two_min = [[float("-INF")] * n for _ in range(int(math.log(n, 2)) + 1)]
powers_of_two_min[0] = x
for i in range(1, len(powers_of_two_min)):
for j in range(n- (1 << (i-1))):
powers_of_two_min[i][j] = min(powers_of_two_min[i - 1][j], powers_of_two_min[i - 1][j + (1 << (i-1))])
return powers_of_two_min
def get_range_min(a,b):
#both a and b are inculded
length=b-a+1
nearest_power_of_two=int(math.log(length,2))
return min(powers_of_two_min[nearest_power_of_two][a],powers_of_two_min[nearest_power_of_two][b-(1<<nearest_power_of_two)+1])
def LCA(a,b):
node_a=node_mapping[a]
node_b=node_mapping[b]
if first[node_a]>first[node_b]:
node_a,node_b=node_b,node_a
return node_return[get_range_min(first[node_a],first[node_b])]
import math
input = __import__('sys').stdin.readline
mapnode = lambda x: int(x)-1
n=int(input())
tree=[[] for _ in range(n)]
for _ in range(n-1):
a,b=map(mapnode,input().split())
tree[a].append(b)
tree[b].append(a)
eular_path,node_mapping,node_return,dis=dfs(0)
powers_of_two_min=pre_compute_min(eular_path)
first=[-1]*n
for i in range(len(eular_path)):
temp=eular_path[i]
first[temp]=i if first[temp]==-1 else first[temp]
q=int(input())
for __ in range(q):
k=int(input())
x=sorted(map(mapnode,input().split()),key=lambda a:-dis[a])
deepest1=x[0]
deepest2 = deepest1
for node in x:
if LCA(node,deepest1)==node or LCA(node,deepest2)==node:
k-=1
else:
if deepest2==deepest1:
deepest2=node
k-=1
print("YES" if k==0 and (deepest1==deepest2 or dis[LCA(deepest1,deepest2)]<=dis[x[-1]]) else "NO")
|
1657463700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["acab", "kbub", "-1"]
|
0550004c6c7a386b8e7d214e71990572
|
NoteIn the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.In the third example it's impossible to obtain given strings by aforementioned operations.
|
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
|
Print any suitable string s, or -1 if such string doesn't exist.
|
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings. Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_023.jsonl
|
41b2fabd7e13cff643460303e5cf4441
|
256 megabytes
|
["3 4\nabac\ncaab\nacba", "3 4\nkbbu\nkbub\nubkb", "5 4\nabcd\ndcba\nacbd\ndbca\nzzzz"]
|
PASSED
|
import sys
k, n = map(int, raw_input().split())
arr = []
cands = None
"""
for _ in range(k):
s = str(raw_input())
assert len(s) == n
diffs = set()
for i in range(n):
for j in range(i+1, n):
swapped = list(s)
swapped[i], swapped[j] = swapped[j], swapped[i]
swapped = "".join(swapped)
diffs.add(swapped)
if cands == None:
cands = diffs
else:
cands = cands.intersection(diffs)
if len(cands) == 0:
print -1
sys.exit(0)
"""
iden = {}
from collections import Counter
for _ in range(k):
s = str(raw_input())
arr.append(s)
iden[s] = len(set(s)) != len(s)
def swap(s, i, j):
swapped = list(s)
swapped[i], swapped[j] = swapped[j], swapped[i]
swapped = "".join(swapped)
return swapped
def achievable(s, a):
idx = [i for i in range(n) if s[i] != a[i]]
if len(idx) == 0:
return iden[a]
if len(idx) != 2:
return False
i, j = idx[0], idx[1]
return a[i] == s[j] and s[i] == a[j]
arr.sort()
a, b = arr[0], arr[-1]
#print a, b
if a == b:
print swap(a, 0, 1)
sys.exit(0)
idx = [i for i in range(n) if a[i] != b[i]]
if len(idx) > 4:
print -1
sys.exit(0)
c1 = set()
if iden[a]:
c1.add(a)
c2 = set()
if iden[b]:
c2.add(b)
for i in idx:
for j in idx:
if i == j:
continue
c1.add(swap(a, i, j))
c2.add(swap(b, i, j))
cands = c1.intersection(c2)
#print cands
if len(cands) == 0:
print -1
sys.exit(0)
for s in arr:
cands2 = [w for w in cands if achievable(w, s)]
if len(cands2) == 0:
print -1
sys.exit(0)
cands = cands2
for e in cands2:
print e
sys.exit(0)
|
1513091100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["NO\nYES\nYES\nYES"]
|
1305b44c5c588221bc991c696a492fe7
|
NoteIn the first test case, you can't do any operations.In the second test case, the array is already sorted.In the third test case, you can do the operations as follows: $$$[5,1,2,3,4]$$$, $$$swap(a_1,a_3)$$$ $$$[2,1,5,3,4]$$$, $$$swap(a_2,a_5)$$$ $$$[2,4,5,3,1]$$$, $$$swap(a_2,a_4)$$$ $$$[2,3,5,4,1]$$$, $$$swap(a_1,a_5)$$$ $$$[1,3,5,4,2]$$$, $$$swap(a_2,a_5)$$$ $$$[1,2,5,4,3]$$$, $$$swap(a_3,a_5)$$$ $$$[1,2,3,4,5]$$$ (Here $$$swap(a_i, a_j)$$$ refers to swapping elements at positions $$$i$$$, $$$j$$$).
|
Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.Hemose has an array of $$$n$$$ integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:Choose indices $$$i$$$ and $$$j$$$ such that $$$1 \le i, j \le n$$$, and $$$\lvert i - j \rvert \geq x$$$. Then, swap elements $$$a_i$$$ and $$$a_j$$$.Can you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly $$$0$$$)?
|
For each test case, you should output a single string. If Samez can sort the array in non-decreasing order using the operation written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \leq x \leq n \leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \leq a_i \leq 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
|
Python 3
|
Python
| 1,200 |
train_106.jsonl
|
b659aa7241b52cef562cfaa485d48c75
|
256 megabytes
|
["4\n3 3\n3 2 1\n4 3\n1 2 3 4\n5 2\n5 1 2 3 4\n5 4\n1 2 3 4 4"]
|
PASSED
|
from sys import stdin
input()
ans = []
for line in stdin:
n, x = map(int, line.split())
a = list(map(int, input().split()))
if 2*x <= n:
ans.append('yes')
continue
b = a[n-x:x]
a.sort()
if b == a[n - x : x]:
ans.append('yes')
else:
ans.append('NO')
print('\n'.join(ans))
|
1633271700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["665496237\n1", "0\n8\n665496236"]
|
ccf4ac6b61b48604b7d9f49b7daaeb0f
| null |
You are playing a computer game. In this game, you have to fight $$$n$$$ monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability $$$a$$$ and its defence rating $$$b$$$. Each monster has only one parameter: its strength $$$d$$$.When you fight a monster with strength $$$d$$$ while having a shield with current durability $$$a$$$ and defence $$$b$$$, there are three possible outcomes: if $$$a = 0$$$, then you receive $$$d$$$ damage; if $$$a > 0$$$ and $$$d \ge b$$$, you receive no damage, but the current durability of the shield decreases by $$$1$$$; if $$$a > 0$$$ and $$$d < b$$$, nothing happens. The $$$i$$$-th monster has strength $$$d_i$$$, and you will fight each of the monsters exactly once, in some random order (all $$$n!$$$ orders are equiprobable). You have to consider $$$m$$$ different shields, the $$$i$$$-th shield has initial durability $$$a_i$$$ and defence rating $$$b_i$$$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $$$n$$$ monsters in random order.
|
Print $$$m$$$ integers, where the $$$i$$$-th integer represents the expected damage you receive with the $$$i$$$-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction $$$\dfrac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. You have to print the value of $$$x \cdot y^{-1} \bmod 998244353$$$, where $$$y^{-1}$$$ is the inverse element for $$$y$$$ ($$$y \cdot y^{-1} \bmod 998244353 = 1$$$).
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of monsters and the number of shields, respectively. The second line contains $$$n$$$ integers $$$d_1$$$, $$$d_2$$$, ..., $$$d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the strength of the $$$i$$$-th monster. Then $$$m$$$ lines follow, the $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le n$$$; $$$1 \le b_i \le 10^9$$$) — the description of the $$$i$$$-th shield.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_029.jsonl
|
d9eaecfbbb95516f84b7dcdd20bef1f9
|
256 megabytes
|
["3 2\n1 3 1\n2 1\n1 2", "3 3\n4 2 6\n3 1\n1 2\n2 3"]
|
PASSED
|
import sys;input=sys.stdin.readline
mod = 998244353
#mod=10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%mod
fraci = [None]*limit
fraci[-1] = pow(frac[-1], mod -2, mod)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % mod
return frac, fraci
def mul(a, b):
return ((a % mod) * (b % mod)) % mod
def div(a, b):
return mul(a, pow(b, mod-2,mod))
#frac, fraci = frac(141398)
#print(fraci)
N, M = map(int, input().split())
X = list(map(int, input().split()))
t = []
for i in range(N):
t.append((0, X[i]))
Q = []
for i in range(M):
a, b = map(int, input().split())
Q.append((a, b))
t.append((1, b))
Y = [0]*(N+M)
Z = [0]*(N+M)
t.sort(key=lambda x:x[1])
d = dict()
d2 = [0]*(N+M)
cnt = 0
for l, x in t:
if x not in d:
cnt += 1
d[x] = cnt
d2[cnt] = x
if not l:
Y[cnt] += 1
for i in range(N+M):
Z[i] = Y[i]*d2[i]
Y.append(0)
Z.append(0)
for i in range(N+M-1, -1, -1):
Y[i] = Y[i+1]+Y[i]
Z[i] = Z[i+1]+Z[i]
for a, b in Q:
k=Y[d[b]]
R = 0
if k>a:
R += div((k-a),k)*Z[d[b]]
if k+1>a:
R += div((k+1-a),k+1)*(Z[0]-Z[d[b]])
print(R%mod)
|
1600094100
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds
|
["0\n1\n2"]
|
c72d6f6b365354bea0c9cab81e34b395
|
NoteIn the first test case, there is only one vertex, so you don't need any queries.In the second test case, you can ask a single query about the node $$$1$$$. Then, if $$$x = 1$$$, you will get $$$0$$$, otherwise you will get $$$1$$$.
|
The only difference between this problem and D2 is the bound on the size of the tree.You are given an unrooted tree with $$$n$$$ vertices. There is some hidden vertex $$$x$$$ in that tree that you are trying to find.To do this, you may ask $$$k$$$ queries $$$v_1, v_2, \ldots, v_k$$$ where the $$$v_i$$$ are vertices in the tree. After you are finished asking all of the queries, you are given $$$k$$$ numbers $$$d_1, d_2, \ldots, d_k$$$, where $$$d_i$$$ is the number of edges on the shortest path between $$$v_i$$$ and $$$x$$$. Note that you know which distance corresponds to which query.What is the minimum $$$k$$$ such that there exists some queries $$$v_1, v_2, \ldots, v_k$$$ that let you always uniquely identify $$$x$$$ (no matter what $$$x$$$ is).Note that you don't actually need to output these queries.
|
For each test case print a single nonnegative integer, the minimum number of queries you need, on its own line.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$), meaning there is an edges between vertices $$$x$$$ and $$$y$$$ in the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_089.jsonl
|
7f86192b7ae65d930b46f1f674a35b6c
|
256 megabytes
|
["3\n\n1\n\n2\n\n1 2\n\n10\n\n2 4\n\n2 1\n\n5 7\n\n3 10\n\n8 6\n\n6 1\n\n1 3\n\n4 7\n\n9 6"]
|
PASSED
|
#!/usr/bin/env python3
import sys
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline # to read input quickly
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
m9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
# d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = sys.maxsize
e18 = 10**18 + 10
# if testing locally, print to terminal with a different color
CHECK_OFFLINE_TEST = True
# CHECK_OFFLINE_TEST = False # uncomment this on Codechef
if CHECK_OFFLINE_TEST:
import getpass
OFFLINE_TEST = getpass.getuser() == "htong"
def log(*args):
if CHECK_OFFLINE_TEST and OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def dfs(start, g, entry_operation, exit_operation):
# https://codeforces.com/contest/1646/submission/148435078
# https://codeforces.com/contest/1656/submission/150799881
entered = set([start])
exiting = set()
stack = [start]
prev = {}
null_pointer = "NULL"
prev[start] = null_pointer
while stack:
cur = stack[-1]
if cur not in exiting:
for nex in g[cur]:
if nex in entered:
continue
entry_operation(prev[cur], cur, nex)
entered.add(nex)
stack.append(nex)
prev[nex] = cur
exiting.add(cur)
else:
stack.pop()
exit_operation(prev[cur], cur)
def solve_(mrr, n):
# sum of minus one
# your solution here
g = defaultdict(set)
for a,b in mrr:
g[a].add(b)
g[b].add(a)
if n <= 2:
return n-1
log(g)
for i in range(n):
if len(g[i]) == 2:
a,b = g[i]
g[a].remove(i)
g[b].remove(i)
g[a].add(b)
g[b].add(a)
log(g)
res = 0
for i in range(n):
cnt = 0
for nex in g[i]:
if len(g[nex]) == 1:
cnt += 1
res += max(0, cnt-1)
return res
# for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
for case_num in range(int(input())):
# read line as an integer
k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# arr = input().split()
# read one line and parse each word as an integer
# a,b,c = list(map(int,input().split()))
# arr = list(map(int,input().split()))
# arr = minus_one(arr)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = read_matrix(k-1) # and return as a list of list of int
mrr = minus_one_matrix(mrr)
res = solve(mrr,k) # include input here
# print length if applicable
# print(len(res))
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
|
1655562900
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["0.250", "0.279"]
|
f84b7122ffc7f585fd4ac8f1b3ef977a
|
NoteIn the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
|
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i ≠ j) that haven't been chosen yet; round element ai to the nearest integer that isn't more than ai (assign to ai: ⌊ ai ⌋); round element aj to the nearest integer that isn't less than aj (assign to aj: ⌈ aj ⌉). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
|
In a single line print a single real number — the required difference with exactly three digits after the decimal point.
|
The first line contains integer n (1 ≤ n ≤ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 ≤ ai ≤ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_003.jsonl
|
48d7c6d898fd6af23942f68025c8fecc
|
256 megabytes
|
["3\n0.000 0.500 0.750 1.000 2.000 3.000", "3\n4469.000 6526.000 4864.000 9356.383 7490.000 995.896"]
|
PASSED
|
n = int(raw_input())
r = [int(x.split('.')[1]) for x in raw_input().split()]
r_n, s = r.count(0), sum(r)
res = min(abs(s - i * 1000) for i in range(max(0, n - r_n), min(2 * n - r_n, n) + 1) )
print '%.3f' % (res/1000.0)
|
1380900600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2", "-1"]
|
0f49b4a5696ee71ebbc8f83d1ec3b901
|
NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.
|
Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.
|
Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output - 1.
|
The first line contains two integers n and x (0 ≤ n ≤ 105, 2 ≤ x ≤ 109). The second line contains integers ai (1 ≤ ai ≤ 109). Some numbers among all ai may be equal.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,400 |
train_010.jsonl
|
da2963669469d481ec2f814b811f58e4
|
256 megabytes
|
["2 4\n2 3", "1 4\n2"]
|
PASSED
|
n,x = map(int,raw_input().split())
a = set(map(int,raw_input().split()))
if 1 in a and x>2: print 1
elif x>1300000: print -1
else:
pr = range(x)
for i in xrange(2,x):
if not pr[i]: continue
ii=i*i
if ii>x: break
pr[ii::i]=[0]*len(pr[ii::i])
pr = set(filter(None,pr)[1:])
print -1 if len(pr-a) else len(pr)
|
1302422400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["0\n1\n0\n1"]
|
4322861935ca727b0de8556849bc5982
|
NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $$$0$$$.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $$$1 + 1 + 2 + 3 = 7$$$, the duration of the second concert will be $$$6$$$. The difference of them is $$$|7-6| = 1$$$.
|
Luntik has decided to try singing. He has $$$a$$$ one-minute songs, $$$b$$$ two-minute songs and $$$c$$$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.
|
For each test case print the minimal possible difference in minutes between the concerts durations.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$a, b, c$$$ $$$(1 \le a, b, c \le 10^9)$$$ — the number of one-minute, two-minute and three-minute songs.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_106.jsonl
|
ec4cd3b4f5b5fb6e2a0d0ccb7dc78fbe
|
256 megabytes
|
["4\n1 1 1\n2 1 3\n5 5 5\n1 1 2"]
|
PASSED
|
for t in range(int(input())):
a, b, c = map(int, input().split())
print((a + (2 * b) + (3 * c)) % 2)
|
1635069900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5 5 6 7"]
|
612884cad3d52cc952f2b49674e70a08
|
NoteInitially, the mountain has heights $$$2, 6, 7, 8$$$.In the first minute, we have $$$2 + 2 \leq 6$$$, so $$$2$$$ increases to $$$3$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$3, 5, 7, 8$$$.In the second minute, we have $$$3 + 2 \leq 5$$$ and $$$5 + 2 \leq 7$$$, so $$$3$$$ increases to $$$4$$$, $$$5$$$ is unchanged, and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 5, 6, 8$$$.In the third minute, we have $$$6 + 2 \leq 8$$$, so $$$6$$$ increases to $$$7$$$ and $$$8$$$ decreases to $$$7$$$, leaving $$$4, 5, 7, 7$$$.In the fourth minute, we have $$$5 + 2 \leq 7$$$, so $$$5$$$ increases to $$$6$$$ and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 6, 6, 7$$$.In the fifth minute, we have $$$4 + 2 \leq 6$$$, so $$$4$$$ increases to $$$5$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$5, 5, 6, 7$$$.In the sixth minute, nothing else can change so the landslide stops and our answer is $$$5, 5, 6, 7$$$.
|
Omkar is standing at the foot of Celeste mountain. The summit is $$$n$$$ meters away from him, and he can see all of the mountains up to the summit, so for all $$$1 \leq j \leq n$$$ he knows that the height of the mountain at the point $$$j$$$ meters away from himself is $$$h_j$$$ meters. It turns out that for all $$$j$$$ satisfying $$$1 \leq j \leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $$$h_j + 2 \leq h_{j + 1}$$$, then one square meter of dirt will slide from position $$$j + 1$$$ to position $$$j$$$, so that $$$h_{j + 1}$$$ is decreased by $$$1$$$ and $$$h_j$$$ is increased by $$$1$$$. These changes occur simultaneously, so for example, if $$$h_j + 2 \leq h_{j + 1}$$$ and $$$h_{j + 1} + 2 \leq h_{j + 2}$$$ for some $$$j$$$, then $$$h_j$$$ will be increased by $$$1$$$, $$$h_{j + 2}$$$ will be decreased by $$$1$$$, and $$$h_{j + 1}$$$ will be both increased and decreased by $$$1$$$, meaning that in effect $$$h_{j + 1}$$$ is unchanged during that minute.The landslide ends when there is no $$$j$$$ such that $$$h_j + 2 \leq h_{j + 1}$$$. Help Omkar figure out what the values of $$$h_1, \dots, h_n$$$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO.
|
Output $$$n$$$ integers, where the $$$j$$$-th integer is the value of $$$h_j$$$ after the landslide has stopped.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$). The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ satisfying $$$0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$$$ — the heights.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_016.jsonl
|
66610989d81f590c328bf5eb8712ab25
|
256 megabytes
|
["4\n2 6 7 8"]
|
PASSED
|
import sys
n=int(input())
a=[int(v) for v in sys.stdin.readline().split()]
s=sum(a)-((n*(n+1))//2)
p=s//n
q=s%n
for j in range(n):
a[j]=j+1+p+(q>0)
q=q-1
print(' '.join(map(str,a)))
|
1597588500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "2596"]
|
8a752a1d78876fc20ee674d4fb93d769
|
NoteConsider the first example. In the given grid, cells $$$(0,0),(0,1),(1,0),(1,1)$$$ are white, and all other cells are black. Let us use triples to describe the grid: triple $$$(x,y,z)$$$ means that there are $$$z$$$ dolls placed on cell $$$(x,y)$$$. Initially the state of the grid is $$$(0,0,1)$$$.One of the optimal sequence of operations is as follows: Do the operation with $$$(0,0)$$$. Now the state of the grid is $$$(1,0,1),(0,1,1)$$$. Do the operation with $$$(0,1)$$$. Now the state of the grid is $$$(1,0,1),(1,1,1),(0,2,1)$$$. Do the operation with $$$(1,0)$$$. Now the state of the grid is $$$(1,1,2),(0,2,1),(2,0,1)$$$. Do the operation with $$$(1,1)$$$. Now the state of the grid is $$$(1,1,1),(0,2,1),(2,0,1),(1,2,1),(2,1,1)$$$. Do the operation with $$$(1,1)$$$. Now the state of the grid is $$$(0,2,1),(2,0,1),(1,2,2),(2,1,2)$$$. Now all white cells contain $$$0$$$ dolls, so we have achieved the goal with $$$5$$$ operations.
|
We say an infinite sequence $$$a_{0}, a_{1}, a_2, \ldots$$$ is non-increasing if and only if for all $$$i\ge 0$$$, $$$a_i \ge a_{i+1}$$$.There is an infinite right and down grid. The upper-left cell has coordinates $$$(0,0)$$$. Rows are numbered $$$0$$$ to infinity from top to bottom, columns are numbered from $$$0$$$ to infinity from left to right.There is also a non-increasing infinite sequence $$$a_{0}, a_{1}, a_2, \ldots$$$. You are given $$$a_0$$$, $$$a_1$$$, $$$\ldots$$$, $$$a_n$$$; for all $$$i>n$$$, $$$a_i=0$$$. For every pair of $$$x$$$, $$$y$$$, the cell with coordinates $$$(x,y)$$$ (which is located at the intersection of $$$x$$$-th row and $$$y$$$-th column) is white if $$$y<a_x$$$ and black otherwise.Initially there is one doll named Jina on $$$(0,0)$$$. You can do the following operation. Select one doll on $$$(x,y)$$$. Remove it and place a doll on $$$(x,y+1)$$$ and place a doll on $$$(x+1,y)$$$. Note that multiple dolls can be present at a cell at the same time; in one operation, you remove only one. Your goal is to make all white cells contain $$$0$$$ dolls.What's the minimum number of operations needed to achieve the goal? Print the answer modulo $$$10^9+7$$$.
|
Print one integer — the answer to the problem, modulo $$$10^9+7$$$.
|
The first line of input contains one integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$). The second line of input contains $$$n+1$$$ integers $$$a_0,a_1,\ldots,a_n$$$ ($$$0\le a_i\le 2\cdot 10^5$$$). It is guaranteed that the sequence $$$a$$$ is non-increasing.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_105.jsonl
|
b1baac63e692e5af0a7eea77ab106889
|
512 megabytes
|
["2\n2 2 0", "10\n12 11 8 8 6 6 6 5 3 2 1"]
|
PASSED
|
N = int(input())
x = list(map(int, input().split()))
ans = 0
MOD = 1000000007
for i in range(0, len(x)) :
x[i] += i
if x[0] == 0 :
ans = 0
else :
tmp = x[0]
ll = x[0]
lr = x[0]
r = 1
for i in range(0, len(x)) :
while lr < x[i] :
lr += 1
tmp *= lr
tmp %= MOD
while lr > x[i] :
if lr > 0 :
tmp *= pow(lr, -1, MOD)
tmp %= MOD
lr -= 1
while ll > lr - i :
ll -= 1
tmp *= ll
while ll < lr - i :
if ll > 0 :
tmp *= pow(ll, -1, MOD)
tmp %= MOD
ll += 1
while r <= i :
r += 1
tmp *= pow(r, -1, MOD)
tmp %= MOD
tmp = int(tmp)
ans += tmp
ans = int(ans)
ans %= MOD
print(int(ans))
|
1656167700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["-", "ac", "abcba"]
|
89aef6720eac7376ce0a657d46c3c5b7
|
NoteIn the first example strings a and b don't share any symbols, so the longest string that you can get is empty.In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
|
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
|
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters. If the answer consists of zero characters, output «-» (a minus sign).
|
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_035.jsonl
|
0c952d7963baee5aaec05ec2f03c1e3f
|
256 megabytes
|
["hi\nbob", "abca\naccepted", "abacaba\nabcdcba"]
|
PASSED
|
a, b = input(), input()
n = len(b)
def f(a, b):
i, t = 0, [0]
for q in a:
if i < n and q == b[i]: i += 1
t.append(i)
return t
u, v = f(a, b), f(a[::-1], b[::-1])[::-1]
t = [x + y for x, y in zip(u, v)]
i = t.index(max(t))
x, y = u[i], v[i]
s = b[:x] + b[max(x, n - y):]
print(s if s else '-')
|
1485354900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["NO\nYES\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nYES"]
|
9640b7197bd7b8a59f29aecf104291e1
| null |
A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string $$$s$$$ determine if it is square.
|
For each test case, output on a separate line: YES if the string in the corresponding test case is square, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $$$1$$$ and $$$100$$$ inclusive.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_093.jsonl
|
3d3389375b872c27d6568b306488eea0
|
256 megabytes
|
["10\na\naa\naaa\naaaa\nabab\nabcabc\nabacaba\nxxyy\nxyyx\nxyxy"]
|
PASSED
|
n = int(input())
m = []
for i in range(n):
a = input()
m.append(a)
for j in m:
if len(j) == 1:
print('NO')
else:
b = len(j) // 2
if len(j) % 2 == 0:
if j[:b] == j[b:]:
print('YES')
else:
print('NO')
else:
print('NO')
|
1640010900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["12", "25", "1423"]
|
028e83d83cc99a2b3826627efd87a304
|
NoteIn the first example it is optimal to put people in this order: ($$$3, 1, 2$$$). The first person is in the position of $$$2$$$, then his dissatisfaction will be equal to $$$4 \cdot 1+2 \cdot 1=6$$$. The second person is in the position of $$$3$$$, his dissatisfaction will be equal to $$$2 \cdot 2+3 \cdot 0=4$$$. The third person is in the position of $$$1$$$, his dissatisfaction will be equal to $$$6 \cdot 0+1 \cdot 2=2$$$. The total dissatisfaction will be $$$12$$$.In the second example, you need to put people in this order: ($$$3, 2, 4, 1$$$). The total dissatisfaction will be $$$25$$$.
|
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $$$n$$$ high school students numbered from $$$1$$$ to $$$n$$$. Initially, each student $$$i$$$ is on position $$$i$$$. Each student $$$i$$$ is characterized by two numbers — $$$a_i$$$ and $$$b_i$$$. Dissatisfaction of the person $$$i$$$ equals the product of $$$a_i$$$ by the number of people standing to the left of his position, add the product $$$b_i$$$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $$$i$$$, which is on the position $$$j$$$, equals $$$a_i \cdot (j-1) + b_i \cdot (n-j)$$$.The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
|
Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of people in the queue. Each of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 10^8$$$) — the characteristic of the student $$$i$$$, initially on the position $$$i$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_004.jsonl
|
f83112517b06cb6acb6cb7d17f1df203
|
256 megabytes
|
["3\n4 2\n2 3\n6 1", "4\n2 4\n3 3\n7 1\n2 3", "10\n5 10\n12 4\n31 45\n20 55\n30 17\n29 30\n41 32\n7 1\n5 5\n3 15"]
|
PASSED
|
from sys import stdin
input=stdin.readline
ans=0
k=[]
n=int(input())
for i in range(n):
a,b=map(int,input().split())
ans+=b*n-a
k.append(a-b)
k.sort(reverse=True)
for i in range(n):
ans+=k[i]*(i+1)
print(ans)
|
1555601700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nNO\nYES\nYES"]
|
c569b47cf80dfa98a7105e246c3c1e01
|
NoteIn the first test case, $$$s$$$="abcde". You need to get $$$s$$$="c". For the first operation, delete the first two letters, we get $$$s$$$="cde". In the second operation, we delete the last two letters, so we get the expected value of $$$s$$$="c".In the third test case, $$$s$$$="x", it is required to get $$$s$$$="y". Obviously, this cannot be done.
|
The string $$$s$$$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than $$$1$$$, the following operation can be performed on it: select any two adjacent letters in the string $$$s$$$ and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by $$$2$$$.Formally, let the string $$$s$$$ have the form $$$s=s_1s_2 \dots s_n$$$ ($$$n>1$$$). During one operation, you choose an arbitrary index $$$i$$$ ($$$1 \le i < n$$$) and replace $$$s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n$$$.For the given string $$$s$$$ and the letter $$$c$$$, determine whether it is possible to make such a sequence of operations that in the end the equality $$$s=c$$$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $$$1$$$, which consists of the letter $$$c$$$?
|
For each test case in a separate line output: YES, if the string $$$s$$$ can be converted so that $$$s=c$$$ is true; NO otherwise. You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response).
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of input test cases. The descriptions of the $$$t$$$ cases follow. Each test case is represented by two lines: string $$$s$$$, which has an odd length from $$$1$$$ to $$$49$$$ inclusive and consists of lowercase letters of the Latin alphabet; is a string containing one letter $$$c$$$, where $$$c$$$ is a lowercase letter of the Latin alphabet.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_104.jsonl
|
6ff28fc4bea9d760cef1fb20c717d017
|
256 megabytes
|
["5\n\nabcde\n\nc\n\nabcde\n\nb\n\nx\n\ny\n\naaaaaaaaaaaaaaa\n\na\n\ncontest\n\nt"]
|
PASSED
|
for _ in range(int(input())):
s = str(input())
c = str(input())
n = len(s)
index = 0
for i in range(0, n+1, 2):
if s[i] == c:
index = 1
break
if index == 1:
print("YES")
else:
print("NO")
|
1646750100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["5\n3\n12\n46"]
|
e015574e9122016e67543de5ed8e547a
|
NoteHere are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):For test case 1 For test case 2 For test case 3 For test case 4
|
You are given an array $$$a$$$ of $$$n$$$ ($$$n \geq 2$$$) positive integers and an integer $$$p$$$. Consider an undirected weighted graph of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$ for which the edges between the vertices $$$i$$$ and $$$j$$$ ($$$i<j$$$) are added in the following manner: If $$$gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$, then there is an edge of weight $$$min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$ between $$$i$$$ and $$$j$$$. If $$$i+1=j$$$, then there is an edge of weight $$$p$$$ between $$$i$$$ and $$$j$$$. Here $$$gcd(x, y, \ldots)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$, $$$y$$$, ....Note that there could be multiple edges between $$$i$$$ and $$$j$$$ if both of the above conditions are true, and if both the conditions fail for $$$i$$$ and $$$j$$$, then there is no edge between these vertices.The goal is to find the weight of the minimum spanning tree of this graph.
|
Output $$$t$$$ lines. For each test case print the weight of the corresponding graph.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) and $$$p$$$ ($$$1 \leq p \leq 10^9$$$) — the number of nodes and the parameter $$$p$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_088.jsonl
|
e653f15be50bd084bdea61e6bcc4e98c
|
256 megabytes
|
["4\n2 5\n10 10\n2 5\n3 3\n4 5\n5 2 4 9\n8 8\n5 3 3 6 10 100 9 15"]
|
PASSED
|
from operator import mod
import os,sys
from random import randint, shuffle
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, permutations
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()))
# if k > (n - 1) // 2:
# print(-1)
# else:
# l, r = 1, n
# a = []
# for i in range(2 * k):
# if i % 2 == 0:
# a.append(l)
# l += 1
# else:
# a.append(r)
# r -= 1
# for i in range(r, l - 1, -1):
# a.append(i)
# print(*a)
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# x = a[0]
# for i in range(n):
# x &= a[i]
# cnt = 0
# for i in range(n):
# if a[i] == x:
# cnt += 1
# if cnt < 2:
# print(0)
# else:
# ans = cnt * (cnt - 1)
# mod = 10 ** 9 + 7
# for i in range(1, n - 1):
# ans = ans * i % mod
# print(ans)
# mod = 10 ** 9 + 7
# ans = [[0] * 200020 for _ in range(10)]
# ans[0][0] = 1
# for j in range(200019):
# for i in range(9):
# ans[i + 1][j + 1] = ans[i][j]
# ans[0][j + 1] = (ans[0][j + 1] + ans[9][j]) % mod
# ans[1][j + 1] = (ans[1][j + 1] + ans[9][j]) % mod
# for _ in range(int(input())):
# n, m = list(map(int, input().split()))
# res = 0
# while n:
# x = n % 10
# for i in range(10):
# res += ans[i][m + x]
# n //= 10
# print(res % mod)
for _ in range(int(input())):
n, p = list(map(int, input().split()))
a = list(map(int, input().split()))
id = [i for i in range(n)]
id.sort(key=lambda x : a[x])
vis = [0] * n
ans = p * (n - 1)
for i in range(n):
x = id[i]
if a[x] >= p: break
if vis[x] == 1: continue
vis[x] = 1
l = x - 1
r = x + 1
while r < n and a[r] % a[x] == 0 and vis[r] == 0:
vis[r] = 1
r += 1
while l >= 0 and a[l] % a[x] == 0 and vis[l] == 0:
vis[l] = 1
l -= 1
if r > x + 1:
vis[r - 1] = 0
if l < x - 1:
vis[l + 1] = 0
ans -= (r - l - 2) * (p - a[x])
print(ans)
|
1618151700
|
[
"number theory",
"graphs"
] |
[
0,
0,
1,
0,
1,
0,
0,
0
] |
|
1 second
|
["7", "999999228"]
|
607e670403a40e4fddf389caba79607e
|
NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$.
|
You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual!
|
Output a single integer — value of given expression modulo $$$10^{9} + 9$$$.
|
The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_000.jsonl
|
be3a8a2ba6790f9107422997c89f2f4f
|
256 megabytes
|
["2 2 3 3\n+-+", "4 1 5 1\n-"]
|
PASSED
|
n, a, b, k = [int(i) for i in input().split()]
st = input()
l = (n + 1) // k
s = 0
mod = 1000000009
def f_pow(a, k):
if k == 0:
return 1
if k % 2 == 1:
return f_pow(a, k - 1) * a % mod
else:
return f_pow(a * a % mod, k // 2) % mod
def rev(b):
return f_pow(b, mod - 2)
q = f_pow(b, k) * rev(f_pow(a, k))
qn = f_pow(q, l)
rq = rev(q - 1)
g1 = f_pow(a, n)
ra = rev(a)
for i in range(len(st)):
sgn = 1 - 2 * (st[i] == '-')
res = g1 * (qn - 1) * rq
if (q % mod) != 1:
s = (s + sgn * res) % mod
else:
s = (s + sgn * g1 * l) % mod
g1 = g1 * ra * b % mod
print(s)
|
1523973900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["11\n0\n1\n1500"]
|
b65767c1ebfe72e08f58a9f9254eaa7b
|
NoteIn the first test case, Day 1: prices are $$$[2, 1, 2]$$$. You can buy all $$$3$$$ packs, since $$$2 + 1 + 2 \le 7$$$. Day 2: prices are $$$[3, 2, 3]$$$. You can't buy all $$$3$$$ packs, since $$$3 + 2 + 3 > 7$$$, so you buy only $$$2$$$ packs. Day 3: prices are $$$[4, 3, 4]$$$. You can buy $$$2$$$ packs with prices $$$4$$$ and $$$3$$$. Day 4: prices are $$$[5, 4, 5]$$$. You can't buy $$$2$$$ packs anymore, so you buy only $$$1$$$ pack. Day 5: prices are $$$[6, 5, 6]$$$. You can buy $$$1$$$ pack. Day 6: prices are $$$[7, 6, 7]$$$. You can buy $$$1$$$ pack. Day 7: prices are $$$[8, 7, 8]$$$. You still can buy $$$1$$$ pack of cost $$$7$$$. Day 8: prices are $$$[9, 8, 9]$$$. Prices are too high, so you can't buy anything. In total, you bought $$$3 + 2 + 2 + 1 + 1 + 1 + 1 = 11$$$ packs.In the second test case, prices are too high even at the first day, so you can't buy anything.In the third test case, you can buy only one pack at day one.In the fourth test case, you can buy $$$2$$$ packs first $$$500$$$ days. At day $$$501$$$ prices are $$$[501, 501]$$$, so you can buy only $$$1$$$ pack the next $$$500$$$ days. At day $$$1001$$$ prices are $$$[1001, 1001]$$$ so can't buy anymore. In total, you bought $$$500 \cdot 2 + 500 \cdot 1 = 1500$$$ packs.
|
Turbulent times are coming, so you decided to buy sugar in advance. There are $$$n$$$ shops around that sell sugar: the $$$i$$$-th shop sells one pack of sugar for $$$a_i$$$ coins, but only one pack to one customer each day. So in order to buy several packs, you need to visit several shops.Another problem is that prices are increasing each day: during the first day the cost is $$$a_i$$$, during the second day cost is $$$a_i + 1$$$, during the third day — $$$a_i + 2$$$ and so on for each shop $$$i$$$.On the contrary, your everyday budget is only $$$x$$$ coins. In other words, each day you go and buy as many packs as possible with total cost not exceeding $$$x$$$. Note that if you don't spend some amount of coins during a day, you can't use these coins during the next days.Eventually, the cost for each pack will exceed $$$x$$$, and you won't be able to buy even a single pack. So, how many packs will you be able to buy till that moment in total?
|
For each test case, print one integer — the total number of packs you will be able to buy until prices exceed your everyday budget.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le x \le 10^9$$$) — the number of shops and your everyday budget. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial cost of one pack in each shop. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_086.jsonl
|
bf32686aaadf9b405171c01a0e277ad4
|
256 megabytes
|
["4\n\n3 7\n\n2 1 2\n\n5 9\n\n10 20 30 40 50\n\n1 1\n\n1\n\n2 1000\n\n1 1"]
|
PASSED
|
import math
for i in range(int(input())):
n, x = list(map(int, input().split()))
l = sorted(list(map(int, input().split())))
ans = 0
if x >= l[0]:
s = 0
for i, a in enumerate(l):
s += a
u = math.floor((x - s) / (i + 1.0)) + 1
if u > 0:
ans += u
else:
break
print(ans)
|
1650638100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2", "1"]
|
c98abd01f026df4254bd29cbeb09dd6f
|
NoteOn the pictures below all $$$U$$$-shaped parabolas that pass through at least two given points are drawn for each of the examples. The $$$U$$$-shaped parabolas that do not have any given point inside their internal area are drawn in red. The first example. The second example.
|
Recently Vasya learned that, given two points with different $$$x$$$ coordinates, you can draw through them exactly one parabola with equation of type $$$y = x^2 + bx + c$$$, where $$$b$$$ and $$$c$$$ are reals. Let's call such a parabola an $$$U$$$-shaped one.Vasya drew several distinct points with integer coordinates on a plane and then drew an $$$U$$$-shaped parabola through each pair of the points that have different $$$x$$$ coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.The internal area of an $$$U$$$-shaped parabola is the part of the plane that lies strictly above the parabola when the $$$y$$$ axis is directed upwards.
|
In the only line print a single integer — the number of $$$U$$$-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of points. The next $$$n$$$ lines describe the points, the $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ — the coordinates of the $$$i$$$-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed $$$10^6$$$ by absolute value.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,400 |
train_022.jsonl
|
3dbd820c8760e128f1014f9a8721d661
|
256 megabytes
|
["3\n-1 0\n0 2\n1 0", "5\n1 0\n1 -1\n0 -1\n-1 0\n-1 -1"]
|
PASSED
|
import sys
def read(tp=int):
return tp(raw_input())
def readn(tp=int):
ln = raw_input().split()
return [tp(x) for x in ln]
def readf(*tp):
ln = raw_input().split()
return [x(y) for x,y in zip(tp,ln)]
################################################################################
def ori(p, q, r):
x1 = q[0] - p[0]
y1 = q[1] - p[1]
x2 = r[0] - p[0]
y2 = r[1] - p[1]
return x1 * y2 - x2 * y1
n = read()
pt = []
for i in range(n):
x, y = readn()
pt.append((x, y - x * x))
pt.sort(reverse=True)
qt = []
for p in pt:
while len(qt) >= 2 and ori(qt[-2], qt[-1], p) <= 0:
qt.pop()
qt.append(p)
if len(qt) >= 2 and qt[-1][0] == qt[-2][0]:
qt.pop()
if len(qt) < 2:
print 0
sys.exit(0)
p = qt[0]
q = qt[1]
s = 1
d = 1
for r in qt[2:]:
if ori(p, q, r) == 0:
d += 1
q = r
else:
d = 1
p = q
q = r
s += d
print s
|
1553965800
|
[
"math",
"geometry"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["4", "2"]
|
37bef742c08e1969b609e39fd6eb8f69
|
NoteIn the first example, the possible pairs $$$(r_0, r_1)$$$ are as follows: "a", "aaaaa" "aa", "aaaa" "aaaa", "aa" "aaaaa", "a" The pair "aaa", "aaa" is not allowed, since $$$r_0$$$ and $$$r_1$$$ must be different.In the second example, the following pairs are possible: "ko", "kokotlin" "koko", "tlin"
|
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $$$s$$$ towards a faraway galaxy. Recently they've received a response $$$t$$$ which they believe to be a response from aliens! The scientists now want to check if the signal $$$t$$$ is similar to $$$s$$$.The original signal $$$s$$$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $$$t$$$, however, does not look as easy as $$$s$$$, but the scientists don't give up! They represented $$$t$$$ as a sequence of English letters and say that $$$t$$$ is similar to $$$s$$$ if you can replace all zeros in $$$s$$$ with some string $$$r_0$$$ and all ones in $$$s$$$ with some other string $$$r_1$$$ and obtain $$$t$$$. The strings $$$r_0$$$ and $$$r_1$$$ must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $$$r_0$$$ and $$$r_1$$$) that transform $$$s$$$ to $$$t$$$.
|
Print a single integer — the number of pairs of strings $$$r_0$$$ and $$$r_1$$$ that transform $$$s$$$ to $$$t$$$. In case there are no such pairs, print $$$0$$$.
|
The first line contains a string $$$s$$$ ($$$2 \le |s| \le 10^5$$$) consisting of zeros and ones — the original signal. The second line contains a string $$$t$$$ ($$$1 \le |t| \le 10^6$$$) consisting of lowercase English letters only — the received signal. It is guaranteed, that the string $$$s$$$ contains at least one '0' and at least one '1'.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_052.jsonl
|
18bbeefd5aab1c0c88bcdd0ff95f7d4d
|
256 megabytes
|
["01\naaaaaa", "001\nkokokokotlin"]
|
PASSED
|
s = input()
t = input()
n,m = len(s), len(t)
a = s.count('0')
b = len(s) - a
pow = [1] * m
h = [0] * (m+1)
p, mod = 31, 10**9+9
for i in range(1, m):
pow[i] = pow[i-1] * p % mod
for i in range(m):
h[i+1] = (h[i] + (ord(t[i])-ord('a')+1) * pow[i]) % mod
def get_hash(i, j):
hash_value = (h[j] - h[i] + mod) % mod
hash_value = (hash_value * pow[m-i-1]) % mod
return hash_value
def check(x, y):
index = 0
hash_x = hash_y = -1
for i in range(n):
if s[i] == '0':
if hash_x == -1:
hash_x = get_hash(index, index+x)
else:
if get_hash(index, index+x) != hash_x: return False
index += x
else:
if hash_y == -1:
hash_y = get_hash(index, index+y)
else:
if get_hash(index, index+y) != hash_y: return False
index += y
return hash_x != hash_y
res = 0
for x in range(1, m//a+1):
if (m - a*x) % b == 0:
y = (m - a*x) // b
if y == 0: continue
if check(x ,y):
res += 1
print(res)
|
1543163700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["5\n1 2\n1 3\n2 3\n2 4\n3 4", "13\n1 2\n1 3\n2 3\n1 4\n2 4\n1 5\n2 5\n1 6\n2 6\n1 7\n1 8\n5 8\n7 8"]
|
17d29a0c2ab4e4be14fe3bdeb10d1e55
|
NoteThe first example was described in the statement.In the second example, the degrees of vertices are $$$[7, 5, 2, 2, 3, 2, 2, 3]$$$. Each of these numbers is prime. Additionally, the number of edges, $$$13$$$, is also a prime number, hence both conditions are satisfied.
|
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied: It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. The number of vertices must be exactly $$$n$$$ — a number he selected. This number is not necessarily prime. The total number of edges must be prime. The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for $$$n = 4$$$. The first graph (left one) is invalid as the degree of vertex $$$2$$$ (and $$$4$$$) equals to $$$1$$$, which is not prime. The second graph (middle one) is invalid as the total number of edges is $$$4$$$, which is not a prime number. The third graph (right one) is a valid answer for $$$n = 4$$$. Note that the graph can be disconnected.Please help Bob to find any such graph!
|
If there is no graph satisfying the conditions, print a single line containing the integer $$$-1$$$. Otherwise, first print a line containing a prime number $$$m$$$ ($$$2 \leq m \leq \frac{n(n-1)}{2}$$$) — the number of edges in the graph. Then, print $$$m$$$ lines, the $$$i$$$-th of which containing two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$) — meaning that there is an edge between vertices $$$u_i$$$ and $$$v_i$$$. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected.
|
The input consists of a single integer $$$n$$$ ($$$3 \leq n \leq 1\,000$$$) — the number of vertices.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_008.jsonl
|
427ed96879eab9aafc25e725e39f1a35
|
256 megabytes
|
["4", "8"]
|
PASSED
|
prime = [-1]*(2001)
for i in range(2,2001):
if prime[i]==-1:
for j in range(i,2001,i):
prime[j] = i
n = int(input())
e = []
for i in range(n):
e.append((i,(i+1)%n))
if prime[n]==n:
print (len(e))
for i in e:
print (i[0]+1,i[1]+1)
else:
i = 1
j = n-1
while prime[n]!=n:
e.append((i,j))
i += 1
j -= 1
n += 1
print (len(e))
for i in e:
print (i[0]+1,i[1]+1)
|
1563636900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["0.2000000000", "0.5000000000"]
|
b779946fe86b1a2a4449bc85ff887367
|
NoteIn the first sample matrix B is In the second sample matrix B is
|
The determinant of a matrix 2 × 2 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.
|
Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.
|
The first line contains two integers a and b (|a|, |b| ≤ 109), the elements of the first row of matrix A. The second line contains two integers c and d (|c|, |d| ≤ 109) the elements of the second row of matrix A.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,100 |
train_035.jsonl
|
dc8403adc103fef533d0d3a57861d6cf
|
256 megabytes
|
["1 2\n3 4", "1 0\n0 1"]
|
PASSED
|
from decimal import *
import sys
getcontext().prec = 22
a,b = map(int,sys.stdin.readline().split())
c, d = map(int,sys.stdin.readline().split())
a = Decimal(a)
b = Decimal(b)
c = Decimal(c)
d = Decimal(d)
l = Decimal(0)
r = Decimal(1000000001)
eps = Decimal(0.00000000001)
binn = Decimal(2)
while(r - l >= eps):
mid = (l + r) / binn
as1 = (a - mid) * (d - mid);
as2 = (a - mid) * (d + mid);
as3 = (a + mid) * (d - mid);
as4 = (a + mid) * (d + mid);
mx1 = max(as1, max(as2, max(as3, as4)));
mn1 = min(as1, min(as2, min(as3, as4)));
as1 = (b - mid) * (c - mid);
as2 = (b - mid) * (c + mid);
as3 = (b + mid) * (c - mid);
as4 = (b + mid) * (c + mid);
mx2 = max(as1, max(as2, max(as3, as4)));
mn2 = min(as1, min(as2, min(as3, as4)));
if (mx1 < mn2 or mn1 > mx2):
l = mid
else :
r = mid
print Decimal(l)
|
1433595600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["50\n46\n10\n26\n35184372088846"]
|
f5de1e9b059bddf8f8dd46c18ce12683
|
NoteIn the first example test case the optimal sequence would be: Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{4}{2} = 2$$$ and $$$a_1 = 6 \cdot 2 = 12$$$, making the array look as: [12, 2, 2]. Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{2}{2} = 1$$$ and $$$a_1 = 12 \cdot 2 = 24$$$, making the array look as: [24, 1, 2]. Pick $$$i = 3$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_3 = \frac{2}{2} = 1$$$ and $$$a_1 = 24 \cdot 2 = 48$$$, making the array look as: [48, 1, 1]. The final answer $$$48 + 1 + 1 = 50$$$.In the third example test case there is no way to change the sum of elements, so the answer is $$$10$$$.
|
William has array of $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. He can perform the following sequence of operations any number of times: Pick any two items from array $$$a_i$$$ and $$$a_j$$$, where $$$a_i$$$ must be a multiple of $$$2$$$ $$$a_i = \frac{a_i}{2}$$$ $$$a_j = a_j \cdot 2$$$ Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.
|
For each test case output the maximal sum of array elements after performing an optimal sequence of operations.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 15)$$$, the number of elements in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i < 16)$$$, the contents of William's array.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 900 |
train_110.jsonl
|
38a0869ec21bae34fb76186bbeefbbdb
|
256 megabytes
|
["5\n3\n6 4 2\n5\n1 2 3 4 5\n1\n10\n3\n2 3 4\n15\n8 8 8 8 8 8 8 8 8 8 8 8 8 8 8"]
|
PASSED
|
# import math
# for i in range(int(input())):
# n = int(input())
# if n % 2 == 0 and math.sqrt(n//2) == int(math.sqrt(n//2)):
# print("YES")
# elif n % 4 == 0 and math.sqrt(n//4) == int(math.sqrt(n//4)):
# print("YES")
# else:
# print('NO')
##for i in range(int(input())):
## t = int(input())
## x = t // 6
## y = t // 4
## if t >= 4 and t % 2 ==0:
## if t % 6 == 2 or t % 6 == 4:
## x += 1
## print(int(x), int(y))
## else:
## print(-1)
import math
for i in range(int(input())):
n = int(input())
a = [int(t) for t in input().split()]
m = 0
n2 = 0
for n in range(len(a)):
n2 = a[n]
while n2 % 2 == 0 and n2 > 0:
m += 1
n2 //= 2
a[n] = n2
print(max(a)*2**m+(sum(a)-max(a)))
|
1638110100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["303", "25", "60"]
|
39dbd405be19c5a56c2b97b28e0edf06
|
NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).
|
Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.
|
In the first line print the maximum possible value of an expression.
|
The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs + and * . The number of signs * doesn't exceed 15.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,100 |
train_005.jsonl
|
4a4c14e78ddbf5f4e4ad1ee279e57229
|
256 megabytes
|
["3+5*7+8*4", "2+3*5", "3*4*5"]
|
PASSED
|
n = raw_input()
ans = 0
a = [-1]
for i in xrange(len(n)):
if n[i]=='*':a.append(i)
a.append(len(n))
for i in a:
for j in a:
if j>i:
ans = max(ans,eval(n[:i+1]+'('+n[i+1:j]+')'+n[j:]))
ans = max(ans,eval(n))
print ans
|
1434645000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["4\n0\n2"]
|
14ce451a31c0dbc2b2f4e04a939b199d
|
NoteIn the first test case, the following combinations of pairs fit: $$$(1, 2)$$$ and $$$(3, 4)$$$; $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(1, 3)$$$ and $$$(3, 4)$$$; $$$(2, 2)$$$ and $$$(3, 4)$$$. There is only one pair in the second test case.In the third test case, the following combinations of pairs fit: $$$(1, 1)$$$ and $$$(2, 2)$$$; $$$(1, 2)$$$ and $$$(2, 1)$$$.
|
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.Each class must present two couples to the ball. In Vasya's class, $$$a$$$ boys and $$$b$$$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs.Formally, you know $$$k$$$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.For example, if $$$a=3$$$, $$$b=4$$$, $$$k=4$$$ and the couples $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(3, 4)$$$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(3, 4)$$$ and $$$(1, 3)$$$; But the following combinations are not possible: $$$(1, 3)$$$ and $$$(1, 2)$$$ — the first boy enters two pairs; $$$(1, 2)$$$ and $$$(2, 2)$$$ — the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.
|
For each test case, on a separate line print one integer — the number of ways to choose two pairs that match the condition above.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 \le a, b, k \le 2 \cdot 10^5$$$) — the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains $$$k$$$ integers $$$a_1, a_2, \ldots a_k$$$. ($$$1 \le a_i \le a$$$), where $$$a_i$$$ is the number of the boy in the pair with the number $$$i$$$. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \ldots b_k$$$. ($$$1 \le b_i \le b$$$), where $$$b_i$$$ is the number of the girl in the pair with the number $$$i$$$. It is guaranteed that the sums of $$$a$$$, $$$b$$$, and $$$k$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that each pair is specified at most once in one test case.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_086.jsonl
|
9918b9e83cdf5f85e4f12502b8968a7e
|
256 megabytes
|
["3\n3 4 4\n1 1 2 3\n2 3 2 4\n1 1 1\n1\n1\n2 2 4\n1 1 2 2\n1 2 1 2"]
|
PASSED
|
from sys import stdin, stdout
I = stdin.readline
O = stdout.write
# n = int(I())
# arr = list(map(int, I().split()))
cntA = [0] * 200005
cntB = [0] * 200005
def solve():
a, b, k = map(int,(input().split()))
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
for i in range(a+1):
cntA[i]=0
for i in range(b+1):
cntB[i]=0
for i in range(k):
cntA[arr[i]]+=1
cntB[brr[i]]+=1
ans=0
for i in range(k):
ans+=(k - cntA[arr[i]] - cntB[brr[i]] + 1)/2
print(int(ans))
for tc in range(int(input())):
solve()
|
1611586800
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n0\n4\n2\n1\n3"]
|
e9065e8bd9afb7d797527bc3a50f2150
|
NoteIn the first test case, Bob can't win on subsegments of length $$$1$$$, as there is no pair of adjacent piles in an array of length $$$1$$$.In the second test case, every subsegment is not winning.In the fourth test case, the subsegment $$$[1, 4]$$$ is winning, because Bob can make moves with pairs of adjacent piles: $$$(2, 3)$$$, $$$(1, 2)$$$, $$$(3, 4)$$$. Another winning subsegment is $$$[2, 3]$$$.
|
Bob decided to take a break from calculus homework and designed a game for himself. The game is played on a sequence of piles of stones, which can be described with a sequence of integers $$$s_1, \ldots, s_k$$$, where $$$s_i$$$ is the number of stones in the $$$i$$$-th pile. On each turn, Bob picks a pair of non-empty adjacent piles $$$i$$$ and $$$i+1$$$ and takes one stone from each. If a pile becomes empty, its adjacent piles do not become adjacent. The game ends when Bob can't make turns anymore. Bob considers himself a winner if at the end all piles are empty.We consider a sequence of piles winning if Bob can start with it and win with some sequence of moves.You are given a sequence $$$a_1, \ldots, a_n$$$, count the number of subsegments of $$$a$$$ that describe a winning sequence of piles. In other words find the number of segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$), such that the sequence $$$a_l, a_{l+1}, \ldots, a_r$$$ is winning.
|
Print a single integer for each test case — the answer to the problem.
|
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_091.jsonl
|
70ab0197ded3ece87b6151529d2d643d
|
256 megabytes
|
["6\n2\n2 2\n3\n1 2 3\n4\n1 1 1 1\n4\n1 2 2 1\n4\n1 2 1 2\n8\n1 2 1 2 1 2 1 2"]
|
PASSED
|
''' E. Game with Stones
https://codeforces.com/contest/1589/problem/E
'''
import io, os, sys
from math import e
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
import random
random.seed(123)
class Node:
def __init__(self, val, priority):
self.val = val
self.priority = priority
self.count = 1
self.left = None
self.right = None
def __repr__(self):
return f'Node(val={self.val}, count={self.count})'
class Treap:
'''Multiset treap, all nodes hold unique values'''
def __init__(self):
self.root = None
self.size = 0
def _rand(self):
return random.randint(1,2**32)
def find(self, val):
'''find node holding val'''
node = self.root
while node:
if node.val == val: break
node = node.left if node.val > val else node.right
return node
@bootstrap
def split(self, root, val):
'''split subtree rooted here into 2 treaps: one < val, one >= val'''
if not root: yield (None, None)
if root.val < val:
x, y = yield self.split(root.right, val)
root.right = x
yield (root, y)
else:
x, y = yield self.split(root.left, val)
root.left = y
yield (x, root)
@bootstrap
def merge(self, x, y):
'''merge 2 treaps into new treap, assuming x vals <= y vals'''
if not x or not y: yield x or y
if x.priority > y.priority: # make x root
x.right = yield self.merge(x.right, y)
yield x
else:
y.left = yield self.merge(x, y.left)
yield y
def insert(self, val):
'''split current tree, then merge 2 trees with new node'''
node = self.find(val)
if node is not None:
node.count += 1
else:
y = Node(val, self._rand())
x, z = self.split(self.root, val)
self.root = self.merge(self.merge(x, y), z)
self.size += 1
def delete(self, val, del_all=False):
'''delete node with val, assuming int val'''
node = self.find(val)
if not node: return
if not del_all and node.count > 1:
node.count -= 1
self.size -= 1
else: # remove entire node
x, y = self.split(self.root, val)
y, z = self.split(y, val+1)
self.root = self.merge(x, z)
self.size -= node.count
def get_min(self):
'''get min value'''
node = self.root
while node.left:
node = node.left
return node.val
def get_max(self):
'''get max value'''
node = self.root
while node.right:
node = node.right
return node.val
def get_count(self, val):
'''get num nodes with val'''
node = self.find(val)
return 0 if not node else node.count
# let S(l, r) = a[r] - a[r-1] + a[r-2] - ... + (-1)^(r-l) * a[l]
# then a[l..r] is winning if S(l, m) >= 0 and S(l, r) == 0 for m=l..r
# iterate i=1..N and track set of valid prefixes / potential segment starts
# * add S(1, i) to prefix set
# * remove all prefixes S(1, l) s.t. S(l, r) < 0; note S(l, r) = S(r, 1) - (-1)^(r-l) * S(l-1, 1)
# -> if S(1, l) remains, then S(i, l) >= 0 for i=l+1..r
# * num winning segments ending at r is num l s.t. S(l, r) == 0
def solve_treap(N, nums):
# set of valid prefixes with even/odd length
pref = [Treap(), Treap()]
pref[0].insert(0)
# running prefix
res = p = 0
for i, num in enumerate(nums):
p = num - p
sign, rsign = (i+1) % 2, i % 2
# remove invalid prefixes
while pref[sign].size > 0:
mx = pref[sign].get_max()
if p - mx >= 0: break
pref[sign].delete(mx, del_all=True)
while pref[rsign].size > 0:
mn = pref[rsign].get_min()
if p + mn >= 0: break
pref[rsign].delete(mn, del_all=True)
# num winning segs ending at i
res += pref[sign].get_count(p)
res += pref[rsign].get_count(-p)
# add current sum
pref[sign].insert(p)
return res
from collections import deque
def solve_deque(N, nums):
dq1, dq2 = deque([[0, 1]]), deque() # (pref, count)
res = p = 0
for num in nums:
p = num - p
# remove invalid prefixes
while dq1 and p - dq1[-1][0] < 0:
dq1.pop()
while dq2 and p + dq2[0][0] < 0:
dq2.popleft()
# num winning segs ending at i
if dq1 and p - dq1[-1][0] == 0:
res += dq1[-1][1]
if dq2 and p + dq2[0][0] == 0:
res += dq2[0][1]
# add current sum
# note p >= all remaining vals in dq1
# so dq1 and dq2 are both increasing deque
if dq1 and dq1[-1][0] == p:
dq1[-1][1] += 1
else:
dq1.append([p, 1])
dq1, dq2 = dq2, dq1
return res
solve = solve_deque
def main():
T = int(input())
for _ in range(T):
N = int(input())
nums = list(map(int, input().split()))
out = solve(N, nums)
output(f'{out}\n')
if __name__ == '__main__':
main()
|
1636869900
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n1 5 11 9\n2 5 7 6\n0"]
|
8b2b7208630af1d086420513a437a914
|
NoteConsider the first test case.Initially $$$a = [9, 6, 3, 11, 15]$$$.In the first operation replace $$$a_1$$$ with $$$11$$$ and $$$a_5$$$ with $$$9$$$. It's valid, because $$$\min{(a_1, a_5)} = \min{(11, 9)} = 9$$$.After this $$$a = [11, 6, 3, 11, 9]$$$.In the second operation replace $$$a_2$$$ with $$$7$$$ and $$$a_5$$$ with $$$6$$$. It's valid, because $$$\min{(a_2, a_5)} = \min{(7, 6)} = 6$$$.After this $$$a = [11, 7, 3, 11, 6]$$$ — a good array.In the second test case, the initial array is already good.
|
Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.
|
For each of $$$t$$$ test cases print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations. You don't need to minimize this number. In each of the next $$$k$$$ lines print $$$4$$$ integers $$$i$$$, $$$j$$$, $$$x$$$, $$$y$$$ ($$$1 \le i \neq j \le n$$$, $$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$ — in this manner you replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. If there are multiple answers, print any.
|
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 length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the array which Nastia has received as a gift. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_099.jsonl
|
4b7b9ffdfc81ffac5cf28df3df1afdb7
|
256 megabytes
|
["2\n5\n9 6 3 11 15\n3\n7 5 13"]
|
PASSED
|
import sys
import math
from collections import defaultdict,Counter
from itertools import permutations
from collections import deque
from decimal import Decimal
from fractions import Fraction
from heapq import heappush , heappop
import bisect
def sin():
return int(sys.stdin.readline())
def array():
return list(map(int, sys.stdin.readline().strip().split()))
def two():
return map(int, sys.stdin.readline().strip().split())
def multiple():
return [int(x) for x in sys.stdin.readline().split()]
def string():
return sys.stdin.readline().strip()
def sqrt(x):
low , high = 0 , x
while low <= high:
mid = (low + high) // 2
if mid * mid <= x < (mid+1) * (mid+1):
return mid
elif x < mid * mid:
high = mid - 1
else:
low = mid + 1
t = sin()
for _ in range(t):
n = sin()
arr = array()
k = 1999999974
ans = []
mini = k
if n == 1:
print(0)
continue
for i in range(1 , n):
mini = min(arr[i-1] , arr[i])
arr[i-1] = k
arr[i] = mini
ans.append([i , i+1 , k , mini])
k -= 1
if math.gcd(arr[n-2] , arr[n-1]) != 1:
ans.append([1 , n , mini , k])
print(len(ans))
for i in ans:
print(*i)
#print(arr)
|
1620398100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["3\n1 2 3", "4\n3 4 1 2"]
|
250c0e647d0f2ff6d86db01675192c9f
| null |
You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v1, v2, ..., vd such, that nodes v1 and vd are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes vi and vi + 1 are connected by an edge of the graph.
|
In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v1, v2, ..., vr (1 ≤ vi ≤ n) — the found simple cycle. It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them.
|
The first line contains three integers n, m, k (3 ≤ n, m ≤ 105; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the indexes of the graph nodes that are connected by the i-th edge. It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_018.jsonl
|
aac2d18d7934d1627c06c48ab65200ef
|
256 megabytes
|
["3 3 2\n1 2\n2 3\n3 1", "4 6 3\n4 3\n1 2\n1 3\n1 4\n2 3\n2 4"]
|
PASSED
|
r = lambda: map(int, raw_input().split())
n, m, k = r()
e = [[] for _ in xrange(n + 1)]
for _ in xrange(m):
a, b = r()
e[a].append(b)
e[b].append(a)
flag = [-1] * (n + 1)
path = []
x, l = 1, 0
while True:
path.append(x)
flag[x] = l
l += 1
for y in e[x]:
if flag[y] == -1:
x = y
break
else:
id = path.index(min(e[x], key = lambda s: flag[s]))
print len(path) - id
print ' '.join(map(str, path[id:]))
break
|
1358350200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["2 3\n2 1\n1 1 1", "1 1\n20\n3"]
|
01ac609133428a0074e8506786096e02
|
NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.
|
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.
|
Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout, mout must satisfy the inequality 1 ≤ nout, mout ≤ 105, and the actual values in the sets aout, i and bout, i must satisfy the inequality 1 ≤ aout, i, bout, i ≤ 107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (x > 1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them.
|
The first input line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 107) — the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1, b2, ..., bm (1 ≤ bi ≤ 107) — the numbers that are multiplied to produce the denominator.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_079.jsonl
|
e58e72f702be5a3686204ab3c424c4ef
|
256 megabytes
|
["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"]
|
PASSED
|
import math as mt
from sys import stdin,stdout
MAXN = 10000001
spf = [0]*(MAXN)
def sieve():
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, mt.ceil(mt.sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
def getFactorization(x):
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
sieve()
def help():
a,b = map(int,stdin.readline().split(" "))
num = list(map(int,stdin.readline().split(" ")))
den = list(map(int,stdin.readline().split(" ")))
spfn = [0]*(MAXN)
for i in range(b):
temp = getFactorization(den[i])
for j in temp:
spfn[j]-=1
spfn_den = [0]*(MAXN)
for i in range(a):
temp = getFactorization(num[i])
for j in temp:
if(spfn[j]<0):
spfn[j]+=1
spfn_den[j] -= 1
num[i] = num[i]//j
for i in range(b):
temp = getFactorization(den[i])
for j in temp:
if(spfn_den[j]<0):
spfn_den[j] += 1
den[i] = den[i]//j
stdout.write(str(a)+" "+str(b)+"\n")
for i in range(a):
stdout.write(str(num[i])+" ")
stdout.write("\n")
for i in range(b):
stdout.write(str(den[i])+" ")
stdout.write("\n")
help()
|
1347291900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["111110\n1 0 0 2 0 0 \n111110\n0 1 1 1 0 1 \n000000\n0 0 0 0 0 0 \n100110\n1 0 0 0 0 0 \n111111\n1 2 1 3 0 4 \n111110\n1 1 4 2 0 4"]
|
38375efafa4861f3443126f20cacf3ae
|
NoteHere is the explanation for the first testcase. Each step shows how the binary string changes in a move. Choose bit $$$1$$$: $$$\color{red}{\underline{1}00001} \rightarrow \color{red}{\underline{1}}\color{blue}{11110}$$$. Choose bit $$$4$$$: $$$\color{red}{111\underline{1}10} \rightarrow \color{blue}{000}\color{red}{\underline{1}}\color{blue}{01}$$$. Choose bit $$$4$$$: $$$\color{red}{000\underline{1}01} \rightarrow \color{blue}{111}\color{red}{\underline{1}}\color{blue}{10}$$$. The final string is $$$111110$$$ and this is the lexicographically largest string we can get.
|
You are given a binary string of length $$$n$$$. You have exactly $$$k$$$ moves. In one move, you must select a single bit. The state of all bits except that bit will get flipped ($$$0$$$ becomes $$$1$$$, $$$1$$$ becomes $$$0$$$). You need to output the lexicographically largest string that you can get after using all $$$k$$$ moves. Also, output the number of times you will select each bit. If there are multiple ways to do this, you may output any of them.A binary string $$$a$$$ is lexicographically larger than a binary string $$$b$$$ of the same length, if and only if the following holds: in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ contains a $$$1$$$, and the string $$$b$$$ contains a $$$0$$$.
|
For each test case, output two lines. The first line should contain the lexicographically largest string you can obtain. The second line should contain $$$n$$$ integers $$$f_1, f_2, \ldots, f_n$$$, where $$$f_i$$$ is the number of times the $$$i$$$-th bit is selected. The sum of all the integers must be equal to $$$k$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case has two lines. The first line has two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$0 \leq k \leq 10^9$$$). The second line has a binary string of length $$$n$$$, each character is either $$$0$$$ or $$$1$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_110.jsonl
|
fd454fc166a3964aa2869f9f990c7762
|
256 megabytes
|
["6\n\n6 3\n\n100001\n\n6 4\n\n100011\n\n6 0\n\n000000\n\n6 1\n\n111001\n\n6 11\n\n101100\n\n6 12\n\n001110"]
|
PASSED
|
I=input
for _ in[0]*int(I()):
n,k=map(int,I().split());a=[int(x)^k&1for x in I()];b=[0]*n;i=0
while(n-i)*k:b[i]=a[i]^1;a[i]=1;k-=b[i];i+=1
a[-1]^=k&1;b[-1]+=k;print(*a,sep='');print(*b)
|
1650206100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["0\n4\n21"]
|
935bceb69117d06eb75121c805bff69c
|
NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.
|
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.
|
For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.
|
The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$). 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
| 900 |
train_091.jsonl
|
181c34b71f1b0cce381ff6e9e98f5ec9
|
256 megabytes
|
["3\n3\n1 2 3\n4\n0 1 1 0\n10\n8 3 6 11 5 2 1 7 10 4"]
|
PASSED
|
import sys
input = lambda: sys.stdin.buffer.readline().decode().strip()
print = sys.stdout.write
for _ in range(int(input())):
n = int(input())
nums = list(map(int, input().split()))
total = sum(nums)
reminder = total % n
print(str((n - reminder) * reminder) + "\n")
|
1625668500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["volga", "no", "baba"]
|
2a414730d1bc7eef50bdb631ea966366
|
NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.
|
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.
|
Print the word that Polycarp encoded.
|
The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 900 |
train_002.jsonl
|
8580285f81fdd6b80bac0074e6da18e9
|
256 megabytes
|
["5\nlogva", "2\nno", "4\nabba"]
|
PASSED
|
n=input()
s=raw_input()
t=s[::2][::-1]+s[1::2]
if n%2:t=t[::-1]
print t
|
1482057300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1 2 2 3\n4 1 4 4\n3 1 1 5\n5 1 1 1\n1 1 2 1\n1 1 1 1\n50 1 1 1000000000"]
|
5aae6b27f35852512a250751ef957ab9
|
NoteHere is a visualization of the first test case.
|
Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with $$$n$$$ rows and $$$m$$$ columns. Let $$$(i, j)$$$ denote the cell in row $$$i$$$ and column $$$j$$$. Anton is currently standing at position $$$(i, j)$$$ in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to $$$(i, j)$$$ by travelling only to adjacent by side cells. That is, if he is in cell $$$(x, y)$$$ then he can travel to the cells $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ and $$$(x, y - 1)$$$ in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.
|
For each test case, print four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1\le y_1, y_2\le m$$$) — the coordinates of where the two yo-yos should be thrown. They will be thrown at coordinates $$$(x_1,y_1)$$$ and $$$(x_2,y_2)$$$. If there are multiple answers, you may print any.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of each test case contains four integers $$$n$$$, $$$m$$$, $$$i$$$, $$$j$$$ ($$$1 \leq n, m \leq 10^9$$$, $$$1\le i\le n$$$, $$$1\le j\le m$$$) — the dimensions of the room, and the cell at which Anton is currently standing.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_084.jsonl
|
a066260df29628fb10bce33fc3e7297f
|
256 megabytes
|
["7\n2 3 1 1\n4 4 1 2\n3 5 2 2\n5 1 2 1\n3 1 3 1\n1 1 1 1\n1000000000 1000000000 1000000000 50"]
|
PASSED
|
t = int(input())
for _ in range(t):
n, m, y, x = map(int, input().split())
if x <= round(m/2):
print(n, m, 1, 1)
else:
print(n, 1, 1, m)
|
1624026900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["-1\n1\n2\n2\n2\n1"]
|
3dc5850220458dec9876560150b612c4
|
NoteIn the first test case, there is no possible $$$m$$$, because all elements of all arrays should be equal to $$$0$$$. But in this case, it is impossible to get $$$a_4 = 1$$$ as the sum of zeros.In the second test case, we can take $$$b_1 = [3, 3, 3]$$$. $$$1$$$ is the smallest possible value of $$$m$$$.In the third test case, we can take $$$b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$$$ and $$$b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$$$. It's easy to see, that $$$a_i = b_{1, i} + b_{2, i}$$$ for all $$$i$$$ and the number of different elements in $$$b_1$$$ and in $$$b_2$$$ is equal to $$$3$$$ (so it is at most $$$3$$$). It can be proven that $$$2$$$ is the smallest possible value of $$$m$$$.
|
You are given a non-decreasing array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Also you are given a positive integer $$$k$$$.You want to find $$$m$$$ non-decreasing arrays of non-negative integers $$$b_1, b_2, \ldots, b_m$$$, such that: The size of $$$b_i$$$ is equal to $$$n$$$ for all $$$1 \leq i \leq m$$$. For all $$$1 \leq j \leq n$$$, $$$a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$$$. In the other word, array $$$a$$$ is the sum of arrays $$$b_i$$$. The number of different elements in the array $$$b_i$$$ is at most $$$k$$$ for all $$$1 \leq i \leq m$$$. Find the minimum possible value of $$$m$$$, or report that there is no possible $$$m$$$.
|
For each test case print a single integer: the minimum possible value of $$$m$$$. If there is no such $$$m$$$, print $$$-1$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n \leq 100$$$, $$$1 \leq k \leq n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$$$, $$$a_n > 0$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_011.jsonl
|
6559ce04c65fa8337a20b6d94153b9dd
|
256 megabytes
|
["6\n4 1\n0 0 0 1\n3 1\n3 3 3\n11 3\n0 1 2 2 3 3 3 4 4 4 4\n5 3\n1 2 3 4 5\n9 4\n2 2 3 5 7 11 13 13 17\n10 7\n0 1 1 2 3 3 4 5 5 6"]
|
PASSED
|
import math
test = int(input())
for q in range(test):
n,k = map(int,input().split())
a = list(map(int,input().split()))
x = set()
if k==1:
if a[0]!=a[n-1]:
print(-1)
continue
else:
print(1)
continue
ans = 0
i = 0
while i<n:
x.add(a[i])
if len(x)==k+1:
x = set()
x.add(a[i])
ans = 1
break
i+=1
if i==n:
print(1)
continue
for j in range(i,n):
x.add(a[j])
ans += math.ceil(len(x)/(k-1))
print(ans)
|
1601476500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n1\n1\n0\n2\n500000000"]
|
8a1ceac1440f7cb406f12d9fc2ca0e20
|
NoteIn the first test case of the example, two teams can be composed. One way to compose two teams is to compose two teams of $$$2$$$ programmers and $$$2$$$ mathematicians.In the second test case of the example, only one team can be composed: $$$3$$$ programmers and $$$1$$$ mathematician in the team.
|
The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate.There are $$$a$$$ programmers and $$$b$$$ mathematicians at Berland State University. How many maximum teams can be made if: each team must consist of exactly $$$4$$$ students, teams of $$$4$$$ mathematicians or $$$4$$$ programmers are unlikely to perform well, so the decision was made not to compose such teams. Thus, each team must have at least one programmer and at least one mathematician.Print the required maximum number of teams. Each person can be a member of no more than one team.
|
Print $$$t$$$ lines. Each line must contain the answer to the corresponding set of input data — the required maximum number of teams.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. This is followed by descriptions of $$$t$$$ sets, one per line. Each set is given by two integers $$$a$$$ and $$$b$$$ ($$$0 \le a,b \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_093.jsonl
|
14398edafa7fdb83898db276cd10be83
|
256 megabytes
|
["6\n5 5\n10 1\n2 3\n0 0\n17 2\n1000000000 1000000000"]
|
PASSED
|
from sys import stdin, stdout
t = int(stdin.readline())
for i in range(t):
a, b = map(int, stdin.readline().strip().split())
teams=0
if a==b:
teams += (a+b)//4
else:
max_one = max(a, b)
min_one = min(a, b)
m_p_pairs = min_one
max_one-=min_one
min_one = 0
m_m_pairs = max_one//2
if m_m_pairs>=m_p_pairs:
teams+=m_p_pairs
else:
teams+=m_m_pairs
m_p_pairs-=m_m_pairs
teams+=m_p_pairs//2
stdout.write(f"{teams}\n")
|
1637850900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["cadb\ngg\ncodfoerces\nNo answer"]
|
d62d0a9d827444a671029407f6a4ad39
|
NoteIn the first example answer "bdac" is also correct.The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.There are lots of valid answers for the third example.
|
You are given a string, consisting of lowercase Latin letters.A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions $$$(1, 2)$$$ — "ab" and $$$(2, 3)$$$ — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.You also have to answer $$$T$$$ separate queries.
|
Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th query. If the answer for the $$$i$$$-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same. If there are multiple answers, print any of them. Otherwise print "No answer" for that query.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Each of the next $$$T$$$ lines contains string $$$s$$$ $$$(1 \le |s| \le 100)$$$ — the string for the next query. It is guaranteed that it contains only lowercase Latin letters. Note that in hacks you have to set $$$T = 1$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_016.jsonl
|
2cad658f31049589fa58a0c5ec188842
|
256 megabytes
|
["4\nabcd\ngg\ncodeforces\nabaca"]
|
PASSED
|
import collections
def add1(c):
return chr(ord(c)+1)
def sv():
m = collections.defaultdict(int)
for c in input():
m[c] += 1
m = list(m.items())
m.sort()
if len(m) == 2 and add1(m[0][0]) == m[1][0]: return False
if len(m) == 3:
if add1(m[0][0]) != m[1][0]:
pass
elif add1(m[1][0]) != m[2][0]:
m[0], m[2] = m[2], m[0]
else:
return False
for i in range(1,len(m),2):
print(m[i][0]*m[i][1], end='')
for i in range(0,len(m),2):
print(m[i][0]*m[i][1], end='')
print()
return True
TC = int(input())
for tc in range(TC):
if not sv(): print('No answer')
|
1556721300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["8", "7", "6"]
|
e849aa63710c817aac610a1deeb366c5
| null |
You are given an array $$$a_1, a_2, \ldots, a_n$$$ and an integer $$$x$$$.Find the number of non-empty subsets of indices of this array $$$1 \leq b_1 < b_2 < \ldots < b_k \leq n$$$, such that for all pairs $$$(i, j)$$$ where $$$1 \leq i < j \leq k$$$, the inequality $$$a_{b_i} \oplus a_{b_j} \leq x$$$ is held. Here, $$$\oplus$$$ denotes the bitwise XOR operation. As the answer may be very large, output it modulo $$$998\,244\,353$$$.
|
Print one integer: the number of non-empty subsets such that the bitwise XOR of every pair of elements is at most $$$x$$$, modulo $$$998\,244\,353$$$.
|
The first line of the input contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 150\,000$$$, $$$0 \leq x < 2^{30}$$$). Here, $$$n$$$ is the size of the array. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{30}$$$): the array itself.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,000 |
train_101.jsonl
|
b4ca7c994a12b253b23b565dce7edacd
|
256 megabytes
|
["4 2\n0 1 2 3", "3 6\n4 2 2", "4 0\n1 1 2 2"]
|
PASSED
|
I=lambda:[*map(int,input().split())]
M=998244353
n,X=I()
a=I()
q=lambda x:pow(2,x,M)-1
E=len
B=lambda a,H:[[z for z in a if z>>H&1==d]for d in[0,1]]
def f(a,b,i):
if i<0 or[]in[a,b]:return q(E(a))*q(E(b))
w,x=B(a,i);y,z=B(b,i);return(f(x,y,i-1)+q(E(x))+q(E(y))+1)*(f(w,z,i-1)+q(E(w))+q(E(z))+1)-q(E(a))-q(E(b))-1 if X>>i&1 else f(x,z,i-1)+f(w,y,i-1)
def F(a,i):
if i<0 or[]==a:return q(E(a))
x,y=B(a,i);return q(E(x))+q(E(y))+f(x,y,i-1)if X>>i&1 else F(x,i-1)+F(y,i-1)
print(F(a,29)%M)
|
1640792100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n3", "2\n1 2", "0"]
|
ce19cc45bbe24177155ce87dfe9d5c22
|
NoteIn the first example, $$$3$$$ is the only possible answer. In the second example, there are $$$2$$$ possible answers. In the third example, the tree can't be generated by McDic's generation.
|
You have an integer $$$n$$$. Let's define following tree generation as McDic's generation: Make a complete and full binary tree of $$$2^{n} - 1$$$ vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. Select a non-root vertex $$$v$$$ from that binary tree. Remove $$$v$$$ from tree and make new edges between $$$v$$$'s parent and $$$v$$$'s direct children. If $$$v$$$ has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.
|
Print two lines. In the first line, print a single integer — the number of answers. If given tree cannot be made by McDic's generation, then print $$$0$$$. In the second line, print all possible answers in ascending order, separated by spaces. If the given tree cannot be made by McDic's generation, then don't print anything.
|
The first line contains integer $$$n$$$ ($$$2 \le n \le 17$$$). The $$$i$$$-th of the next $$$2^{n} - 3$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le 2^{n} - 2$$$) — meaning there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. It is guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_053.jsonl
|
eddc88ff772193c203afec5e9195f864
|
256 megabytes
|
["4\n1 2\n1 3\n2 4\n2 5\n3 6\n3 13\n3 14\n4 7\n4 8\n5 9\n5 10\n6 11\n6 12", "2\n1 2", "3\n1 2\n2 3\n3 4\n4 5\n5 6"]
|
PASSED
|
#!/usr/bin/python3
import array
import math
import os
import sys
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
def solve(N, M, G):
if N == 2:
return [0, 1]
degv = [set() for _ in range(5)]
for i in range(M):
d = len(G[i])
if d == 0 or d >= 5:
return []
degv[d].add(i)
layer_vcount = 1 << (N - 1)
vs = degv[1]
levels = bytearray(M)
ans = []
for level in range(1, N):
#dprint('level', level, [x for x in levels])
#dprint('vs', vs)
#dprint('layer_vcount', layer_vcount)
if len(vs) not in (layer_vcount - 1, layer_vcount):
return []
if len(vs) == layer_vcount - 1:
if ans:
return []
if level == 1:
sp_deg_off = -1
else:
sp_deg_off = 1
else:
sp_deg_off = 0
#dprint('sp_deg_off', sp_deg_off)
ndeg = 3 if level < N - 1 else 2
us = set()
ss = set()
for v in vs:
#dprint('v', v)
levels[v] = level
p = None
for u in G[v]:
if levels[u] == 0:
if p is not None:
return []
p = u
break
#dprint(' p', p)
if p is None:
return []
deg = len(G[p])
#dprint(' deg', deg)
if deg == ndeg:
us.add(p)
elif deg == ndeg + sp_deg_off:
ss.add(p)
elif sp_deg_off == 0 and deg == ndeg + 1:
ss.add(p)
else:
return []
#dprint('us', us)
#dprint('ss', ss)
if sp_deg_off != 0:
if len(ss) != 1:
return []
(sp,) = list(ss)
ans = [sp]
us.add(sp)
if sp_deg_off == 0:
if level == N - 2:
if ss:
return []
if not ans:
li = list(us)
li.sort()
return li
if len(ss) > 1:
return []
vs = us
layer_vcount >>= 1
return ans
def main():
N = int(inp())
M = (1 << N) - 2
G = [[] for _ in range(M)]
for _ in range(M - 1):
a, b = [int(e) - 1 for e in inp().split()]
G[a].append(b)
G[b].append(a)
ans = solve(N, M, G)
print(len(ans))
if ans:
print(*[v + 1 for v in ans])
if __name__ == '__main__':
main()
|
1569762300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["? 0\n\n? 1\n\n! 1", "? 2\n\n? 1\n\n? 0\n\n! -1"]
|
b26140f647eee09f5f0d6c428d99126d
|
NoteThe polynomial in the first sample is $$$1000002 + x^2$$$.The polynomial in the second sample is $$$1 + x^2$$$.
|
Jury picked a polynomial $$$f(x) = a_0 + a_1 \cdot x + a_2 \cdot x^2 + \dots + a_k \cdot x^k$$$. $$$k \le 10$$$ and all $$$a_i$$$ are integer numbers and $$$0 \le a_i < 10^6 + 3$$$. It's guaranteed that there is at least one $$$i$$$ such that $$$a_i > 0$$$.Now jury wants you to find such an integer $$$x_0$$$ that $$$f(x_0) \equiv 0 \mod (10^6 + 3)$$$ or report that there is not such $$$x_0$$$.You can ask no more than $$$50$$$ queries: you ask value $$$x_q$$$ and jury tells you value $$$f(x_q) \mod (10^6 + 3)$$$.Note that printing the answer doesn't count as a query.
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_072.jsonl
|
f12c1b3b780a5d9698537ea8a5b24b63
|
256 megabytes
|
["1000002\n\n0", "5\n\n2\n\n1"]
|
PASSED
|
def main():
seed = []
for i in range(11):
print('?', i)
seed.append(int(input()))
if not seed[-1]:
print('!', i)
return
poly = [seed[-1]]
for _ in range(10):
seed = [(b - a) % 1000003 for a, b in zip(seed, seed[1:])]
poly.append(seed[-1])
a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa = poly
for i in range(11, 1000003):
a9 = (a9 + aa) % 1000003
a8 = (a8 + a9) % 1000003
a7 = (a7 + a8) % 1000003
a6 = (a6 + a7) % 1000003
a5 = (a5 + a6) % 1000003
a4 = (a4 + a5) % 1000003
a3 = (a3 + a4) % 1000003
a2 = (a2 + a3) % 1000003
a1 = (a1 + a2) % 1000003
a0 = (a0 + a1) % 1000003
if not a0:
print('!', i)
break
else:
print('! -1')
if __name__ == '__main__':
main()
|
1555943700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0.5", "0.875", "-1"]
|
74ed99af5a5ed51c73d68f7d4ff2c70e
|
NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .
|
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.
|
If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
|
The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_001.jsonl
|
58595d599ad2ee26fd5e4be8d8f8d244
|
256 megabytes
|
["4 4\n1 3 5 7", "10 8\n10 13 15 16 17 19 20 22 24 25", "3 1\n2 5 10"]
|
PASSED
|
n,u=[int(x) for x in input().split()]
a=list(map(int,input().split()))
idx=0
ans=-1
for i in range(n):
while(idx<n-1 and a[idx+1]-a[i]<=u):
idx+=1
if(idx-i<2):
continue
ans=max(ans,(a[idx]-a[i+1])/(a[idx]-a[i]))
print(ans)
|
1521905700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["3", "2"]
|
94f1521ccc24cfb78469c81546346cd5
|
NoteIn the first sample case there is only one sum $$$1 + 2 = 3$$$.In the second sample case there are three sums: $$$1 + 2 = 3$$$, $$$1 + 3 = 4$$$, $$$2 + 3 = 5$$$. In binary they are represented as $$$011_2 \oplus 100_2 \oplus 101_2 = 010_2$$$, thus the answer is 2.$$$\oplus$$$ is the bitwise xor operation. To define $$$x \oplus y$$$, consider binary representations of integers $$$x$$$ and $$$y$$$. We put the $$$i$$$-th bit of the result to be 1 when exactly one of the $$$i$$$-th bits of $$$x$$$ and $$$y$$$ is 1. Otherwise, the $$$i$$$-th bit of the result is put to be 0. For example, $$$0101_2 \, \oplus \, 0011_2 = 0110_2$$$.
|
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute$$$$$$ (a_1 + a_2) \oplus (a_1 + a_3) \oplus \ldots \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus \ldots \oplus (a_2 + a_n) \\ \ldots \\ \oplus (a_{n-1} + a_n) \\ $$$$$$Here $$$x \oplus y$$$ is a bitwise XOR operation (i.e. $$$x$$$ ^ $$$y$$$ in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.
|
Print a single integer — xor of all pairwise sums of integers in the given array.
|
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 400\,000$$$) — the number of integers in the array. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_008.jsonl
|
ee98d3057ddb217fe13e6794f6262fe8
|
512 megabytes
|
["2\n1 2", "3\n1 2 3"]
|
PASSED
|
import io
import os
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
DEBUG = False
def solveBrute(N, A):
ans = 0
for i in range(N):
for j in range(i + 1, N):
ans ^= A[i] + A[j]
return ans
def solve(N, A):
B = max(A).bit_length()
ans = 0
for k in range(B + 1):
# Count number of pairs with kth bit on (0 indexed)
# For example if k==2, want pairs where lower 3 bits are between 100 and 111 inclusive
# If we mask A to the lower 3 bits, we can find all pairs that sum to either 100 to 111 or overflowed to 1100 to 1111
MOD = 1 << (k + 1)
MASK = MOD - 1
# Sort by x & MASK incrementally
left = []
right = []
for x in A:
if (x >> k) & 1:
right.append(x)
else:
left.append(x)
A = left + right
arr = [x & MASK for x in A]
if DEBUG:
assert arr == sorted(arr)
numPairs = 0
tLo = 1 << k
tHi = (1 << (k + 1)) - 1
for targetLo, targetHi in [(tLo, tHi), (MOD + tLo, MOD + tHi)]:
# Want to binary search for y such that targetLo <= x + y <= targetHi
# But this TLE so walk the lo/hi pointers instead
lo = N
hi = N
for i, x in enumerate(arr):
lo = max(lo, i + 1)
hi = max(hi, lo)
while lo - 1 >= i + 1 and arr[lo - 1] >= targetLo - x:
lo -= 1
while hi - 1 >= lo and arr[hi - 1] > targetHi - x:
hi -= 1
numPairs += hi - lo
if DEBUG:
# Check
assert lo == bisect_left(arr, targetLo - x, i + 1)
assert hi == bisect_right(arr, targetHi - x, lo)
for j, y in enumerate(arr):
cond = i < j and targetLo <= x + y <= targetHi
if lo <= j < hi:
assert cond
else:
assert not cond
ans += (numPairs % 2) << k
return ans
if DEBUG:
import random
random.seed(0)
for i in range(100):
A = [random.randint(1, 1000) for i in range(100)]
N = len(A)
ans1 = solveBrute(N, A)
ans2 = solve(N, A)
print(A, bin(ans1), bin(ans2))
assert ans1 == ans2
else:
if False:
# Timing
import random
random.seed(0)
A = [random.randint(1, 10 ** 7) for i in range(400000)]
N = len(A)
print(solve(N, A))
if __name__ == "__main__":
(N,) = list(map(int, input().split()))
A = list(map(int, input().split()))
ans = solve(N, A)
print(ans)
|
1583573700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["9", "0", "299997"]
|
cabb7edf51f32c94415d580b96eef7b7
|
NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios.
|
Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$.
|
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n,k \leq 10^5$$$) — the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$) — Bob's questions.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_026.jsonl
|
11c86b36666fdda7358c622ab76c7b33
|
256 megabytes
|
["5 3\n5 1 4", "4 8\n1 2 3 4 4 3 2 1", "100000 1\n42"]
|
PASSED
|
n, k = list(map(int, input().split()))
x = list(map(int, input().split()))
ml = []
for i in range(n):
ml.append([])
for i in range(k):
ml[x[i]-1] += [i+1]
c = 0
for i in range(n):
if not ml[i]:
c += 1
if i != 0:
if not ml[i] or not ml[i-1] or min(ml[i]) > max(ml[i-1]):
c += 1
if i != n-1:
if not ml[i] or not ml[i+1] or min(ml[i]) > max(ml[i+1]):
c += 1
print(c)
|
1556989500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["166666669", "500000009", "500000007"]
|
987433ba0b6a115d05f79f512e329f7a
|
NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample:
|
You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.
|
Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,300 |
train_092.jsonl
|
73b96d00c90909ef37de0a780994e1cc
|
256 megabytes
|
["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"]
|
PASSED
|
m=10**9+7
n=input()
h=range(n)
d=[n*[m]for f in h]
for f in h[1:]:a,b=map(int,raw_input().split());a-=1;b-=1;d[a][b]=d[b][a]=1;d[a][a]=d[b][b]=s=0
for k in h:
for i in h:
for j in h:d[i][j]=min(d[i][j],d[i][k]+d[k][j])
c=[[1]+n*[0]for f in[0]+h]
for i in h:
for j in h:c[i+1][j+1]=(c[i][j+1]+c[i+1][j])*-~m/2%m
for i in h:
for j in h[i+1:]:
for k in h:x,y=d[i][k],d[j][k];v=(x+y-d[i][j])/2;s+=c[x-v][y-v]
print s*pow(n,m-2,m)%m
|
1624635300
|
[
"probabilities",
"math",
"trees",
"graphs"
] |
[
0,
0,
1,
1,
0,
1,
0,
1
] |
|
1 second
|
["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"]
|
c0f79d7ebcecc4eb7d07c372ba9be802
|
NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character.
|
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers — $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ — and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.
| null | null |
standard output
|
standard input
|
PyPy 3
|
Python
| 1,400 |
train_003.jsonl
|
22b745e04d857f2e8013dd849090868a
|
256 megabytes
|
["16\n64\n345\n672"]
|
PASSED
|
from itertools import permutations
x = [4,8,15,16,23,42]
print("? 1 2", flush=True)
a = int(input())
print("? 3 4", flush=True)
b = int(input())
print("? 5 5", flush=True)
c = int(input())
print("? 1 3", flush=True)
d = int(input())
for p in permutations(x):
if p[0]*p[1] == a and p[2]*p[3] == b and p[4]*p[4] == c and p[0]*p[2] == d:
print("!", ' '.join(map(str,p)), flush=True)
break
|
1557930900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n3\n3"]
|
c9da10199ad1a5358195b693325e628b
|
NoteIn the first testcase, each shuffle effectively swaps two cards. After three swaps, the deck will be $$$[2, 1]$$$.In the second testcase, the second shuffle cancels what the first shuffle did. First, three topmost cards went underneath the last card, then that card went back below the remaining three cards. So the deck remained unchanged from the initial one — the topmost card has value $$$3$$$.
|
Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $$$n$$$ cards. You see that the values of cards from the topmost to the bottommost are integers $$$a_1, a_2, \dots, a_n$$$, and all values are different.Then he asks you to shuffle the deck $$$m$$$ times. With the $$$j$$$-th shuffle, you should take $$$b_j$$$ topmost cards and move them under the remaining $$$(n - b_j)$$$ cards without changing the order.And then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?
|
For each testcase, print a single integer — the value of the card on the top of the deck after the deck is shuffled $$$m$$$ times.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of cards in the deck. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the values of the cards. The third line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of shuffles. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_j \le n - 1$$$) — the amount of cards that are moved on the $$$j$$$-th shuffle. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_087.jsonl
|
92dd58c9ae9fcc3a77c757e7da165d0e
|
256 megabytes
|
["3\n\n2\n\n1 2\n\n3\n\n1 1 1\n\n4\n\n3 1 4 2\n\n2\n\n3 1\n\n5\n\n2 1 5 4 3\n\n5\n\n3 2 1 2 1"]
|
PASSED
|
case = int(input())
def solve():
n = int(input())
card = list(map(int,input().split()))
m = int(input())
v = list(map(int,input().split()))
counter = 0
for i in v:
counter+=i
counter = counter%n
print(card[counter])
for _ in range(case):
solve()
|
1653316500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["70.00000000", "55.00000000"]
|
0c3fd1226188cccd013b0842666c3597
| null |
Once Petya was in such a good mood that he decided to help his mum with the washing-up. There were n dirty bowls in the sink. From the geometrical point of view each bowl looks like a blunted cone. We can disregard the width of the walls and bottom. Petya puts the clean bowls one on another naturally, i. e. so that their vertical axes coincide (see the picture). You will be given the order in which Petya washes the bowls. Determine the height of the construction, i.e. the distance from the bottom of the lowest bowl to the top of the highest one.
|
Output the height of the plate pile accurate to at least 10 - 6.
|
The first input line contains integer n (1 ≤ n ≤ 3000). Each of the following n lines contains 3 integers h, r and R (1 ≤ h ≤ 10000, 1 ≤ r < R ≤ 10000). They are the height of a bowl, the radius of its bottom and the radius of its top. The plates are given in the order Petya puts them on the table.
|
output.txt
|
input.txt
|
PyPy 3
|
Python
| 2,200 |
train_058.jsonl
|
ee4e7a89ddb096556d53238cd9cb3a86
|
64 megabytes
|
["2\n40 10 50\n60 20 30", "3\n50 30 80\n35 25 70\n40 10 90"]
|
PASSED
|
import sys
from array import array # noqa: F401
def input1():
with open('input.txt') as fp:
return fp.readlines()
def output1(ans: str):
with open('output.txt', mode='w') as fp:
fp.write(ans)
def input2():
return [line.decode('utf-8') for line in sys.stdin.buffer.readlines()]
def output2(ans):
print(ans)
submit = 1
if submit:
input = input1
output = output1
else:
input = input2
output = output2
s = input()
n = int(s[0])
bowls = [tuple(map(float, line.split())) for line in s[1:]]
ans = bowls[0][0]
bottom = [0.0] * n
eps = 1e-9
for i in range(1, n):
hi, ri, Ri = bowls[i]
res = bottom[i - 1]
for j in range(i - 1, -1, -1):
hj, rj, Rj = bowls[j]
x = 0.0
if Rj <= ri:
x = hj
elif Rj >= Ri:
x = max((Ri - rj) / (Rj - rj) * hj - hi, (ri - rj) / (Rj - rj) * hj)
else:
x = max(hj - (Rj - ri) / (Ri - ri) * hi, (ri - rj) / (Rj - rj) * hj)
res = max(res, x + bottom[j])
bottom[i] = res
ans = max(ans, bottom[i] + hi)
output('{:.10f}'.format(ans))
|
1287482400
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["6", "8", "8"]
|
a88e4a7c476b9af1ff2ca9137214dfd7
|
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
|
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$ — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
Print one number — maximal value of $$$c$$$.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$) — the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$) — the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_004.jsonl
|
1c2e7cfd1ae49e41e349035e00537f47
|
256 megabytes
|
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
|
PASSED
|
n, k = map(int, input().split())
a = input()
b = input()
res = 0
ans = 0
for i in range(0, n):
res = min(res * 2 + (b[i] == 'b') - (a[i] == 'b'), k)
ans += min(res + 1, k)
print(ans)
|
1544459700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["12", "11"]
|
d2fe5a201d1ec20c5b32cd99b54e13d0
|
NoteThe algorithm for the first example: add to the answer $$$1010_2~ \&~ 1101_2 = 1000_2 = 8_{10}$$$ and set $$$b := 110$$$; add to the answer $$$1010_2~ \&~ 110_2 = 10_2 = 2_{10}$$$ and set $$$b := 11$$$; add to the answer $$$1010_2~ \&~ 11_2 = 10_2 = 2_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1010_2~ \&~ 1_2 = 0_2 = 0_{10}$$$ and set $$$b := 0$$$. So the answer is $$$8 + 2 + 2 + 0 = 12$$$.The algorithm for the second example: add to the answer $$$1001_2~ \&~ 10101_2 = 1_2 = 1_{10}$$$ and set $$$b := 1010$$$; add to the answer $$$1001_2~ \&~ 1010_2 = 1000_2 = 8_{10}$$$ and set $$$b := 101$$$; add to the answer $$$1001_2~ \&~ 101_2 = 1_2 = 1_{10}$$$ and set $$$b := 10$$$; add to the answer $$$1001_2~ \&~ 10_2 = 0_2 = 0_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1001_2~ \&~ 1_2 = 1_2 = 1_{10}$$$ and set $$$b := 0$$$. So the answer is $$$1 + 8 + 1 + 0 + 1 = 11$$$.
|
You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.
|
Print the answer to this problem in decimal notation modulo $$$998244353$$$.
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,700 |
train_008.jsonl
|
0af6a82bceb4fc9cdaa52febaa7c4160
|
256 megabytes
|
["4 4\n1010\n1101", "4 5\n1001\n10101"]
|
PASSED
|
def main():
n, m = [int(c) for c in input().split()]
a, b = input(), input()
mod = 998244353
N = 300009
if n < m:
a = '0' * (m - n) + a
elif m < n:
b = '0' * (n - m) + b
n = max(n, m)
one = [b[0] == '1']
for i in range(1, n):
one.append(one[-1] + (b[i] == '1'))
pw = [1]
for i in range(1, N):
pw.append(pw[-1] * 2 % mod)
ans = 0
for i in range(n):
res = (a[i] == '1') * pw[n - i - 1] % mod
ans = (ans + res * one[i] % mod) % mod
print(ans)
if __name__ == '__main__':
main()
|
1539354900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4", "528", "63"]
|
268f90d0595f7c51fb336ce377409dde
|
NoteIn the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
|
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.
|
Print a single integer — the required number of ways modulo 1000000007 (109 + 7).
|
In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_015.jsonl
|
036201488c1d3ed9cb8bb8f0413b6472
|
256 megabytes
|
["1256\n1", "13990\n2", "555\n2"]
|
PASSED
|
t, k = input(), int(input())
s, n, d = 0, 1, 1000000007
for i in t:
if i in '05': s += n
n = (n << 1) % d
p = (pow(n, k, d) - 1) * pow(n - 1, d - 2, d)
print(((p % d) * (s % d)) % d)
# Made By Mostafa_Khaled
|
1372941000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "2", "4"]
|
b2bc51df4a2c05c56c211e8f33fe1b45
|
NoteIn the first sample n = 2 is a beautiful number.In the second sample n = 7 and Valera can decompose it into sum 23 + ( - 20).In the third sample n = 109 can be decomposed into the sum of four summands as follows: 27 + ( - 24) + ( - 22) + 20.
|
Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.
|
Print a single integer — the minimum amount of beautiful numbers that give a total of n.
|
The first line contains string s (1 ≤ |s| ≤ 106), that is the binary representation of number n without leading zeroes (n > 0).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_044.jsonl
|
76c3466abdc3b452cf7ffb1b0c53bd4a
|
256 megabytes
|
["10", "111", "1101101"]
|
PASSED
|
t = input()
j = t[0]
d, s = 0, int(j)
for i in t[1: ]:
if j != i:
if d == 1: d, s = 0, s + 1
else: d = 1
j = i
else: d = 1
print(s + (d and j == '1'))
|
1362411000
|
[
"number theory",
"games"
] |
[
1,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["YES", "NO"]
|
99f37936b243907bf4ac1822dc547a61
|
NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
|
A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
|
If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.
|
The first line contains one integer $$$n$$$ ($$$13 \le n < 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,200 |
train_002.jsonl
|
cc1d033ffd1653e8fa0ed051cc3133d9
|
256 megabytes
|
["13\n8380011223344", "15\n807345619350641"]
|
PASSED
|
n=int(raw_input())
s=list(raw_input())
cnt=n-11
cntt=[0 for i in xrange(10)]
for i in xrange(n):
cntt[int(s[i])] += 1
if cntt[8] <= cnt/2:
print "NO"
else:
summ=0
for i in xrange(n):
if s[i] == "8":
summ += 1
s[i]='0'
if summ == cnt/2:
break
flag = -1
for i in xrange(0,cnt+1):
if s[i] == '8':
print "YES"
flag = 0
break
if flag == -1:
print "NO"
|
1555943700
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["0\n-1\n2\n-1\n-1\n12\n36"]
|
3ae468c425c7b156983414372fd35ab8
|
NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$: Divide by $$$6$$$ and get $$$2519424$$$; divide by $$$6$$$ and get $$$419904$$$; divide by $$$6$$$ and get $$$69984$$$; divide by $$$6$$$ and get $$$11664$$$; multiply by $$$2$$$ and get $$$23328$$$; divide by $$$6$$$ and get $$$3888$$$; divide by $$$6$$$ and get $$$648$$$; divide by $$$6$$$ and get $$$108$$$; multiply by $$$2$$$ and get $$$216$$$; divide by $$$6$$$ and get $$$36$$$; divide by $$$6$$$ and get $$$6$$$; divide by $$$6$$$ and get $$$1$$$.
|
You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer — the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_002.jsonl
|
0c55656e8cbd4ebdac8e5788ee7e3f29
|
256 megabytes
|
["7\n1\n2\n3\n12\n12345\n15116544\n387420489"]
|
PASSED
|
for i in range (int(input())):
n=int(input())
j=0;k=0
while n % 6 == 0:
n/=6
j=j+1
while n % 3 == 0:
n/=3
k=k+1
if n!=1:
print(-1)
else:print(j+2*k)
|
1593354900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["99\n0"]
|
53975eea2503bb47bfd0a5119406aea3
|
NoteIn the first test case, you can, for example, increase $$$p_0$$$ by $$$50$$$ and $$$p_1$$$ by $$$49$$$ and get array $$$[20150, 50, 202, 202]$$$. Then you get the next inflation coefficients: $$$\frac{50}{20150} \le \frac{1}{100}$$$; $$$\frac{202}{20150 + 50} \le \frac{1}{100}$$$; $$$\frac{202}{20200 + 202} \le \frac{1}{100}$$$; In the second test case, you don't need to modify array $$$p$$$, since the inflation coefficients are already good: $$$\frac{1}{1} \le \frac{100}{100}$$$; $$$\frac{1}{1 + 1} \le \frac{100}{100}$$$;
|
You have a statistic of price changes for one product represented as an array of $$$n$$$ positive integers $$$p_0, p_1, \dots, p_{n - 1}$$$, where $$$p_0$$$ is the initial price of the product and $$$p_i$$$ is how the price was increased during the $$$i$$$-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $$$p_i$$$ to the price at the start of this month $$$(p_0 + p_1 + \dots + p_{i - 1})$$$.Your boss said you clearly that the inflation coefficients must not exceed $$$k$$$ %, so you decided to increase some values $$$p_i$$$ in such a way, that all $$$p_i$$$ remain integers and the inflation coefficients for each month don't exceed $$$k$$$ %.You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %?
|
For each test case, print the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$; $$$1 \le k \le 100$$$) — the length of array $$$p$$$ and coefficient $$$k$$$. The second line of each test case contains $$$n$$$ integers $$$p_0, p_1, \dots, p_{n - 1}$$$ ($$$1 \le p_i \le 10^9$$$) — the array $$$p$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_102.jsonl
|
18bbd696c53ac0fa40a25b6869c381fb
|
256 megabytes
|
["2\n4 1\n20100 1 202 202\n3 100\n1 1 1"]
|
PASSED
|
#import io, os
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import math
t = int(input())
for _ in range(t):
n, k = map(int,input().split())
k = k
arr = list(map(int,input().split()))
running_total = arr[0]
ans = 0
for i in range(1,len(arr)):
if (arr[i] / running_total) > k/100:
ans += math.ceil(100 * arr[i] / k ) - running_total
running_total += math.ceil(100 * arr[i] / k ) - running_total
running_total += arr[i]
print(ans)
|
1611930900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2012-03-16 16:16:43", "-1", "2012-03-17 00:00:00"]
|
c3f671243f0aef7b78a7e091b0e8f75e
| null |
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.
|
If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.
|
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000 |
train_012.jsonl
|
6dfed102eff84baaf1c4af6a008100a9
|
256 megabytes
|
["60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected", "1 2\n2012-03-16 23:59:59:Disk size\n2012-03-17 00:00:00: Network\n2012-03-17 00:00:01:Cant write varlog", "2 2\n2012-03-16 23:59:59:Disk size is too sm\n2012-03-17 00:00:00:Network failute dete\n2012-03-17 00:00:01:Cant write varlogmysq"]
|
PASSED
|
import sys,time,re
n,m=map(int,raw_input().split())
t=[]
i=j=0
for s in sys.stdin:
t+=[time.mktime(map(int,re.split('[-: ]',s[:19]))+[0]*3)]
while j<i and t[j]<=t[i]-n:j+=1
i+=1
if i-j>=m:
print s[:19]
exit()
print -1
|
1353339000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["MULTIPLE", "NONE", "UNIQUE\nSSSSSSSSSS\nSGGGGGGGGS\nSGSSSSSSGS\nSGSGGGGSGS\nSGSGSSGSGS\nSGSGSSGSGS\nSGSGGGGSGS\nSGSSSSSSGS\nSGGGGGGGGS\nSSSSSSSSSS", "NONE"]
|
4425c6660c9e9c037e32c2e1c081b9c1
|
NoteFor the first test case, Omkar can make the mastapeecesSSSSSGGSSGGSSSSSand SSGGSSGGGGSSGGSS.For the second test case, it can be proven that it is impossible for Omkar to add tiles to create a mastapeece.For the third case, it can be proven that the given mastapeece is the only mastapeece Omkar can create by adding tiles.For the fourth test case, it's clearly impossible for the only tile in any mosaic Omkar creates to be adjacent to two tiles of the same color, as it will be adjacent to $$$0$$$ tiles total.
|
Omkar is creating a mosaic using colored square tiles, which he places in an $$$n \times n$$$ grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells. A completed mosaic will be a mastapeece if and only if each tile is adjacent to exactly $$$2$$$ tiles of the same color ($$$2$$$ tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a mastapeece. Now he is wondering, is the way to do this unique, and if it is, what is it?
|
On the first line, print UNIQUE if there is a unique way to get a mastapeece, NONE if Omkar cannot create any, and MULTIPLE if there is more than one way to do so. All letters must be uppercase. If you print UNIQUE, then print $$$n$$$ additional lines with $$$n$$$ characters in each line, such that the $$$i$$$-th character in the $$$j^{\text{th}}$$$ line is $$$S$$$ if the tile in row $$$i$$$ and column $$$j$$$ of the mastapeece is sinoper, and $$$G$$$ if it is glaucous.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$). Then follow $$$n$$$ lines with $$$n$$$ characters in each line. The $$$i$$$-th character in the $$$j$$$-th line corresponds to the cell in row $$$i$$$ and column $$$j$$$ of the grid, and will be $$$S$$$ if Omkar has placed a sinoper tile in this cell, $$$G$$$ if Omkar has placed a glaucous tile, $$$.$$$ if it's empty.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,500 |
train_096.jsonl
|
2b789c313224ccc55157a487155d383c
|
256 megabytes
|
["4\nS...\n..G.\n....\n...S", "6\nS.....\n....G.\n..S...\n.....S\n....G.\nG.....", "10\n.S....S...\n..........\n...SSS....\n..........\n..........\n...GS.....\n....G...G.\n..........\n......G...\n..........", "1\n."]
|
PASSED
|
import sys
o = {'G':'S', 'S':'G'}
n = int(sys.stdin.readline())
d = [list(sys.stdin.readline()[:n]) for _ in range(n)]
f = [1]*(n*n)
finished = 1
def none(): print('NONE'); sys.exit()
def printd(): print('\n'.join(''.join(d[i]) for i in range(n)))
if n % 2: none()
x = ['']*(n//2)
def findt(i,j): return abs(j-i)//2 if (j - i) % 2 else min(i+j, 2*(n-1)-j-i) // 2
def findr(i,j,t):
if (j-i) % 2: return o[t] if min(i,j) % 2 else t
else:
if i+j < n: return o[t] if i % 2 else t
else: return t if i % 2 else o[t]
for i in range(n):
for j in range(n):
if d[i][j] != '.':
t = findt(i,j)
r = findr(i,j,d[i][j])
if x[t] == o[r]: none()
else: x[t] = r
for i in range(n//2):
if not x[i]: print('MULTIPLE'); sys.exit()
for i in range(n):
for j in range(n):
d[i][j] = findr(i,j,x[findt(i,j)])
print('UNIQUE')
printd()
|
1634468700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["42", "28"]
|
e6689123fefea251555e0e096f58f6d1
|
NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
|
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_010.jsonl
|
5f5b99a7173786f22366e38943303554
|
256 megabytes
|
["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"]
|
PASSED
|
n = int(input())
k = 0
i = 0
while i != n:
x = str(input())
if x == 'Tetrahedron':
k += 4
if x == 'Cube':
k += 6
if x == 'Octahedron':
k += 8
if x == 'Dodecahedron':
k += 12
if x == 'Icosahedron':
k += 20
i += 1
print(k)
# 374 ms по слову for
# 390 ms по индексу for
# 467 ms по слову while
# 467 ms по индексу while
|
1489590300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["YES\nYES\nNO\nNO"]
|
a27ad7c21cd6402bfd082da4f6c7ab9d
|
NoteIn the first test case there is the following sequence of operation: $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax; $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax; $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation: $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc; $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc; $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc; $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc.
|
You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted): aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ ade; aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dae; aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dea; aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ bde; aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ dbe; aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ deb; aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ ade; aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dae; aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.
|
For each query print YES if it is possible to make $$$s$$$ equal to $$$t$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
|
The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by three consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \le |p| \le 100$$$) consisting of lowercase Latin letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_008.jsonl
|
5260e723c4bf71ec0f83d3cc18495056
|
256 megabytes
|
["4\nab\nacxb\ncax\na\naaaa\naaabbcc\na\naaaa\naabbcc\nab\nbaaa\naaaaa"]
|
PASSED
|
t=int(input())
for _ in range(t):
s=input()
t=input()
p=input()
if(len(t)<len(s)):
print('NO')
elif(len(t)==len(s)):
if(t==s):
print('YES')
else:
print('NO')
else:
j=0
c=0
for i in s:
while(j<len(t)):
if(t[j]==i):
c+=1
j+=1
break
j+=1
if(c==len(s)):
f=0
s=s+' '
for i in range(len(t)):
#print(t[i])
if(t[i]!=s[i]):
if(t[i] in p):
s=s[:i]+t[i]+s[i:]
index=p.index(t[i])
p=p[:index]+p[index+1:]
#print(p)
else:
print('NO')
f=1
break
if(f==0):
print('YES')
else:
print('NO')
|
1563115500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1 0", "4 14", "0 8"]
|
1e6d7ec8023eb0dc482b1f133e5dfe2a
|
NoteIn the first sample it is optimal to leave the array as it is by choosing $$$x = 0$$$.In the second sample the selection of $$$x = 14$$$ results in $$$b$$$: $$$[4, 9, 7, 4, 9, 11, 11, 13, 11]$$$. It has $$$4$$$ inversions: $$$i = 2$$$, $$$j = 3$$$; $$$i = 2$$$, $$$j = 4$$$; $$$i = 3$$$, $$$j = 4$$$; $$$i = 8$$$, $$$j = 9$$$. In the third sample the selection of $$$x = 8$$$ results in $$$b$$$: $$$[0, 2, 11]$$$. It has no inversions.
|
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. You have to choose a non-negative integer $$$x$$$ and form a new array $$$b$$$ of size $$$n$$$ according to the following rule: for all $$$i$$$ from $$$1$$$ to $$$n$$$, $$$b_i = a_i \oplus x$$$ ($$$\oplus$$$ denotes the operation bitwise XOR).An inversion in the $$$b$$$ array is a pair of integers $$$i$$$ and $$$j$$$ such that $$$1 \le i < j \le n$$$ and $$$b_i > b_j$$$.You should choose $$$x$$$ in such a way that the number of inversions in $$$b$$$ is minimized. If there are several options for $$$x$$$ — output the smallest one.
|
Output two integers: the minimum possible number of inversions in $$$b$$$, and the minimum possible value of $$$x$$$, which achieves those number of inversions.
|
First line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements in $$$a$$$. Second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,000 |
train_006.jsonl
|
651a581141808334f7590ad06be54f47
|
512 megabytes
|
["4\n0 1 3 2", "9\n10 7 9 10 7 5 5 3 5", "3\n8 10 3"]
|
PASSED
|
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
n = int(input())
l = list(map(int, input().split()))
inv = 0
out = 0
mult = 1
for i in range(32):
curr = dict()
opp = 0
same = 0
for v in l:
if v ^ 1 in curr:
if v & 1:
opp += curr[v ^ 1]
else:
same += curr[v ^ 1]
if v not in curr:
curr[v] = 0
curr[v] += 1
for i in range(n):
l[i] >>= 1
if same <= opp:
inv += same
else:
inv += opp
out += mult
mult *= 2
print(inv, out)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
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__":
main()
|
1601219100
|
[
"math",
"strings",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
1,
1
] |
|
1 second
|
["4", "5"]
|
0151a87d0f82a9044a0ac8731d369bb9
|
NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
|
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
|
Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.
|
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_003.jsonl
|
e312b5d158a67e1ee59db648b992aca9
|
256 megabytes
|
["4 2\nabba", "8 1\naabaabaa"]
|
PASSED
|
def getMax(s,i,j,t,k,n):
res = 0
count = 0
while i<n :
while j<n and count<k:
if s[j]!=t:
count+=1
j+=1
while j<n and s[j]==t:
j+=1
res = max(res,j-i)
while i<n and s[i]==t:
i+=1
if i<n :
i+=1
count-=1
return res
n,k =[int(x) for x in input().split()]
s = input()
print(max(getMax(s,0,0,'a',k,n), getMax(s,0,0,'b',k,n)))
|
1464188700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["4", "1", "0"]
|
d98ecf6c5550e7ec7639fcd1f727fb35
| null |
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.
|
Print integer s — the value of the required sum modulo 109 + 7.
|
The only line contains two integers n, m (1 ≤ n, m ≤ 1013) — the parameters of the sum.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_023.jsonl
|
afcf7d0217b0f37d409716fd8e633984
|
256 megabytes
|
["3 4", "4 4", "1 1"]
|
PASSED
|
n,m = map(int,raw_input().split(" "))
ans = 0
w = 1000000007
if m > n:
ans += n*(m-n)
m = n
last = min(m,n-1)
def su(s,e,l):
return (s+e)*l/2
for i in xrange(2,900000):
q = n/i
if q >= last:
continue
ans += (n%last+n%(q+1))*(last-q)/2
last = q
ans %= w
for i in xrange(1,last+1):
ans += n%i
ans %= w
print ans%w
|
1452524400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["3", "0"]
|
3dc14d8d19938d9a5ed8323fe608f581
| null |
You are given $$$n$$$ segments on a number line, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th segments covers all integer points from $$$l_i$$$ to $$$r_i$$$ and has a value $$$w_i$$$.You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point $$$m$$$ starting from point $$$1$$$ in arbitrary number of moves.The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset.In every test there exists at least one good subset.
|
Print a single integer — the minimum cost of a good subset.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^6$$$) — the number of segments and the number of integer points. Each of the next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$ and $$$w_i$$$ ($$$1 \le l_i < r_i \le m$$$; $$$1 \le w_i \le 10^6$$$) — the description of the $$$i$$$-th segment. In every test there exists at least one good subset.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100 |
train_088.jsonl
|
5ddb90d6a6d600f3803336cf0ac1b199
|
256 megabytes
|
["5 12\n1 5 5\n3 4 10\n4 10 6\n11 12 5\n10 12 3", "1 10\n1 10 23"]
|
PASSED
|
import bisect
import sys
input = sys.stdin.readline
from collections import defaultdict, deque
from itertools import permutations, accumulate
from functools import reduce
p = print
r = range
def I(): return int(input())
def II(): return list(map(int, input().split()))
def S(): return input()[:-1]
def M(n): return [list(map(int, input().split())) for ___ in r(n)]
def pb(b): print('Yes' if b else 'No')
def INF(): return float('inf')
INF = 8 * 10 ** 18
MOD = 998244353
MASK = 32
class LazySegTree:
def __init__(self, op, e, mapping, composition, id, n = -1, v= []):
if(len(v) == 0):
v = [e] * n
self.__n = len(v)
self.__log = (self.__n - 1).bit_length()
self.__size = 1 << self.__log
self.__d = [e] * (2 * self.__size)
self.__lz = [id] * self.__size
self.__op = op
self.__e = e
self.__mapping = mapping
self.__composition = composition
self.__id = id
for i in range(self.__n):
self.__d[self.__size + i] = v[i]
for i in range(self.__size - 1, 0, -1):
self.__update(i)
def __update(self, k):
self.__d[k] = self.__op(self.__d[2 * k], self.__d[2 * k + 1])
def __all_apply(self, k, f):
self.__d[k] = self.__mapping(f, self.__d[k])
if(k < self.__size):
self.__lz[k] = self.__composition(f, self.__lz[k])
def __push(self, k):
self.__all_apply(2 * k, self.__lz[k])
self.__all_apply(2 * k + 1, self.__lz[k])
self.__lz[k] = self.__id
def set(self, p, x):
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
self.__d[p] = x
for i in range(1, self.__log + 1):
self.__update(p >> i)
def get(self, p):
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
return self.__d[p]
def prod(self, l, r):
if(l == r):
return self.__e
l += self.__size
r += self.__size
for i in range(self.__log, 0, -1):
if((l >> i) << i) != l:
self.__push(l >> i)
if((r >> i) << i) != r:
self.__push(r >> i)
sml = self.__e
smr = self.__e
while(l < r):
if(l & 1):
sml = self.__op(sml, self.__d[l])
l += 1
if(r & 1):
r -= 1
smr = self.__op(self.__d[r], smr)
l //= 2
r //= 2
return self.__op(sml, smr)
def all_prod(self):
return self.__d[1]
def apply(self, p, f):
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
self.__d[p] = self.__mapping(f, self.__d[p])
for i in range(1, self.__log + 1):
self.__update(p >> i)
def apply_range(self, l, r, f):
if(l == r):
return
l += self.__size
r += self.__size
for i in range(self.__log, 0, -1):
if((l >> i) << i) != l:
self.__push(l >> i)
if((r >> i) << i) != r:
self.__push((r - 1) >> i)
l2, r2 = l, r
while(l < r):
if(l & 1):
self.__all_apply(l, f)
l += 1
if(r & 1):
r -= 1
self.__all_apply(r, f)
l //= 2
r //= 2
l, r = l2, r2
for i in range(1, self.__log + 1):
if((l >> i) << i) != l:
self.__update(l >> i)
if((r >> i) << i) != r:
self.__update((r - 1) >> i)
def max_right(self, l, g):
if(l == self.__n):
return self.__n
l += self.__size
for i in range(self.__log, 0, -1):
self.__push(l >> i)
sm = self.__e
while(True):
while(l % 2 == 0):
l //= 2
if(not g(self.__op(sm, self.__d[l]))):
while(l < self.__size):
self.__push(l)
l *= 2
if(g(self.__op(sm, self.__d[l]))):
sm = self.__op(sm, self.__d[l])
l += 1
return l - self.__size
sm = self.__op(sm, self.__d[l])
l += 1
if(l & -l) == l:
break
return self.__n
def min_left(self, r, g):
if(r == 0):
return 0
r += self.__size
for i in range(self.__log, 0, -1):
self.__push((r - 1) >> i)
sm = self.__e
while(True):
r -= 1
while(r > 1) & (r % 2):
r //= 2
if(not g(self.__op(self.__d[r], sm))):
while(r < self.__size):
self.__push(r)
r = 2 * r + 1
if(g(self.__op(self.__d[r], sm))):
sm = self.__op(self.__d[r], sm)
r -= 1
return r + 1 - self.__size
sm = self.__op(self.__d[r], sm)
if(r & -r) == r:
break
return 0
def all_push(self):
for i in range(1, self.__size):
self.__push(i)
def get_all(self):
self.all_push()
return self.__d[self.__size:self.__size + self.__n]
def print(self):
print(list(map(lambda x: divmod(x, (1 << 30)), self.__d)))
print(self.__lz)
print('------------------')
e = INF
id = 0
def op(a, b):
return min(a, b)
def mapping(f, a):
return a + f
def composition(f, g):
return f + g
# -----------------------------------------------------------------------------------------------------
#
# ∧_∧
# ∧_∧ (´<_` ) Welcome to My Coding Space !
# ( ´_ゝ`) / ⌒i Free Hong Kong !
# / \ | | Free Tibet !
# / / ̄ ̄ ̄ ̄/ | |
# __(__ニつ/ _/ .| .|____
# \/____/ (u ⊃
#
# BINARY SEARCH ?
# CHANGE TO GRAPH?
# pow(x,-1,q) PLEASE USE [python 3.8.2]
# -----------------------------------------------------------------------------------------------------
n, m = II()
query = sorted(M(n), key= lambda x: x[2])
for i in r(n):
query[i][1] -= 1
seg = LazySegTree(op, e, mapping, composition, id, m, [0]*(m))
hi = 1
lo = 0
#p(query)
seg.apply_range(query[0][0], query[0][1] + 1, 1)
#p(*[seg.get(i) for i in r(m)])
res = INF
while lo < n and hi <= n:
check = seg.prod(1,m)
if check > 0:
res = min(res, query[hi-1][2] - query[lo][2])
seg.apply_range(query[lo][0], query[lo][1] + 1, -1)
lo += 1
else:
if hi >= n:
break
seg.apply_range(query[hi][0], query[hi][1] + 1, 1)
hi += 1
#p(lo,hi,res)
#p(*[seg.get(i) for i in r(1,m-1)])
p(res)
|
1627655700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1\n2\n2\n5\n8"]
|
19df5f3b8b31b763162c5331c1499529
|
NotePossible optimal arrangement of the lanterns for the $$$2$$$-nd test case of input data example: Possible optimal arrangement of the lanterns for the $$$3$$$-rd test case of input data example:
|
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park). The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.
|
Print $$$t$$$ answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$n$$$, $$$m$$$ ($$$1 \le n, m \le 10^4$$$) — park sizes.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_018.jsonl
|
8e580289d2bb2743d731f11fc13766b0
|
256 megabytes
|
["5\n1 1\n1 3\n2 2\n3 3\n5 3"]
|
PASSED
|
for _ in range(int(input())):
n,m=map(int,input().split())
s=n*m
if s%2==0:
print(int(m*n/2))
else:
print(int(m*n//2)+1)
|
1590503700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2 2 3 3 3", "-1"]
|
7dea96a7599946a5b5d0b389c7e76651
|
NoteIn the first example, if $$$v_{1} = \{ 1 \}$$$, $$$v_{2} = \{ 2, 3 \}$$$, and $$$v_{3} = \{ 4, 5, 6 \}$$$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. In the second example, it's impossible to make such vertex sets.
|
You have a simple undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let $$$v_1$$$ and $$$v_2$$$ be two some nonempty subsets of vertices that do not intersect. Let $$$f(v_{1}, v_{2})$$$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $$$v_1$$$. There are no edges with both endpoints in vertex set $$$v_2$$$. For every two vertices $$$x$$$ and $$$y$$$ such that $$$x$$$ is in $$$v_1$$$ and $$$y$$$ is in $$$v_2$$$, there is an edge between $$$x$$$ and $$$y$$$. Create three vertex sets ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
|
If the answer exists, print $$$n$$$ integers. $$$i$$$-th integer means the vertex set number (from $$$1$$$ to $$$3$$$) of $$$i$$$-th vertex. Otherwise, print $$$-1$$$. If there are multiple answers, print any.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 10^{5}$$$, $$$0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$$$) — the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$m$$$ 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}$$$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_000.jsonl
|
9c372f74ccc3656797e5d61fdee09156
|
256 megabytes
|
["6 11\n1 2\n1 3\n1 4\n1 5\n1 6\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
|
PASSED
|
# https://codeforces.com/contest/1228/problem/D
# all neightbor in group --> pass 1
# all neighbor not in group --> merge 0
# invalid 2
# WA
def type_(list_v, group):
cnt_0 = 0
cnt_1 = 0
for v in list_v:
if v in group:
cnt_1 += 1
else:
cnt_0 += 1
if cnt_1 == len(group):
return 1
if cnt_0 == len(list_v):
return 0
return 2
def is_all_type_1(ex_index, list_group, v):
for i, group in list_group.items():
if i == ex_index:
continue
if type_(g[v], group) != 1:
return False
return True
def check(v, list_group):
t = None
for i, group in list_group.items():
t = type_(g[v], group)
if t == 0 or t == 2:
if t == 0:
if is_all_type_1(i, list_group, v) == True:
group[v] = 1
else:
return 2
return t
return t
group = {}
def process(g):
for v in g:
if len(group) == 0:
group[0] = {}
group[0][v] = 1
continue
t = check(v, group)
if t == 2:
return -1
if t == 1:
if len(group) == 3:
return -1
group[len(group)] = {}
group[len(group)-1][v] = 1
return group
g = {}
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
ans = process(g)
if ans == -1 or len(ans) < 3:
print(-1)
else:
pr = [0] * n
cnt = 0
for k, gr in group.items():
for v in gr:
cnt += 1
pr[v-1] = str(k+1)
if cnt == n:
print(' '.join(pr))
else:
print(-1)
# 1,2 3,4 5,6
#6 12
#1 3
#1 4
#2 3
#2 4
#1 5
#1 6
#2 5
#2 6
#3 5
#3 6
#4 5
#4 6
|
1569762300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"]
|
db473ad780a93983667d12b1357c6e2f
|
NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed.
|
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a substring.
|
The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c".
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,100 |
train_110.jsonl
|
711ec2f0e5300d8273b52a74ad3add05
|
256 megabytes
|
["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"]
|
PASSED
|
from sys import stdin,stdout
import re
n,m=map(int,input().split())
s=list(input())
k="".join(s)
l=k.count("abc")
for i in range(m):
j,x=map(str,input().split())
j=int(j)-1
if(s[j]==x):
stdout.write(str(l)+"\n")
continue
if(j+2<n and s[j]=="a" and s[j+1]=="b" and s[j+2]=="c"):
l-=1
elif(1<j+1<n and s[j-1]=="a" and s[j]=="b" and s[j+1]=="c"):
l-=1
elif(1<j and s[j-2]=="a" and s[j-1]=="b" and s[j]=="c"):
l-=1
s[j]=x
if(j+2<n and s[j]=="a" and s[j+1]=="b" and s[j+2]=="c"):
l+=1
elif(1<j+1<n and s[j-1]=="a" and s[j]=="b" and s[j+1]=="c"):
l+=1
elif(1<j and s[j-2]=="a" and s[j-1]=="b" and s[j]=="c"):
l+=1
if(l<=0):
l=0
stdout.write(str(l)+"\n")
|
1638110100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1000100010", "1001101000", "No"]
|
61a067dc6b8e04bfc661b7fa9ecb4eda
|
NoteIn the first example, $$$7$$$ is not a period of the resulting string because the $$$1$$$-st and $$$8$$$-th characters of it are different.In the second example, $$$6$$$ is not a period of the resulting string because the $$$4$$$-th and $$$10$$$-th characters of it are different.In the third example, $$$9$$$ is always a period because the only constraint that the first and last characters are the same is already satisfied.Note that there are multiple acceptable answers for the first two examples, you can print any of them.
|
Walking along a riverside, Mino silently takes a note of something."Time," Mino thinks aloud."What?""Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this.""And what are you recording?""You see it, tide. Everything has its own period, and I think I've figured out this one," says Mino with confidence.Doubtfully, Kanno peeks at Mino's records. The records are expressed as a string $$$s$$$ of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low).You are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer $$$p$$$ is not a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino.In this problem, a positive integer $$$p$$$ is considered a period of string $$$s$$$, if for all $$$1 \leq i \leq \lvert s \rvert - p$$$, the $$$i$$$-th and $$$(i + p)$$$-th characters of $$$s$$$ are the same. Here $$$\lvert s \rvert$$$ is the length of $$$s$$$.
|
Output one line — if it's possible that $$$p$$$ is not a period of the resulting string, output any one of such strings; otherwise output "No" (without quotes, you can print letters in any case (upper or lower)).
|
The first line contains two space-separated integers $$$n$$$ and $$$p$$$ ($$$1 \leq p \leq n \leq 2000$$$) — the length of the given string and the supposed period, respectively. The second line contains a string $$$s$$$ of $$$n$$$ characters — Mino's records. $$$s$$$ only contains characters '0', '1' and '.', and contains at least one '.' character.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,200 |
train_013.jsonl
|
73fdf29e6f43bb412031c11c7f8b9741
|
256 megabytes
|
["10 7\n1.0.1.0.1.", "10 6\n1.0.1.1000", "10 9\n1........1"]
|
PASSED
|
entrada = raw_input().split()
p = int(entrada[1])
abc = raw_input()
s = list(abc)
ans = True
#print s
for i in xrange(len(s)):
if i + p >= len(s):
break
#print s[i], s[i + p]
if s[i] == "." and s[i + p] == ".":
s[i] = "0"
s[i + p] = "1"
ans = False
elif s[i] != s[i + p]:
if s[i] == "1":
s[i + p] == "0"
if s[i] == "0":
s[i + p] == "1"
if s[i] == ".":
if s[i + p] == "0":
s[i] == "1"
else:
s[i] == "0"
ans = False
if ans:
print "No"
else:
ans = ""
for i in xrange(len(s)):
if s[i] == ".":
if i - p >= 0:
if s[i - p] == "1":
s[i] = "0"
break
else:
s[i] = "1"
break
for i in xrange(len(s)):
if s[i] == ".":
if i + p >= len(s):
s[i] = "1"
elif s[i + p] == ".":
s[i] = "0"
s[i + p] = "1"
elif s[i + p] == "0":
s[i] = "1"
else:
s[i] = "0"
ans+=s[i]
print ans
|
1528724100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds
|
["2", "-1", "0", "3"]
|
56b207a6d280dc5ea39ced365b402a96
|
NoteIn the first sample test, Okabe can take the path , paying only when moving to (2, 3) and (4, 4).In the fourth sample, Okabe can take the path , paying when moving to (1, 2), (3, 4), and (5, 4).
|
Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren.Okabe's city is represented by a 2D grid of cells. Rows are numbered from 1 to n from top to bottom, and columns are numbered 1 to m from left to right. Exactly k cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit.Okabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays 1 coin, allowing him to walk through some cells not lit initially. Note that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit.Help Okabe find the minimum number of coins he needs to pay to complete his walk!
|
Print the minimum number of coins Okabe needs to pay to complete his walk, or -1 if it's not possible.
|
The first line of input contains three space-separated integers n, m, and k (2 ≤ n, m, k ≤ 104). Each of the next k lines contains two space-separated integers ri and ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m) — the row and the column of the i-th lit cell. It is guaranteed that all k lit cells are distinct. It is guaranteed that the top-left cell is lit.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_062.jsonl
|
e824cc9dbd2407eff33fca75ac9e0e47
|
256 megabytes
|
["4 4 5\n1 1\n2 1\n2 3\n3 3\n4 3", "5 5 4\n1 1\n2 1\n3 1\n3 2", "2 2 4\n1 1\n1 2\n2 1\n2 2", "5 5 4\n1 1\n2 2\n3 3\n4 4"]
|
PASSED
|
from sys import stdin
from collections import deque
def main():
n, m, k = map(int, stdin.readline().split())
a = [map(int, stdin.readline().split()) for _ in xrange(k)]
row = [dict() for i in xrange(n + 10)]
col = [dict() for i in xrange(m + 10)]
inf = 10010001
d = [inf] * k
q = []
pu = q.append
for i in xrange(k):
r, c = a[i]
row[r][c] = i
col[c][r] = i
if r == c == 1:
d[i] = 0
pu(i)
done = [None] * k
while q:
v = []
for x in q:
r, c = a[x]
qq = deque()
qq.append(x)
done[x] = 1
while qq:
y = qq.popleft()
r, c = a[y]
for cc in (c-1, c+1):
if cc in row[r] and done[row[r][cc]] is None:
z = row[r][cc]
done[z] = 1
qq.append(z)
for rr in (r-1, r+1):
if rr in col[c] and done[col[c][rr]] is None:
z = col[c][rr]
done[z] = 1
qq.append(z)
d[y] = d[x]
v.append(y)
sr = set()
sc = set()
del q[:]
for x in v:
r, c = a[x]
for rr in xrange(r - 2, r + 3):
sr.add(rr)
for cc in xrange(c - 2, c + 3):
sc.add(cc)
for i in sr:
for j in row[i].viewvalues():
if d[j] == inf:
d[j] = d[x] + 1
pu(j)
row[i] = {}
for i in sc:
for j in col[i].viewvalues():
if d[j] == inf:
d[j] = d[x] + 1
pu(j)
col[i] = {}
ans = inf
for i in xrange(k):
r, c = a[i]
if r == n and c == m:
if ans > d[i]:
ans = d[i]
if r >= n - 1:
if ans > d[i] + 1:
ans = d[i] + 1
if c >= m - 1:
if ans > d[i] + 1:
ans = d[i] + 1
if ans == inf:
print -1
else:
print ans
main()
|
1498401300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["5\n10\n5\n2\n5\n3\n1\n0", "49\n35\n24\n29\n49\n39\n31\n23\n29\n27", "1332632508\n1333333000"]
|
c72b1a45f5cf80a31c239cf1409c0104
| null |
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered top to bottom, the columns are numbered left to right.Each cell of the matrix can be either free or locked.Let's call a path in the matrix a staircase if it: starts and ends in the free cell; visits only free cells; has one of the two following structures: the second cell is $$$1$$$ to the right from the first one, the third cell is $$$1$$$ to the bottom from the second one, the fourth cell is $$$1$$$ to the right from the third one, and so on; the second cell is $$$1$$$ to the bottom from the first one, the third cell is $$$1$$$ to the right from the second one, the fourth cell is $$$1$$$ to the bottom from the third one, and so on. In particular, a path, consisting of a single cell, is considered to be a staircase.Here are some examples of staircases: Initially all the cells of the matrix are free.You have to process $$$q$$$ queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
|
Print $$$q$$$ integers — the $$$i$$$-th value should be equal to the number of different staircases after $$$i$$$ queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
|
The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000$$$; $$$1 \le q \le 10^4$$$) — the sizes of the matrix and the number of queries. Each of the next $$$q$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x \le n$$$; $$$1 \le y \le m$$$) — the description of each query.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_090.jsonl
|
413ca9100c30f80ee9eaf5cb2abae5fe
|
256 megabytes
|
["2 2 8\n1 1\n1 1\n1 1\n2 2\n1 1\n1 2\n2 1\n1 1", "3 4 10\n1 4\n1 2\n2 3\n1 2\n2 3\n3 2\n1 3\n3 4\n1 3\n3 1", "1000 1000 2\n239 634\n239 634"]
|
PASSED
|
class SplayTree():
def __init__(self):
self.children={}
self.parents={}
self.root=None
def insert(self, x):
if self.root is None:
self.root=x
self.children[x]=[None,None]
self.parents[x]=None
else:
curr = self.root
while True:
if curr == x:
self.splay(x)
return None
elif x < curr:
if self.children[curr][0] is None:
self.children[curr][0] = x
self.children[x] = [None, None]
self.parents[x] = curr
self.splay(x)
return None
else:
curr = self.children[curr][0]
else:
if self.children[curr][1] is None:
self.children[curr][1] = x
self.children[x] = [None, None]
self.parents[x] = curr
self.splay(x)
return None
else:
curr = self.children[curr][1]
def find(self, x):
return x in self.parents
def delete(self, x, show=False):
if self.children[x][0] is None and self.children[x][1] is None:
if self.root == x:
self.root = None
del self.children[x]
p = self.parents[x]
del self.parents[x]
for i in range(2):
if self.children[p][i] == x:
self.children[p][i] = None
self.splay(p)
elif self.children[x][0] is None or self.children[x][1] is None:
if self.children[x][0] is None:
ind = 1
else:
ind = 0
child = self.children[x][ind]
if self.root == x:
self.root = child
del self.children[x]
del self.parents[x]
self.parents[child] = None
else:
p = self.parents[x]
self.parents[child] = p
for i in range(2):
if self.children[p][i] == x:
self.children[p][i] = child
del self.parents[x]
del self.children[x]
self.splay(p)
else:
s = self.successor(x)
if self.parents[s] == x:
skids = self.children[s][:]
xkid = self.children[x][0]
xpar = self.parents[x]
self.children[s] = [xkid, x]
self.parents[s] = xpar
self.children[x] = skids
self.parents[x] = s
for i in skids:
if i is not None:
self.parents[i] = x
if xkid is not None:
self.parents[xkid] = s
if xpar is not None:
for i in range(2):
if self.children[xpar][i] == x:
self.children[xpar][i] = s
if self.root == x:
self.root = s
self.delete(x)
if xpar is not None:
self.splay(xpar)
else:
skids = self.children[s][:]
spar = self.parents[s]
xkids = self.children[x][:]
xpar = self.parents[x]
self.children[s] = xkids
self.parents[s] = xpar
self.children[x] = skids
self.parents[x] = spar
for i in skids:
if i is not None:
self.parents[i] = x
for i in xkids:
if i is not None:
self.parents[i] = s
for i in range(2):
if spar is not None and self.children[spar][i] == s:
self.children[spar][i] = x
if xpar is not None and self.children[xpar][i] == x:
self.children[xpar][i] = s
if self.root == x:
self.root = s
if show:
print(self.children)
print(self.parents)
print(self.root)
self.delete(x)
if xpar is not None:
self.splay(xpar)
def successor(self,x):
if self.find(x):
if self.children[x][1] is None:
curr = x
while self.parents[curr] is not None:
if self.parents[curr] > curr:
return self.parents[curr]
curr = self.parents[curr]
return None
else:
curr = self.children[x][1]
while self.children[curr][0] is not None:
curr = self.children[curr][0]
return curr
else:
curr = self.root
prev = None
while True:
if x < curr:
if self.children[curr][0] is None:
self.splay(curr)
return curr
else:
prev = curr
curr = self.children[curr][0]
else:
if self.children[curr][1] is None:
if prev is not None:
self.splay(prev)
return prev
else:
curr = self.children[curr][1]
def predecessor(self,x):
if self.find(x):
if self.children[x][0] is None:
curr = x
while self.parents[curr] is not None:
if self.parents[curr] < curr:
return self.parents[curr]
curr = self.parents[curr]
return None
else:
curr = self.children[x][0]
while self.children[curr][1] is not None:
curr = self.children[curr][1]
return curr
else:
curr = self.root
prev = None
while True:
if x > curr:
if self.children[curr][1] is None:
self.splay(curr)
return curr
else:
prev = curr
curr = self.children[curr][1]
else:
if self.children[curr][0] is None:
if prev is not None:
self.splay(prev)
return prev
else:
curr = self.children[curr][0]
def splay(self, x):
while self.parents[x] is not None:
p = self.parents[x]
gp = self.parents[p]
if gp is None:
if p > x:
a,b = self.children[x]
c = self.children[p][1]
self.children[x] = [a,p]
self.children[p] = [b,c]
self.parents[x] = None
self.parents[p] = x
self.parents[b] = p
self.root = x
else:
a = self.children[p][0]
b,c = self.children[x]
self.children[x] = [p,c]
self.children[p] = [a,b]
self.parents[x] = None
self.parents[p] = x
self.parents[b] = p
self.root = x
else:
ggp = self.parents[gp]
if p > x and gp > x:
a,b = self.children[x]
c = self.children[p][1]
d = self.children[gp][1]
self.children[x] = [a,p]
self.children[p] = [b,gp]
self.children[gp] = [c,d]
self.parents[x] = ggp
self.parents[p] = x
self.parents[gp] = p
self.parents[b] = p
self.parents[c] = gp
elif p < x and gp < x:
c,d = self.children[x]
b = self.children[p][0]
a = self.children[gp][0]
self.children[x] = [p,d]
self.children[p] = [gp,c]
self.children[gp] = [a,b]
self.parents[x] = ggp
self.parents[p] = x
self.parents[gp] = p
self.parents[b] = gp
self.parents[c] = p
elif p < x and gp > x:
b,c = self.children[x]
a = self.children[p][0]
d = self.children[gp][1]
self.children[x] = [p,gp]
self.children[p] = [a,b]
self.children[gp] = [c,d]
self.parents[x] = ggp
self.parents[p] = x
self.parents[gp] = x
self.parents[b] = p
self.parents[c] = gp
else:
b,c = self.children[x]
d = self.children[p][1]
a = self.children[gp][0]
self.children[x] = [gp,p]
self.children[p] = [c,d]
self.children[gp] = [a,b]
self.parents[x] = ggp
self.parents[p] = x
self.parents[gp] = x
self.parents[b] = gp
self.parents[c] = p
if ggp is not None:
for i in range(2):
if self.children[ggp][i] == gp:
self.children[ggp][i] = x
else:
self.root = x
if None in self.parents:
del self.parents[None]
n,m,q = map(int,input().split())
diag = {}
for i in range(-m,n+1):
diag[i] = SplayTree()
diag[i].insert(max(0,i))
diag[i].insert(min(n+1,m+1+i))
total = 0
j = n
k = m
while j>0 and k>0:
total += 2*j*k
total += j*(k-1)
total += k*(j-1)
j-=1
k-=1
total -= n*m
for _ in range(q):
x, y = map(int, input().split())
diff = x-y
pred = diag[diff].predecessor(x)
succ = diag[diff].successor(x)
predup = diag[diff-1].predecessor(x)
succup = diag[diff-1].successor(x-1)
preddown = diag[diff+1].predecessor(x+1)
succdown = diag[diff+1].successor(x)
beforeup = min(2*(x-pred)-1,2*(x-predup)-2)
afterup = min(2*(succ-x)-1,2*(succup-x))
beforedown = min(2*(x-pred)-1,2*(x-preddown))
afterdown = min(2*(succ-x)-1,2*(succdown-x)-2)
change = (beforeup+1)*(afterup+1) + (beforedown+1)*(afterdown+1) - 1
if diag[diff].find(x):
total += change
diag[diff].delete(x)
else:
total -= change
diag[diff].insert(x)
print(total)
|
1633856700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "2"]
|
7b56edf7cc71a1b3e39b3057a4387cad
|
NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.
|
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.
|
Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.
|
The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_004.jsonl
|
8d06b5826ffd382a4a7a37ee3ed10469
|
256 megabytes
|
["8\n10000011", "2\n01"]
|
PASSED
|
n = int(input())
t = [int(i) for i in input()]
ch = 0
sm = 0
for i in range(n-1):
if t[i] == t[i+1]:
sm+=1
else:
ch+=1
print(ch + min(sm,2) + 1)
|
1448984100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["8\n19"]
|
00b1e45e9395d23e850ce1a0751b8378
|
NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.
|
You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves: decrease $$$n$$$ by $$$1$$$; divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.
|
For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_019.jsonl
|
1e3f3ddc813e321a7fc03e354a546f31
|
256 megabytes
|
["2\n59 3\n1000000000000000000 10"]
|
PASSED
|
t=int(input())
for _ in range(t):
n,k = map(int,input().split())
counter=0
while(n!=0):
if(n%k==0):
n=n//k
counter+=1
else:
counter+=(n%k)
n=n-(n%k)
print(int(counter))
|
1559745300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0001111111\n001\n01\n0\n1"]
|
bb071f1f4fc1c129a32064c1301f4942
|
NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\rightarrow$$$ 1100101 $$$\rightarrow$$$ 110101 $$$\rightarrow$$$ 10101 $$$\rightarrow$$$ 1101 $$$\rightarrow$$$ 101 $$$\rightarrow$$$ 01.
|
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.
|
Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).
|
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,200 |
train_002.jsonl
|
6d75cb443fc90476dfd18173d04668c7
|
256 megabytes
|
["5\n10\n0001111111\n4\n0101\n8\n11001101\n10\n1110000000\n1\n1"]
|
PASSED
|
from sys import stdin
from collections import deque
# https://codeforces.com/contest/1354/status/D
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
from collections import Counter as cc
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f
# def ncr(x, y):
# return f(x) // (f(y) * f(x - y))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
import sys
# input = sys.stdin.readline
# LCA
# def bfs(na):
#
# queue = [na]
# boo[na] = True
# level[na] = 0
#
# while queue!=[]:
#
# z = queue.pop(0)
#
# for i in hash[z]:
#
# if not boo[i]:
#
# queue.append(i)
# level[i] = level[z] + 1
# boo[i] = True
# dp[i][0] = z
#
#
#
# def prec(n):
#
# for i in range(1,20):
#
# for j in range(1,n+1):
# if dp[j][i-1]!=-1:
# dp[j][i] = dp[dp[j][i-1]][i-1]
#
#
# def lca(u,v):
# if level[v] < level[u]:
# u,v = v,u
#
# diff = level[v] - level[u]
#
#
# for i in range(20):
# if ((diff>>i)&1):
# v = dp[v][i]
#
#
# if u == v:
# return u
#
#
# for i in range(19,-1,-1):
# # print(i)
# if dp[u][i] != dp[v][i]:
#
# u = dp[u][i]
# v = dp[v][i]
#
#
# return dp[u][0]
#
# dp = []
#
#
# n = int(input())
#
# for i in range(n + 10):
#
# ka = [-1]*(20)
# dp.append(ka)
# 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 find_kth_smallest(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
# import sys
# def rs(): return sys.stdin.readline().strip()
# def ri(): return int(sys.stdin.readline())
# def ria(): return list(map(int, sys.stdin.readline().split()))
# def prn(n): sys.stdout.write(str(n))
# def pia(a): sys.stdout.write(' '.join([str(s) for s in a]))
#
#
# import gc, os
#
# ii = 0
# _inp = b''
#
#
# def getchar():
# global ii, _inp
# if ii >= len(_inp):
# _inp = os.read(0, 100000)
# gc.collect()
# ii = 0
# if not _inp:
# return b' '[0]
# ii += 1
# return _inp[ii - 1]
#
#
# def input():
# c = getchar()
# if c == b'-'[0]:
# x = 0
# sign = 1
# else:
# x = c - b'0'[0]
# sign = 0
# c = getchar()
# while c >= b'0'[0]:
# x = 10 * x + c - b'0'[0]
# c = getchar()
# if c == b'\r'[0]:
# getchar()
# return -x if sign else x
# fenwick Tree
# n,q = map(int,input().split())
#
#
# l1 = list(map(int,input().split()))
#
# l2 = list(map(int,input().split()))
#
# bit = [0]*(10**6 + 1)
#
# def update(i,add,bit):
#
# while i>0 and i<len(bit):
#
# bit[i]+=add
# i = i + (i&(-i))
#
#
# def sum(i,bit):
# ans = 0
# while i>0:
#
# ans+=bit[i]
# i = i - (i & ( -i))
#
#
# return ans
#
# def find_smallest(k,bit):
#
# l = 0
# h = len(bit)
# while l<h:
#
# mid = (l+h)//2
# if k <= sum(mid,bit):
# h = mid
# else:
# l = mid + 1
#
#
# return l
#
#
# def insert(x,bit):
# update(x,1,bit)
#
# def delete(x,bit):
# update(x,-1,bit)
# fa = set()
#
# for i in l1:
# insert(i,bit)
#
#
# for i in l2:
# if i>0:
# insert(i,bit)
#
# else:
# z = find_smallest(-i,bit)
#
# delete(z,bit)
#
#
# # print(bit)
# if len(set(bit)) == 1:
# print(0)
# else:
# for i in range(1,n+1):
# z = find_smallest(i,bit)
# if z!=0:
# print(z)
# break
#
# service time problem
# def solve2(s,a,b,hash,z,cnt):
# temp = cnt.copy()
# x,y = hash[a],hash[b]
# i = 0
# j = len(s)-1
#
# while z:
#
# if s[j] - y>=x-s[i]:
# if temp[s[j]]-1 == 0:
# j-=1
# temp[s[j]]-=1
# z-=1
#
#
# else:
# if temp[s[i]]-1 == 0:
# i+=1
#
# temp[s[i]]-=1
# z-=1
#
# return s[i:j+1]
#
#
#
#
#
# def solve1(l,s,posn,z,hash):
#
# ans = []
# for i in l:
# a,b = i
# ka = solve2(s,a,b,posn,z,hash)
# ans.append(ka)
#
# return ans
#
# def consistent(input, window, min_entries, max_entries, tolerance):
#
# l = input
# n = len(l)
# l.sort()
# s = list(set(l))
# s.sort()
#
# if min_entries<=n<=max_entries:
#
# if s[-1] - s[0]<window:
# return True
# hash = defaultdict(int)
# posn = defaultdict(int)
# for i in l:
# hash[i]+=1
#
# z = (tolerance*(n))//100
# poss_window = set()
#
#
# for i in range(len(s)):
# posn[i] = l[i]
# for j in range(i+1,len(s)):
# if s[j]-s[i] == window:
# poss_window.add((s[i],s[j]))
#
# if poss_window!=set():
# print(poss_window)
# ans = solve1(poss_window,s,posn,z,hash)
# print(ans)
#
#
# else:
# pass
#
# else:
# return False
#
#
#
#
# l = list(map(int,input().split()))
#
# min_ent,max_ent = map(int,input().split())
# w = int(input())
# tol = int(input())
# consistent(l, w, min_ent, max_ent, tol)
# t = int(input())
#
# for i in range(t):
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# e,o = 0,0
#
# for i in l:
# if i%2 == 0:
# e+=1
# else:
# o+=1
#
# if e+o>=x and o!=0:
# z = e+o - x
# if z == 0:
# if o%2 == 0:
# print('No')
# else:
# print('Yes')
# continue
# if o%2 == 0:
# o-=1
# z-=1
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
#
# else:
#
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
# else:
# print('No')
#
#
#
#
#
#
#
# def dfs(n):
# boo[n] = True
# dp2[n] = 1
# for i in hash[n]:
# if not boo[i]:
#
# dfs(i)
# dp2[n] += dp2[i]
#
#
# n = int(input())
# x = 0
# l = list(map(int,input().split()))
# for i in range(n):
#
# x = l[i]|x
#
# z = list(bin(x)[2:])
# ha = z.copy()
# k = z.count('1')
# ans = 0
# # print(z)
# cnt = 0
# for i in range(20):
#
#
# maxi = 0
# idx = -1
#
# for j in range(n):
# k = bin(l[j])[2:]
# k = '0'*(len(z) -len(k)) + k
# cnt = 0
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# cnt+=1
#
# maxi = max(maxi,cnt)
# if maxi == cnt:
# idx = j
# if idx!=-1:
#
# k = bin(l[idx])[2:]
# k = '0'*(len(z) -len(k)) + k
#
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# z[i] = '0'
# l[idx] = 0
#
#
# ans = 0
# for i in range(len(z)):
# if z[i] == '0' and ha[i] == '1':
# ans+=1
# flip = 0
# for i in range(ans):
# flip+=2**i
#
#
#
# print(flip)
# def search(k,l,low):
#
# high = len(l)-1
# z = bisect_left(l,k,low,high)
#
# return z
#
#
#
#
#
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# prefix = [0]
# ha = [0]
# for i in l:
# prefix.append(i + prefix[-1])
# ha.append((i*(i+1))//2 + ha[-1])
# fin = 0
# print(prefix)
# for i in range(n):
# ans = 0
# if l[i]<x:
#
#
# if prefix[-1]-prefix[i]>=x:
#
# z = search(x+prefix[i],prefix,i+1)
# print(z)
# z+=i+1
# k1 = x-(prefix[z-1]-prefix[i])
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
# else:
# z1 = x - (prefix[-1]-prefix[i])
# z = search(z1,prefix,1)
#
# k1 = x-prefix[z-1]
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
#
#
# elif l[i]>x:
# z1 = ((l[i])*(l[i]+1))//2
# z2 = ((l[i]-x)*(l[i]-x+1))//2
# ans+=z1-z2
# else:
# ans+=(x*(x+1))//2
# t = int(input())
#
# for _ in range(t):
#
# s = list(input())
# ans = [s[0]]
#
# for i in range(1,len(s)-1,2):
# ans.append(s[i])
#
# ans.append(s[-1])
# print(''.join(ans))
#
#
#
# t = int(input())
#
# for _ in range(t):
#
# n = int(input())
# l = list(map(int,input().split()))
# ans = 0
# for i in range(n):
# if l[i]%2!=i%2:
# ans+=1
#
# if ans%2 == 0:
# print(ans//2)
# else:
# print(-1)
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# s = input()
#
#
# ans = 0
# ba = []
# for i in range(n):
# if s[i] == '1':
# ba.append(i)
# if ba == []:
# for i in range(0,n,k+1):
# ans+=1
#
# print(ans)
# continue
#
# i = s.index('1')
# c = 0
# for x in range(i-1,-1,-1):
# if c == k:
# c = 0
# ans+=1
# else:
# c+=1
#
#
# while i<len(s):
# count = 0
# dis = 0
# while s[i] == '0':
# dis+=1
# if dis == k:
# dis = 0
# count+=1
# if dis<k and s[i] == '1':
# count-=1
# break
# i+=1
# if i == n:
# break
# i+=1
#
# print(ans)
#
#
#
#
# q1
# def poss1(x):
# cnt = 1
# mini = inf
# for i in l:
# if cnt%2 != 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# mini = min()
# if cnt == k:
# return
#
# return -1
#
#
#
#
# def poss2(x):
# cnt = 1
# for i in l:
# if cnt%2 == 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# if cnt == k:
# return
#
# return -1
#
#
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# z1 = min(l)
# z2 = max(l)
#
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# l1 = list(map(int,input().split()))
# l.sort(reverse=True)
# l1.sort()
# for i in range(k):
# l1[i]-=1
#
# i = 0
# j = k
# x = 0
# ans = sum(l[:k])
# # print(l)
# # print(l1)
# # print(ans)
# while x<k:
# cnt = 1
# z = l1[x]
# while z>cnt:
# j+=1
# cnt+=1
#
# if z == 0:
# ans+=l[i]
# i+=1
# else:
# # print(j,z)
# ans+=l[j]
#
# i+=1
# j+=1
# x+=1
#
# print(ans)
#
#
t = int(input())
for _ in range(t):
n = int(input())
s = input()
if '1' not in s:
print(s)
continue
if '0' not in s:
print(s)
continue
if n == 1:
print(s)
continue
z1 = n-s[::-1].index('0')-1
z2 = s.index('1')
if z1>z2:
print(s[:z2] + '0' + s[z1+1:])
else:
print(s)
|
1592921100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.