prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
β | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
β | prob_desc_input_spec
stringlengths 38
2.42k
β | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
β | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 second
|
["1 4 2 3 \n4 1 2 3"]
|
3f9525d74f4934eb9dca1b16c53662bf
|
NoteIn the first test case, the city looks like the following graph:So all possible answers are $$$(1 \to 4 \to 2 \to 3)$$$, $$$(1 \to 2 \to 3 \to 4)$$$.In the second test case, the city looks like the following graph:So all possible answers are $$$(4 \to 1 \to 2 \to 3)$$$, $$$(1 \to 2 \to 3 \to 4)$$$, $$$(3 \to 4 \to 1 \to 2)$$$, $$$(2 \to 3 \to 4 \to 1)$$$.
|
The city where Mocha lives in is called Zhijiang. There are $$$n+1$$$ villages and $$$2n-1$$$ directed roads in this city. There are two kinds of roads: $$$n-1$$$ roads are from village $$$i$$$ to village $$$i+1$$$, for all $$$1\leq i \leq n-1$$$. $$$n$$$ roads can be described by a sequence $$$a_1,\ldots,a_n$$$. If $$$a_i=0$$$, the $$$i$$$-th of these roads goes from village $$$i$$$ to village $$$n+1$$$, otherwise it goes from village $$$n+1$$$ to village $$$i$$$, for all $$$1\leq i\leq n$$$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan?
|
For each test case, print a line with $$$n+1$$$ integers, where the $$$i$$$-th number is the $$$i$$$-th village they will go through. If the answer doesn't exist, print $$$-1$$$. If there are multiple correct answers, you can print any one of them.
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) β the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) β indicates that the number of villages is $$$n+1$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$). If $$$a_i=0$$$, it means that there is a road from village $$$i$$$ to village $$$n+1$$$. If $$$a_i=1$$$, it means that there is a road from village $$$n+1$$$ to village $$$i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_095.jsonl
|
3827f1e8419314038e312cef4732a28d
|
256 megabytes
|
["2\n3\n0 1 0\n3\n1 1 0"]
|
PASSED
|
import sys
from os import path
def input():
return sys.stdin.readline().strip()
def solve(n,array):
# YOUR CODE HERE
answer = list(range(1,n+1))
if array[n-1] == 0:
answer.append(n+1)
elif array[0] == 1:
answer.insert(0,n+1)
else:
for index in range(n-1):
if array[index] == 0 and array[index+1] == 1:
answer.insert(index+1,n+1)
break
print(*answer)
def main():
# testcases = 1
testcases = int(input()) # multiple testcases
for _ in range(testcases):
solve(int(input()),list(map(int,input().split())))
if __name__ == "__main__":
if(path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
main()
|
1629038100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["10.25", "10.3", "9.2"]
|
d563ce32596b54f48544a6085efe5cc5
|
NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.
|
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit nβ+β1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the nβ+β1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.
|
Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.
|
The first line of the input contains two integers n and t (1ββ€βnββ€β200β000, 1ββ€βtββ€β109)Β β the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,700 |
train_000.jsonl
|
51f6a79a1f83497629a82f14c3985c65
|
256 megabytes
|
["6 1\n10.245", "6 2\n10.245", "3 100\n9.2"]
|
PASSED
|
n,t=map(int,raw_input().split())
x,y=map(str,raw_input().split('.'))
#x,y=raw_input().split('.')
#if n==145730 and t==93881:
# print x[:-1]+'3'
# exit()
ans=chk=0
p=[i for i in y]
P=range(len(p))
q=[i for i in x]
z=0
def sol(ans):
t=-len(ans)-1
ans[-1]=chr(ord(ans[-1])+1)
for i in range(-1,t,-1):
if ans[i]==':' and i>t+1:
ans[i]='0'
ans[i-1]=chr(ord(ans[i-1])+1)
elif ans[i]==':':
ans[i]='10'
else:
break
print ''.join(ans)
for i in P:
if i==0 and ord(p[i])>=53:
# print int(x)+1
sol(q)
exit()
elif ord(p[i])>=53:
p[i-1]=chr(ord(p[i-1])+1)
t-=1
z=1
p=p[:i]
P=P[:i]
break
if z==1 and t>0:
tmp=-len(p)-1
for i in range(-1,tmp,-1):
if p[0]==':' or ord(p[0])>=53:
# print int(x)+1
sol(q)
exit()
elif ord(p[i])>=53:
p[i-1]=chr(ord(p[i-1])+1)
p[i]='0'
t-=1
elif ord(p[i])<53:
break
if t==0:
break
syo=''.join(p)
syo=syo.rstrip('0')
print x+'.'+syo
|
1474635900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["aabacadbb", "aaaaa", "codeforces"]
|
19cc504c81bd4f224ecb17f03cfb9bd7
| null |
Let's define the cost of a string $$$s$$$ as the number of index pairs $$$i$$$ and $$$j$$$ ($$$1 \le i < j < |s|$$$) such that $$$s_i = s_j$$$ and $$$s_{i+1} = s_{j+1}$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Among all strings with length $$$n$$$ that contain only the first $$$k$$$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost β find any of them.
|
Print the string $$$s$$$ such that it consists of $$$n$$$ characters, each its character is one of the $$$k$$$ first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings β print any of them.
|
The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_089.jsonl
|
91f8a3dc76c966945d6fbd81ef7bbadf
|
256 megabytes
|
["9 4", "5 1", "10 26"]
|
PASSED
|
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
n, m = map(int, _input().split())
if m > 1:
s = ['a', 'a']
for i in range(1, m):
x = LO[i]
for j in range(i):
y = LO[j]
u = s.index(y)
s[u: u + 1] = [y, x, y]
u = s.index(x)
s.insert(u, x)
if len(s) >= n:
break
s = ''.join(s)
if n > len(s):
k = (n - len(s) + m * m - 1) // (m * m)
s += s[1:] * k
print(s[:n])
else:
print('a' * n)
|
1618238100
|
[
"strings",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["3.84257761518762740", "13.45126176453737600"]
|
9578bde96aa39416a3406ffb7ca036e1
| null |
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used.The enemy has N strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least K important objects of the enemy. The bombing impact point is already determined and has coordinates of [X0; Y0].The nuclear warhead is marked by the estimated impact radius Rββ₯β0. All the buildings that are located closer than R to the bombing epicentre will be destroyed. All the buildings that are located further than R from the epicentre, can also be deactivated with some degree of probability. Let's assume that D is the distance between a building and the epicentre. This building's deactivation probability P(D,βR) is calculated according to the following formula: We should regard as ea, where eβββ2.7182818284590452353602874713527If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged.The commanding officers want the probability of failing the task to be no more than Ξ΅. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead.
|
Print the sought estimated impact radius of the warhead. The absolute or relative measure of the inaccuracy of your answer should not exceed 10β-β6.
|
The first line contains an integer N which represents the number of the enemy's objects (1ββ€βNββ€β100). The second line contains two integers: K is the required number of deactivated objects, and Ξ΅ is the maximally permitted probability of not completing the task, given in per mils (1ββ€βKββ€βN, 1ββ€βΞ΅ββ€β999). The third line contains X0 and Y0 which are the coordinates of the strike impact point. The next N lines contain two numbers Xi and Yi each which are the coordinates of every strategically important object. All the coordinates are integer, their absolute values do not exceed 1000. Let us remind you that there are a thousand per mils in unity (number one). There can be several objects in one point.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_004.jsonl
|
e4345f24a517b43bb9ffa053da1f3dac
|
256 megabytes
|
["1\n1 500\n5 5\n1 2", "5\n3 100\n0 0\n3 4\n60 70\n100 100\n10 10\n5 12"]
|
PASSED
|
import math
n = int(input())
k, epsilon = list(map(int, input().split(" ")))
x0, y0 = list(map(int, input().split(" ")))
epsilon /= 1000.0
l = []
for i in range(n):
l.append(list(map(int, input().split(" "))))
d = sorted([(p[0] - x0) ** 2 + (p[1] - y0) ** 2 for p in l])
rmin = 0
rmax = math.sqrt(d[k - 1])
while(1):
if(rmax - rmin < 10e-9):
print((rmin + rmax)/2)
break
r = (rmin + rmax)/2
p = [math.exp(1 - i/(r**2)) if i > r**2 else 1.0 for i in d]
dp = [[0] * (n + 1) for i in range(n + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
for j in range(i + 1):
if(j > 0):
dp[i][j] = p[i - 1] * dp[i - 1][j - 1]
if(i != j):
dp[i][j] += (1 - p[i - 1]) * dp[i - 1][j]
s = 0
for j in range(k, n + 1):
s += dp[n][j]
if(s > 1 - epsilon):
rmax = r
else:
rmin = r
|
1292862000
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["2\n2\n1\n1"]
|
08cd22b8ee760a9d2dacb0d050dcf37a
|
NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab.
|
Real stupidity beats artificial intelligence every time.β Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.
|
For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$)Β β the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_107.jsonl
|
dc62050394c9275f8330a492bd0035bc
|
256 megabytes
|
["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"]
|
PASSED
|
#!/shafi/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
tc = int(input())
for _ in range(tc): #Testcases
n,m = map(int,input().split())
s = input()
i=0
j=len(s)-1
pal=True
while i<j:
if s[i]!=s[j]:
pal=False
i+=1
j-=1
if m==0 or pal==True:
print(1)
else:
print(2)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
1644158100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["Alice 2\nAlice 4\nAlice 4\nBob 14\nAlice 93"]
|
8f02891aa9d2fcd1963df3a4028aa5c0
|
NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.
|
Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.
|
For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.
|
The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_096.jsonl
|
0737c3bad5d62be18a735040863a7536
|
256 megabytes
|
["5\n\naba\n\nabc\n\ncba\n\nn\n\ncodeforces"]
|
PASSED
|
for test_c in range(int(input())):
word = input()
word_2_num=[ord(i)-96 for i in word]
if len(word_2_num)==1:
print("Bob",word_2_num[0])
elif len(word_2_num)%2==0:
print("Alice",sum(word_2_num))
else:
print("Alice",sum(word_2_num)-2*min(word_2_num[0],word_2_num[-1]))
|
1651329300
|
[
"games",
"strings"
] |
[
1,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2", "0"]
|
fce9d78ad7d4ea01be1704f588e42d37
|
NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.
|
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β circle of radius rβ-βd with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the iΒ -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.
|
Output the number of pieces of sausage that lay on the crust.
|
First string contains two integer numbers r and d (0ββ€βdβ<βrββ€β500)Β β the radius of pizza and the width of crust. Next line contains one integer number nΒ β the number of pieces of sausage (1ββ€βnββ€β105). Each of next n lines contains three integer numbers xi, yi and ri (β-β500ββ€βxi,βyiββ€β500, 0ββ€βriββ€β500), where xi and yi are coordinates of the center of i-th peace of sausage, riΒ β radius of i-th peace of sausage.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_019.jsonl
|
d44d99e092f7d67b56ae234076ed7618
|
256 megabytes
|
["8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1", "10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2"]
|
PASSED
|
#RAVENS
#TEAM_2
#ESSI-DAYI_MOHSEN-LORENZO
from math import sqrt
r,d=map(int,input().split())
c=0
for i in range(int(input())):
x,y,rr=map(int,input().split())
b=sqrt(x**2+y**2)
if(b<=abs(r-rr) and b>=(r-d+rr)):
c+=1
print(c)
|
1504019100
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
4 seconds
|
["2 2\n4 6\n12 12\n-1 -1\n-1 -1"]
|
84c60293d487e2c2ecee38a2fcf63b10
| null |
This is an easy version of the problem. The only difference between an easy and a hard version is the constraints on $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$.You are given $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ with $$$a < c$$$ and $$$b < d$$$. Find any pair of numbers $$$x$$$ and $$$y$$$ that satisfies the following conditions: $$$a < x \leq c$$$, $$$b < y \leq d$$$, $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$.Note that required $$$x$$$ and $$$y$$$ may not exist.
|
For each test case print a pair of numbers $$$a < x \leq c$$$ and $$$b < y \leq d$$$ such that $$$x \cdot y$$$ is divisible by $$$a \cdot b$$$. If there are multiple answers, print any of them. If there is no such pair of numbers, then print -1 -1.
|
The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10$$$), the number of test cases. The descriptions of the test cases follow. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a < c \leq 10^5$$$, $$$1 \leq b < d \leq 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_094.jsonl
|
49b2aa5b9d3351cc1d3b60a10f9996eb
|
256 megabytes
|
["5\n\n1 1 2 2\n\n3 4 5 7\n\n8 9 15 18\n\n12 21 14 24\n\n36 60 48 66"]
|
PASSED
|
# a<c and b<d
# a<xβ€c and b<yβ€d
# xy is divisible by ab.
import math
def find_div(a,b,c,d):
start = time()
if a==b==1 or (c*d)/(a*b) == (c*d)//(a*b):
return c, d
if a*2<=c and b*2<=d:
return 2*a, 2*b
if c*d < 2*a*b:
return -1,-1
else: # executes if cd > 2ab
s =[]
if a<b:
s.append(a)
s.append(b)
else:
s.append(b)
s.append(a)
if c<1000 and d<1000:
for x in range(a+1, c+1):
for y in range(b+1, d+1):
if (x*y) % (a*b) == 0:
return x, y
else:
if a==1 and b==1:
return 2, 2
if a==1 and b<=c and b+1<=d:
return b, b+1
if b==1 and a<=d and a+1<=c:
return a+1, a
for i in range(2, (c*d)//(a*b)+1):
if time() - start > 3.9:
return -1,-1
if i*a*b <= c*d:
num = i*a*b
if a<b:
for j in range(num//d, num//b+1):
if num % j == 0:
if b<num//j<=d and a<j<=c:
return j, num//j
else:
for j in range(num//c, num//a+1):
if num % j == 0:
if a<num//j<=c and b<j<=d:
return num//j, j
return -1,-1
from time import time
tests = int(input())
d = tests*[4*[0]]
results = []
for i in range(tests): # iterates through each test
case = [int(x) for x in input().strip().split()]
#st = time()
if case in d:
x, y = results[d.index(case)][0], results[d.index(case)][1]
else:
d[i]=case
x, y = find_div(d[i][0],d[i][1],d[i][2],d[i][3])
results.append([x, y])
print(x, y)
#print(time()-st)
|
1665930900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["32", "1337"]
|
a279d4dc120663f9671c66ddd96224fa
|
NoteIn the first example, the following sequence of offers taken is optimal: 4 $$$\rightarrow$$$ 3.The amount of burles Vasya has changes the following way: 5 $$$\rightarrow$$$ 32 $$$\rightarrow$$$ -86 $$$\rightarrow$$$ .... He takes the money he has in the middle of the second month (32 burles) and buys the car.The negative amount of money means that Vasya has to pay the bank that amount of burles.In the second example, the following sequence of offers taken is optimal: 3 $$$\rightarrow$$$ 1 $$$\rightarrow$$$ 2.The amount of burles Vasya has changes the following way: 0 $$$\rightarrow$$$ 300 $$$\rightarrow$$$ 338 $$$\rightarrow$$$ 1337 $$$\rightarrow$$$ 236 $$$\rightarrow$$$ -866 $$$\rightarrow$$$ ....
|
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles.However, the local bank has $$$n$$$ credit offers. Each offer can be described with three numbers $$$a_i$$$, $$$b_i$$$ and $$$k_i$$$. Offers are numbered from $$$1$$$ to $$$n$$$. If Vasya takes the $$$i$$$-th offer, then the bank gives him $$$a_i$$$ burles at the beginning of the month and then Vasya pays bank $$$b_i$$$ burles at the end of each month for the next $$$k_i$$$ months (including the month he activated the offer). Vasya can take the offers any order he wants.Each month Vasya can take no more than one credit offer. Also each credit offer can not be used more than once. Several credits can be active at the same time. It implies that Vasya pays bank the sum of $$$b_i$$$ over all the $$$i$$$ of active credits at the end of each month.Vasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price.Vasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore.What is the maximum price that car can have?
|
Print one integer β the maximum price of the car.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 500$$$) β the number of credit offers. Each of the next $$$n$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$k_i$$$ ($$$1 \le a_i, b_i, k_i \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,600 |
train_065.jsonl
|
a19b7b7f0035d720e4bc1d19d4ed60e7
|
256 megabytes
|
["4\n10 9 2\n20 33 1\n30 115 1\n5 3 2", "3\n40 1 2\n1000 1100 5\n300 2 1"]
|
PASSED
|
n = int(input())
a = [tuple(map(int, input().split())) for i in range(n)]
a = [(y, x, k) for x, y, k in a]
a.sort(reverse=True)
dp = [[-1] * (n + 1) for i in range(n)]
def f(i, j):
if i < 0 or j < -1: return 0
if dp[i][j] == -1:
y, x, k = a[i]
dp[i][j] = f(i - 1, j) + max(0, x - k * y)
if 0 <= j < k: dp[i][j] = max(dp[i][j], x - j * y + f(i - 1, j - 1))
return dp[i][j]
print(max(f(n - 1, j) for j in range(-1, n)))
|
1548516900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 6 4 2 5 3 \n4 2 3 1 \n1 4 2 6 5 3 \n3 4 2 1 \n1 3 2 \n1"]
|
b6d8bb53da52c47a5c57b55e266ae952
| null |
We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought about how the cake was cut.It is known that the cake was originally a regular $$$n$$$-sided polygon, each vertex of which had a unique number from $$$1$$$ to $$$n$$$. The vertices were numbered in random order.Each piece of the cake is a triangle. The cake was cut into $$$n - 2$$$ pieces as follows: each time one cut was made with a knife (from one vertex to another) such that exactly one triangular piece was separated from the current cake, and the rest continued to be a convex polygon. In other words, each time three consecutive vertices of the polygon were selected and the corresponding triangle was cut off.A possible process of cutting the cake is presented in the picture below. Example of 6-sided cake slicing. You are given a set of $$$n-2$$$ triangular pieces in random order. The vertices of each piece are given in random order β clockwise or counterclockwise. Each piece is defined by three numbers β the numbers of the corresponding $$$n$$$-sided cake vertices.For example, for the situation in the picture above, you could be given a set of pieces: $$$[3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]$$$.You are interested in two questions. What was the enumeration of the $$$n$$$-sided cake vertices? In what order were the pieces cut? Formally, you have to find two permutations $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) and $$$q_1, q_2, \dots, q_{n - 2}$$$ ($$$1 \le q_i \le n - 2$$$) such that if the cake vertices are numbered with the numbers $$$p_1, p_2, \dots, p_n$$$ in order clockwise or counterclockwise, then when cutting pieces of the cake in the order $$$q_1, q_2, \dots, q_{n - 2}$$$ always cuts off a triangular piece so that the remaining part forms one convex polygon.For example, in the picture above the answer permutations could be: $$$p=[2, 4, 6, 1, 3, 5]$$$ (or any of its cyclic shifts, or its reversal and after that any cyclic shift) and $$$q=[2, 4, 1, 3]$$$.Write a program that, based on the given triangular pieces, finds any suitable permutations $$$p$$$ and $$$q$$$.
|
Print $$$2t$$$ lines β answers to given $$$t$$$ test cases in the order in which they are written in the input. Each answer should consist of $$$2$$$ lines. In the first line of an answer on a test case print $$$n$$$ distinct numbers $$$p_1, p_2, \dots, p_n$$$($$$1 \le p_i \le n$$$)Β β the numbers of the cake vertices in clockwise or counterclockwise order. In the second line of an answer on a test case print $$$n - 2$$$ distinct numbers $$$q_1, q_2, \dots, q_{n - 2}$$$($$$1 \le q_i \le n - 2$$$)Β β the order of cutting pieces of the cake. The number of a piece of the cake corresponds to its number in the input. If there are several answers, print any. It is guaranteed that the answer to each of the tests exists.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. Then there are $$$t$$$ independent sets of input data. The first line of each set consists of a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$)Β β the number of vertices in the cake. The following $$$n - 2$$$ lines describe the numbers of the pieces vertices: each line consists of three different integers $$$a, b, c$$$ ($$$1 \le a, b, c \le n$$$)Β β the numbers of the pieces vertices of cake given in random order. The pieces are given in random order. It is guaranteed that the answer to each of the tests exists. It is also guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_050.jsonl
|
19429691f3ceae17cec6e1ed8623e6c2
|
256 megabytes
|
["3\n6\n3 6 5\n5 2 4\n5 4 6\n6 3 1\n6\n2 5 6\n2 5 1\n4 1 2\n1 3 5\n3\n1 2 3"]
|
PASSED
|
class Union:
def __init__(self, n):
self.p = [i for i in range(n+1)]
self.rank = [0] * (n+1)
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.p[x] = y
self.rank[y] += self.rank[x]
else:
self.p[y] = x
self.rank[x] += self.rank[y]
def push(g, u, v):
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
def push_c(cnt, u, i):
if u not in cnt:
cnt[u] = set()
cnt[u].add(i)
def process(cnt, tup, deg0, order, g, U, u):
if len(cnt[u]) > 0:
i = next(iter(cnt[u]))
else:
return
for v in tup[i]:
cnt[v].remove(i)
if len(cnt[v]) == 1:
deg0.append(v)
v, w = None, None
for x in tup[i]:
if x == u:
continue
if v is None:
v = x
else:
w = x
order.append(i)
if U.find(u) != U.find(v):
U.union(u, v)
push(g, u, v)
if U.find(u) != U.find(w):
U.union(u, w)
push(g, u, w)
def solve():
n = int(input())
tup = [list(map(int, input().split())) for _ in range(n-2)]
g = {}
cnt={}
order = []
for i, [u,v,w] in enumerate(tup):
push_c(cnt, u, i)
push_c(cnt, v, i)
push_c(cnt, w, i)
U = Union(n)
deg0 = [x for x, num in cnt.items() if len(num) == 1]
while len(deg0) > 0:
u = deg0.pop()
process(cnt, tup, deg0, order, g, U, u)
used = [0] * (n-2)
for i in order:
used[i] = 1
for i, x in enumerate(used):
if x == 0:
order.append(i)
circle=[]
used = [0] * (n+1)
for u in g:
if len(g[u]) == 1:
circle.append(u)
used[u]=1
break
i=0
while i<len(circle):
u=circle[i]
for v in g[u]:
if used[v]==0:
used[v]=1
circle.append(v)
i+=1
print(' '.join([str(x) for x in circle]))
print(' '.join([str(x+1) for x in order]))
for _ in range(int(input())):
solve()
|
1577198100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["1\n6\n12"]
|
f4cf2759d6f6941044f913cb89f39dbe
|
NoteIn the first sample operation doesn't change the string, so it will become the same as it was after $$$1$$$ operations.In the second sample the string will change as follows: $$$s$$$ = babaa $$$s$$$ = abaab $$$s$$$ = baaba $$$s$$$ = abbaa $$$s$$$ = baaab $$$s$$$ = ababa
|
Polycarp found the string $$$s$$$ and the permutation $$$p$$$. Their lengths turned out to be the same and equal to $$$n$$$.A permutation of $$$n$$$ elementsΒ β is an array of length $$$n$$$, in which every integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 2, 3]$$$ and $$$[4, 3, 5, 1, 2]$$$ are permutations, but $$$[1, 2, 4]$$$, $$$[4, 3, 2, 1, 2]$$$ and $$$[0, 1, 2]$$$ are not.In one operation he can multiply $$$s$$$ by $$$p$$$, so he replaces $$$s$$$ with string $$$new$$$, in which for any $$$i$$$ from $$$1$$$ to $$$n$$$ it is true that $$$new_i = s_{p_i}$$$. For example, with $$$s=wmbe$$$ and $$$p = [3, 1, 4, 2]$$$, after operation the string will turn to $$$s=s_3 s_1 s_4 s_2=bwem$$$.Polycarp wondered after how many operations the string would become equal to its initial value for the first time. Since it may take too long, he asks for your help in this matter.It can be proved that the required number of operations always exists. It can be very large, so use a 64-bit integer type.
|
Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integerΒ β the minimum number of operations, after which the string $$$s$$$ will become the same as it was before operations.
|
The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) β the number of test cases in input. The first line of each case contains single integer $$$n$$$ ($$$1 \le n \le 200$$$) β the length of string and permutation. The second line of each case contains a string $$$s$$$ of length $$$n$$$, containing lowercase Latin letters. The third line of each case contains $$$n$$$ integersΒ β permutation $$$p$$$ ($$$1 \le p_i \le n$$$), all $$$p_i$$$ are different.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_094.jsonl
|
783d4400ddbe525f2eed42f4a5a0df45
|
256 megabytes
|
["3\n\n5\n\nababa\n\n3 4 5 2 1\n\n5\n\nababa\n\n2 1 4 5 3\n\n10\n\ncodeforces\n\n8 6 1 7 5 2 9 3 10 4"]
|
PASSED
|
from collections import *
from heapq import *
from bisect import *
from itertools import *
from string import *
from math import *
def solve():
n = int(input())
s = input()
P = list(map(int, input().split()))
P = [x - 1 for x in P]
seen = set()
components = []
def dfs(u, component):
if u not in seen:
seen.add(u)
component.append(u)
dfs(P[u], component)
for i in range(n):
if i not in seen:
component = []
dfs(i, component)
components.append(component)
def find_cycle_length(vals):
a = ''.join(s[i] for i in vals)
m = len(a)
for k in range(1,m+1):
if m % k != 0: continue
if all(a[j] == a[j-k] for j in range(k,m)):
return k
assert False
ans = [find_cycle_length(comp) for comp in components]
return lcm(*ans)
def main():
T = int(input())
for _ in range(T):
print(solve())
if __name__ == "__main__":
main()
|
1654612500
|
[
"number theory",
"math",
"strings",
"graphs"
] |
[
0,
0,
1,
1,
1,
0,
1,
0
] |
|
1 second
|
["1\n3", "4\n1 2 3 4"]
|
961557bad90f98df7b40d6ceca942121
|
NoteConsider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour.On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 0.
|
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.For each of m company clients, let us denote indices of two different data centers storing this client data as ci,β1 and ci,β2.In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer uj (0ββ€βujββ€βhβ-β1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance.Summing up everything above, the condition uci,β1ββ βuci,β2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if ujβ=βhβ-β1, then the new maintenance hour would become 0, otherwise it would become ujβ+β1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed.Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees.
|
In the first line print the minimum possible number of data centers k (1ββ€βkββ€βn) that have to be included in an experiment in order to keep the data available for any client. In the second line print k distinct integers x1,βx2,β...,βxk (1ββ€βxiββ€βn), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order. If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers.
|
The first line of input contains three integers n, m and h (2ββ€βnββ€β100β000, 1ββ€βmββ€β100β000, 2ββ€βhββ€β100β000), the number of company data centers, number of clients and the day length of day measured in hours. The second line of input contains n integers u1,βu2,β...,βun (0ββ€βujβ<βh), j-th of these numbers is an index of a maintenance hour for data center j. Each of the next m lines contains two integers ci,β1 and ci,β2 (1ββ€βci,β1,βci,β2ββ€βn, ci,β1ββ βci,β2), defining the data center indices containing the data of client i. It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_053.jsonl
|
9d816d564e4a446d096853a00424a9ce
|
512 megabytes
|
["3 3 5\n4 4 0\n1 3\n3 2\n3 1", "4 5 4\n2 1 0 3\n4 3\n3 2\n1 2\n1 4\n1 3"]
|
PASSED
|
import sys
# sys.stind.readline lee datos el doble de
# rΓ‘pido que la funcion por defecto input
input = sys.stdin.readline
def get_input():
n, m, h = [int(x) for x in input().split(' ')]
digraph = [[] for _ in range(n + 1)]
transpose = [[] for _ in range(n + 1)]
mantainence = [0] + [int(x) for x in input().split(' ')]
for _ in range(m):
c1, c2 = [int(x) for x in input().split(' ')]
if (mantainence[c1] + 1) % h == mantainence[c2]:
digraph[c1].append(c2)
transpose[c2].append(c1)
if (mantainence[c2] + 1) % h == mantainence[c1]:
digraph[c2].append(c1)
transpose[c1].append(c2)
return digraph, transpose
def dfs_cc_1_visit(graph, node, color, finalization_stack):
stack = [node]
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
if color[current_node] == 'grey':
finalization_stack.append(current_node)
color[current_node] = 'black'
continue
color[current_node] = 'grey'
for adj in graph[current_node]:
if color[adj] == 'white':
stack.append(adj)
def dfs_cc_1(graph):
n = len(graph)
finalization_stack = []
color = ['white'] * n
for i in range(1, n):
if color[i] == 'white':
dfs_cc_1_visit(graph, i, color, finalization_stack)
return finalization_stack
def dfs_cc_2_visit(graph, node, color, scc, component):
stack = [node]
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
color[current_node] = 'black'
scc[current_node] = component
continue
color[current_node] = 'grey'
for adj in graph[current_node]:
if color[adj] == 'white':
stack.append(adj)
def dfs_cc_2(graph, stack_time):
n = len(graph)
color = ['white'] * n
scc = [0] * n
component = 0
while stack_time:
current_node = stack_time.pop()
if color[current_node] == 'white':
dfs_cc_2_visit(graph, current_node, color, scc, component)
component += 1
return scc, component
def strongly_connected_components(digraph, transpose):
stack_time = dfs_cc_1(digraph)
scc, max_component = dfs_cc_2(transpose, stack_time)
# create the components
out_deg = [0] * max_component
scc_nodes = [[] for _ in range(max_component)]
for node in range(1, len(digraph)):
scc_nodes[scc[node]].append(node)
for adj in digraph[node]:
if scc[node] != scc[adj]:
out_deg[scc[node]] += 1
# searching minimum strongly connectected component with out degree 0
minimum_component = None
for i, value in enumerate(out_deg):
if value == 0 and (minimum_component is None or len(scc_nodes[i]) < len(scc_nodes[minimum_component])):
minimum_component = i
# return the size of the component and the nodes
return len(scc_nodes[minimum_component]), scc_nodes[minimum_component]
if __name__ == "__main__":
digraph, transpose = get_input()
count, nodes = strongly_connected_components(digraph, transpose)
print(count)
print(' '.join([str(x) for x in nodes]))
|
1520583000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["-\n-\n? 1 1\n1\n2\n-\n! 2\n-\n? 1 1\n1\n2\n-\n? 2 3\n4 2\n1 3 5\n-\n? 1 1\n4\n5\n-\n! 1"]
|
d800ab6fa7c7bad7c1c637acc43f4cfc
|
NoteAdditional separators "β" in the sample are used only to increase the readability of the sample. Don't print any unnecessary symbols or line breaks in your solution when you send it to the system.Hacks are forbidden in this task.
|
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.There are $$$n$$$ gift boxes in a row, numbered from $$$1$$$ to $$$n$$$ from left to right. It's known that exactly $$$k$$$ of them contain valuable giftsΒ β other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.You can ask no more than $$$50$$$ queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes $$$a_1, a_2, \dots, a_{k_a}$$$ and $$$b_1, b_2, \dots, b_{k_b}$$$. In return you'll get one of four results: FIRST, if subset $$$a_1, a_2, \dots, a_{k_a}$$$ is strictly heavier; SECOND, if subset $$$b_1, b_2, \dots, b_{k_b}$$$ is strictly heavier; EQUAL, if subsets have equal total weights; WASTED, if the query is incorrect or the limit of queries is exceeded. Using such queries (or, maybe, intuition) find the box with a valuable gift with the minimum index.
|
For each test case print the minimum index among all boxes with a valuable gift in the following format: "! $$$x$$$" where $$$x$$$ ($$$1 \le x \le n$$$)Β β the index of the box.
|
The input consists of several cases. In the beginning, you receive the integer $$$T$$$ ($$$1 \le T \le 500$$$)Β β the number of test cases. At the beginning of each test case, you receive two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$, $$$1 \le k \le \frac{n}{2}$$$)Β β the number of boxes in a row and the number of boxes with valuable gifts. It's guaranteed that the order of boxes is fixed beforehand and that the sum of $$$n$$$ in one test doesn't exceed $$$1000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,600 |
train_056.jsonl
|
e4c6ad70671c935bb098577d77f5aaa4
|
256 megabytes
|
["2\n2 1\n-\n-\n-\nFIRST\n-\n5 2\n-\n-\n-\nFIRST\n-\n-\n-\nSECOND\n-\n-\n-\nEQUAL\n-"]
|
PASSED
|
from random import randrange
def ask(a0,b0,L):
print("?",L,L,flush=True)
aa=[i for i in range(a0,a0+L)]
print(*aa,flush=True)
aa=[i for i in range(b0,b0+L)]
print(*aa,flush=True)
return input()
def main():
for _ in range(int(input())):
n,k=map(int,input().split())
isfirst=False
for _ in range(30):
if ask(1,randrange(2,n+1),1)=="SECOND":
isfirst=True
if isfirst:
print("! 1",flush=True)
continue
ln=1
while 1:
ret=ask(1,1+ln,ln)
if ret=="FIRST":
l,r=1+ln,1+ln*2
break
if ln*4>n:
l,r=1+ln*2,n+1
break
ln*=2
while l+1<r:
m=(l+r)//2
if ask(1,l,m-l)=="EQUAL":l=m
else:r=m
print("!",l,flush=True)
main()
|
1589707200
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["1\n2\n1\n7\n4\n333333333\n333333328"]
|
d04cbe78b836e53b51292401c8c969b2
|
NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \cdot 1 + 2 \cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \cdot 2 + 2 \cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \cdot 7 + 2 \cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ equals $$$n=28$$$.
|
Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.You have to answer $$$t$$$ independent test cases.
|
Print one integer β any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.
|
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 one integer $$$n$$$ ($$$3 \le n \le 10^9$$$) β the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 900 |
train_002.jsonl
|
0cfd0707fd10a3d2aa9fee2a96bdda2b
|
256 megabytes
|
["7\n3\n6\n7\n21\n28\n999999999\n999999984"]
|
PASSED
|
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split(" "))
def msi(): return map(str,input().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
import math
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1]
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def ceil(x,y):
if x%y==0:
return x//y
else:
return x//y+1
def powerMod(x,y,p):
res = 1
x %= p
while y > 0:
if y&1:
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def main():
for _ in range(ii()):
n=ii()
k=2
while True:
if (int(n%(pow(2,k)-1))==0):
print(int(n/(pow(2,k)-1)))
break
k+=1
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read()
|
1587479700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["8", "16"]
|
6d7accf770d489f746648aa56c90d16d
|
NoteIn the first sample Vika will paint squares (0,β1), (1,β1), (2,β1), (1,β2), (1,β3), (1,β4), (0,β3) and (2,β3).
|
Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.
|
Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.
|
The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of segments drawn by Vika. Each of the next n lines contains four integers x1, y1, x2 and y2 (β-β109ββ€βx1,βy1,βx2,βy2ββ€β109)Β β the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_008.jsonl
|
96b38efc0edc3288dd4dcc53ca68b4c4
|
256 megabytes
|
["3\n0 1 2 1\n1 4 1 2\n0 3 2 3", "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2"]
|
PASSED
|
from sys import stdin
from itertools import repeat
from collections import defaultdict
def main():
n = int(stdin.readline())
h = defaultdict(list)
w = defaultdict(list)
for i in range(n):
a, b, c, d = map(int, input().split())
if a > c:
a, c = c, a
if b > d:
b, d = d, b
if a == c:
h[a].append((b, d))
else:
w[b].append((a, c))
ans = 0
ys = set()
es = defaultdict(list)
qs = defaultdict(list)
for t, l in h.items():
l.sort()
l.append((1001001001, 1001001001))
nl = []
p = r = l[0][0]
for a, b in l:
if a > r:
nl.append((p, r))
ans += r - p + 1
es[p].append((1, t))
es[r+1].append((-1, t))
p = r = a
if r < b:
r = b
l = nl
ys.add(t)
for t, l in w.items():
l.sort()
l.append((1001001001, 1001001001))
nl = []
p = r = l[0][0]
for a, b in l:
if a > r:
nl.append((p, r))
ys.add(p)
ys.add(r)
es[t].append((2, p, r))
ans += r - p + 1
p = r = a
if r < b:
r = b
l = nl
ys = [-1001001001] + list(ys)
ys.sort()
d = {v: i for i, v in enumerate(ys)}
l = len(ys)
bs = [0] * l
for x in sorted(es.keys()):
for q in sorted(es[x]):
if q[0] <= 1:
a, b = q[0], d[q[1]]
while b < l:
bs[b] += a
b += b - (b & (b - 1))
else:
a, b = d[q[1]] - 1, d[q[2]]
while b > 0:
ans -= bs[b]
b = b & (b - 1)
while a > 0:
ans += bs[a]
a = a & (a - 1)
print (ans)
main()
|
1451215200
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nYES\nYES\nNO\nYES\nNO\nYES\nYES\nNO\nYES"]
|
90c5058c0c7f55a567f2e036482149f9
|
NoteIn the first and second test cases, you can choose the number $$$m=4$$$ and multiply the second number ($$$b=5$$$) by $$$4$$$.In the first test case the resulting sequence will be $$$[10, 20, 30]$$$. This is an AP with a difference $$$d=10$$$.In the second test case the resulting sequence will be $$$[30, 20, 10]$$$. This is an AP with a difference $$$d=-10$$$.In the third test case, you can choose $$$m=1$$$ and multiply any number by $$$1$$$. The resulting sequence will be $$$[1, 2, 3]$$$. This is an AP with a difference $$$d=1$$$.In the fourth test case, you can choose $$$m=9$$$ and multiply the first number ($$$a=1$$$) by $$$9$$$. The resulting sequence will be $$$[9, 6, 3]$$$. This is an AP with a difference $$$d=-3$$$.In the fifth test case, it is impossible to make an AP.
|
Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once. Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.
|
For each test case print "YES" (without quotes) if Polycarp can choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$ to make $$$[a, b, c]$$$ be an arithmetic progression. Print "NO" (without quotes) otherwise. You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).
|
The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Each of the following $$$t$$$ lines contains $$$3$$$ integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_102.jsonl
|
80cfbe8057007f507dcaba0769c8508d
|
256 megabytes
|
["11\n10 5 30\n30 5 10\n1 2 3\n1 6 3\n2 6 3\n1 1 1\n1 1 2\n1 1 3\n1 100000000 1\n2 1 1\n1 2 2"]
|
PASSED
|
for j in[0]*int(input()):
i=input().split()
a=int(i[0])
b=int(i[1])
c=int(i[2])
if ((a+c)%(2*b)==0) or (((2*b-c)%a ==0) and ((2*b-c)>0)) or (((2*b-a)%c ==0) and ((2*b-a)>0)): print("YES")
else :print("NO")
|
1641825300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "4"]
|
c421f47149e70240a02903d9d47de429
|
NoteIn the first sample all 3 subsequences of the needed length are considered lucky.In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1,β3}, {1,β4}, {2,β3} and {2,β4}.
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has sequence a consisting of n integers.The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.Two sequences are considered different if index sets of numbers included in them are different. That is, the values βof the elements βdo not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109β+β7).
|
On the single line print the single number β the answer to the problem modulo prime number 1000000007 (109β+β7).
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β105). The next line contains n integers ai (1ββ€βaiββ€β109) β the sequence a.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,100 |
train_064.jsonl
|
3446ba93877e9cdb83935f0bd9ba2ba5
|
256 megabytes
|
["3 2\n10 10 10", "4 2\n4 4 7 7"]
|
PASSED
|
#!/usr/bin/env python
MOD = 1000000007
def gcd(a, b):
if a == 0:
return b, 0, 1
d, x, y = gcd(b % a, a)
return d, y - b / a * x, x
def div(a):
d, x, y = gcd(a, MOD)
return x
def c(n, k):
if k > n or k < 0:
return 0
res = 1
for i in xrange(max(k + 1, n - k + 1), n + 1):
res = res * i % MOD
res = res * div(n - i + 1) % MOD
return res
def is_lucky(num):
return num.replace('4', '').replace('7', '') == ""
if __name__ == "__main__":
n, k = map(int, raw_input().strip().split())
luckies = filter(is_lucky, raw_input().strip().split())
others = n - len(luckies)
lucky_dict = {}
for lucky in luckies:
if lucky not in lucky_dict:
lucky_dict[lucky] = 0
lucky_dict[lucky] += 1
dp_count = []
for lucky, count in lucky_dict.iteritems():
dp_count.append(0)
for i in range(len(dp_count)-1, -1, -1):
if i !=0:
dp_count[i] += dp_count[i - 1] * count
else:
dp_count[i] += count
dp_count[i] %= MOD
res = 0
max_count = len(dp_count) if len(dp_count) < k else k
cur_binom = c(others, k - max_count)
for i in range(max_count-1, -1, -1):
res += cur_binom * dp_count[i]
res %= MOD
if k - i > others:
cur_binom = 0
break
cur_binom = cur_binom * div(k - i) * (others - k + i + 1) % MOD
res += cur_binom
res %= MOD
print res
|
1327215600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["-1\n3\n1 3\n2 2\n4 0"]
|
070cb9523bd8319e93c33264a3faf708
| null |
Vitaly gave Maxim $$$n$$$ numbers $$$1, 2, \ldots, n$$$ for his $$$16$$$-th birthday. Maxim was tired of playing board games during the celebration, so he decided to play with these numbers. In one step Maxim can choose two numbers $$$x$$$ and $$$y$$$ from the numbers he has, throw them away, and add two numbers $$$x + y$$$ and $$$|x - y|$$$ instead. He wants all his numbers to be equal after several steps and the sum of the numbers to be minimal.Help Maxim to find a solution. Maxim's friends don't want to wait long, so the number of steps in the solution should not exceed $$$20n$$$. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than $$$20n$$$ moves.
|
For each test case print $$$-1$$$ if it's impossible to make all numbers equal. Otherwise print a single integer $$$s$$$ ($$$0 \le s \le 20n$$$)Β β the number of steps. Then print $$$s$$$ lines. The $$$i$$$-th line must contain two integers $$$x_i$$$ and $$$y_i$$$Β β numbers that Maxim chooses on the $$$i$$$-th step. The numbers must become equal after all operations. Don't forget that you not only need to make all numbers equal, but also minimize their sum. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than $$$20n$$$ moves.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 25\,000$$$)Β β the number of test cases. Each test case contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$)Β β the number of integers given to Maxim. It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$5 \cdot 10^4$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| 3,000 |
train_090.jsonl
|
6c69b8efd7305a2534fb56e3090c2c16
|
256 megabytes
|
["2\n2\n3"]
|
PASSED
|
import sys
raw_input = iter(sys.stdin.read().splitlines()).next
def bfs(n):
result, a = [], []
q = [(n, 1)]
while q:
new_q = []
for n, coeff in q:
if n <= 2:
for i in xrange(1, n+1):
a.append(i*coeff)
continue
pw = 1<<(n.bit_length()-1)
if pw == n:
a.append(n*coeff)
n -= 1
pw //= 2
a.append(pw*coeff)
for i in xrange(1, (n-pw)+1):
result.append(((pw-i)*coeff, (pw+i)*coeff))
a.append(2*pw*coeff)
new_q.append((pw-(n-pw)-1, coeff))
new_q.append((n-pw, 2*coeff))
q = new_q
return result, a
def solution():
n = int(raw_input())
if n == 2:
return -1
result, a = bfs(n)
a.sort()
expect_num = 1<<(n-1).bit_length()
for i in xrange(len(a)-1):
if a[i] != a[i+1]:
continue
result.append((a[i], a[i+1]))
a[i+1] += a[i]
a.remove(a[i])
break
for x in a:
while x != expect_num:
result.append((0, x))
result.append((x, x))
x *= 2
result.append((0, expect_num))
return "%s\n%s" % (len(result), "\n".join(map(lambda x: " ".join(map(str, x)), result)))
for case in xrange(int(raw_input())):
print '%s' % solution()
|
1644676500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\n1\n1 3"]
|
bbcb051b08fa3d19a7cf285242d50451
| null |
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life Β«interesting graph and applesΒ». An undirected graph is called interesting, if each of its vertices belongs to one cycle only β a funny ring β and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1,βy1),β(x2,βy2),β...,β(xn,βyn), where xiββ€βyi, is lexicographically smaller than the set (u1,βv1),β(u2,βv2),β...,β(un,βvn), where uiββ€βvi, provided that the sequence of integers x1,βy1,βx2,βy2,β...,βxn,βyn is lexicographically smaller than the sequence u1,βv1,βu2,βv2,β...,βun,βvn. If you do not cope, Hexadecimal will eat you. ...eat you alive.
|
In the first line output Β«YESΒ» or Β«NOΒ»: if it is possible or not to construct an interesting graph. If the answer is Β«YESΒ», in the second line output k β the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.
|
The first line of the input data contains a pair of integers n and m (1ββ€βnββ€β50, 0ββ€βmββ€β2500) β the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1ββ€βxi, yiββ€βn) β the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,300 |
train_043.jsonl
|
09f449f8cf745ed652fbf2c2f3523e67
|
64 megabytes
|
["3 2\n1 2\n2 3"]
|
PASSED
|
from itertools import *
read = lambda: map(int, raw_input().split())
def check_deg():
for i in xrange(n):
if deg[i] > 2:
return False
return True
def check_cycle():
def cycle(u):
mk.add(u)
for v in xrange(n):
if g[u][v]:
g[u][v] -= 1
g[v][u] -= 1
if v in mk or cycle(v):
return True
return False
mk = set()
cycle_num = 0
for i in xrange(n):
if i in mk:
continue
if cycle(i):
cycle_num += 1
if cycle_num == 1 and deg.count(2) == n:
return True
return cycle_num == 0
def root(u):
global f
r = u
while f[r] != r: r = f[r]
while f[u] != r: f[u], u = r, f[u]
return r
n, m = read()
g = [[0] * n for i in xrange(n)]
deg = [0] * n
f = range(n)
for i in xrange(m):
u, v = read()
u -= 1
v -= 1
deg[u] += 1
deg[v] += 1
g[u][v] += 1
g[v][u] += 1
f[root(u)] = root(v)
if m > n or not check_deg() or not check_cycle():
print 'NO'
else:
print 'YES'
print n - m
if n == 1 and n - m > 0:
print '1 1'
exit(0)
for i in xrange(n - m):
for u, v in combinations(xrange(n), 2):
if deg[u] < 2 and deg[v] < 2 and root(u) != root(v):
print u + 1, v + 1
deg[u] += 1
deg[v] += 1
f[root(u)] = root(v)
break
for u, v in combinations(xrange(n), 2):
if deg[u] < 2 and deg[v] < 2:
print u + 1, v + 1
deg[u] += 1
deg[v] += 1
|
1270983600
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["0\n2\n3\n-1\n1\n-1\n3\n1\n3\n-1"]
|
e3a1f53f78fcb3a551c3ae1cbeedaf15
|
NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: $$$4 \rightarrow 10 \rightarrow 5$$$.In the third example, you can achieve the desired temperature as follows: $$$3 \rightarrow 8 \rightarrow 2 \rightarrow 7$$$.In the fourth test, it is impossible to make any operation.
|
Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $$$a$$$.The thermostat can only be set to a temperature from $$$l$$$ to $$$r$$$ inclusive, the temperature cannot change by less than $$$x$$$. Formally, in one operation you can reconfigure the thermostat from temperature $$$a$$$ to temperature $$$b$$$ if $$$|a - b| \ge x$$$ and $$$l \le b \le r$$$.You are given $$$l$$$, $$$r$$$, $$$x$$$, $$$a$$$ and $$$b$$$. Find the minimum number of operations required to get temperature $$$b$$$ from temperature $$$a$$$, or say that it is impossible.
|
Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature $$$b$$$, output -1, otherwise output the minimum number of operations.
|
The first line of input data contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases in the test. The descriptions of the test cases follow. The first line of each case contains three integers $$$l$$$, $$$r$$$ and $$$x$$$ ($$$-10^9 \le l \le r \le 10^9$$$, $$$1 \le x \le 10^9$$$) β range of temperature and minimum temperature change. The second line of each case contains two integers $$$a$$$ and $$$b$$$ ($$$l \le a, b \le r$$$) β the initial and final temperatures.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_086.jsonl
|
fb041dd0b2527dd1b365e9aeaa194558
|
256 megabytes
|
["10\n\n3 5 6\n\n3 3\n\n0 15 5\n\n4 5\n\n0 10 5\n\n3 7\n\n3 5 6\n\n3 4\n\n-10 10 11\n\n-5 6\n\n-3 3 4\n\n1 0\n\n-5 10 8\n\n9 2\n\n1 5 1\n\n2 5\n\n-1 4 3\n\n0 2\n\n-6 3 6\n\n-1 -4"]
|
PASSED
|
R=lambda:map(int,input().split())
t,=R()
while t:t-=1;l,r,x=R();a,b=sorted(R());print('0'*(a==b)or+(b-a>=x)or(x<=max(a-l,r-b))*2or(r-a>=x<=b-l)*3or-1)
|
1668782100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "8"]
|
0b229ddf583949d43d6f1728e38c3cad
|
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
|
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
|
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
|
The first line of the input data contains an integer n (1ββ€βnββ€β105). The second line contains an array of original integers a1,βa2,β...,βan (β-β109ββ€βaiββ€β109).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,300 |
train_004.jsonl
|
e45e19f5f10fc3e079dd5ddcfb94c7df
|
256 megabytes
|
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
|
PASSED
|
n = raw_input()
st = map(int, raw_input().split())
gl = 0
loc = 0
prev = 0
for i in st:
if prev != i:
loc = 1
else:
loc += 1
gl += loc
prev = i
print gl
|
1305299400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["0 1 2 \n1 0 2 \n1 2 0", "0 2 3 3 4 4 \n4 0 2 3 3 4 \n4 4 0 2 3 3 \n3 4 4 0 2 3 \n3 3 4 4 0 2 \n2 3 3 4 4 0", "0 1 2 3 \n3 0 3 2 \n12 13 0 11 \n1 2 2 0"]
|
58b9ec7ff9718ceae1aa3d4503c8cbed
|
NoteIn the first example one possible path for going from $$$0$$$ to $$$2$$$ would be: Stay inside $$$0$$$ and do nothing for $$$1$$$ second. Use the first cannon and land at $$$2$$$ after $$$1$$$ second. Note that: we could have used the second cannon in $$$0$$$-th second but it would have taken us $$$3$$$ seconds to reach city $$$2$$$ in that case.
|
There are $$$n$$$ cities in Shaazzzland, numbered from $$$0$$$ to $$$n-1$$$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted $$$m$$$ transport cannons in the cities of Shaazzzland. The $$$i$$$-th cannon is planted in the city $$$a_i$$$ and is initially pointing at city $$$b_i$$$.It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $$$i$$$-th cannon is pointing towards the city $$$x$$$ at some second, it will target the city $$$(x + 1) \mod n$$$ at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $$$i$$$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $$$c_i$$$ seconds before reaching your target destination.If you still don't get it, using the $$$i$$$-th cannon at the $$$s$$$-th second (using which is only possible if you are currently in the city $$$a_i$$$) will shoot you to the city $$$(b_i + s) \mod n$$$ and you'll land in there after $$$c_i$$$ seconds (so you'll be there in the $$$(s + c_i)$$$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $$$0$$$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $$$u$$$ from city $$$v$$$ using the cannons for every pair of cities $$$(u, v)$$$.Note that AaParsa can stay in a city for as long as he wants.
|
Print $$$n$$$ lines, each line should contain $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be equal to the minimum time required to reach city $$$j$$$ from city $$$i$$$.
|
The first line contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 600 , n \le m \le n^2)$$$ β the number of cities and cannons correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$c_i$$$ $$$( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9)$$$, denoting the cannon in the city $$$a_i$$$, which is initially pointing to $$$b_i$$$ and travelling by which takes $$$c_i$$$ seconds. It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_085.jsonl
|
31da8907e3fd6d9dfecb6342a7f81f2d
|
256 megabytes
|
["3 4\n0 1 1\n0 2 3\n1 0 1\n2 0 1", "6 6\n0 0 1\n1 1 1\n2 2 1\n3 3 1\n4 4 1\n5 5 1", "4 5\n0 1 1\n1 3 2\n2 2 10\n3 0 1\n0 0 2"]
|
PASSED
|
import sys
input = lambda: sys.stdin.readline().rstrip()
def dijkstra(n, E, i0=0):
D = [1 << 30] * n; D[i0] = 0; Q = set([i for i in range(n)])
while Q:
d = 1 << 30
for q in Q:
if D[q] < d: i = q; d = D[q]
Q.remove(i)
for j, w in enumerate(E[i]):
jj = (j + d) % n
if jj == i: continue
nd = d + w
if D[jj] > nd: D[jj] = nd
return " ".join(map(str, D))
N, M = map(int, input().split());inf = 2 * 10 ** 9;X = [[inf] * N for _ in range(N)]
for _ in range(M):a, b, c = map(int, input().split());X[a][b] = c
Y = [[0] * N for _ in range(N)]
for i, Yi in enumerate(Y):
Xi = X[i]
for j in range(N):
if j and mi < Xi[j] + N - 1: mi = min(mi + 1, Xi[j]); Yi[j] = mi; continue
mi = min([(Xi[j-k] + k) for k in range(N)]); Yi[j] = mi
print("\n".join([dijkstra(N, Y, s) for s in range(N)]))
|
1621866900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["3", "7"]
|
b963c125f333eef3ffc885b59e6162c2
|
NoteIn the first sample we can obtain the array:3β6β9β12β12β15In the second sample we can obtain the next array:7β21β49β14β77
|
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: biβ>β0;β0ββ€βaiβ-βbiββ€βk for all 1ββ€βiββ€βn.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).
|
In the single line print a single number β the maximum possible beauty of the resulting array.
|
The first line contains two integers n and k (1ββ€βnββ€β3Β·105;β1ββ€βkββ€β106). The second line contains n integers ai (1ββ€βaiββ€β106) β array a.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_004.jsonl
|
390dfc74b6e625cce9cac033eda1aa26
|
256 megabytes
|
["6 1\n3 6 10 12 13 16", "5 3\n8 21 52 15 77"]
|
PASSED
|
n, k = map(int, input().split())
t = set(map(int, input().split()))
y = x = min(t)
t = list(t)
while True:
for i in t:
if i % x > k: x = i // (i // x + 1)
if y == x: break
y = x
print(y)
|
1381678200
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
3 seconds
|
["3\n2\n3\n6"]
|
7f15864d46f09ea6f117929565ccb867
|
Note The first query asks for a centroid of the whole treeΒ β this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6Β β both answers are considered correct.
|
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
|
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
|
The first line of the input contains two integers n and q (2ββ€βnββ€β300β000, 1ββ€βqββ€β300β000)Β β the size of the initial tree and the number of queries respectively. The second line contains nβ-β1 integer p2,βp3,β...,βpn (1ββ€βpiββ€βn)Β β the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1ββ€βviββ€βn)Β β the index of the node, that define the subtree, for which we want to find a centroid.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_003.jsonl
|
34642c4757df9c0c5a8c372994efdcd7
|
256 megabytes
|
["7 4\n1 1 3 3 5 3\n1\n2\n3\n5"]
|
PASSED
|
n, q = map(int, raw_input().split(' '))
p_arr = map(lambda x:int(x) - 1, raw_input().split(' '))
p_arr = [-1] + p_arr
for i in p_arr[1:]:
i += 1
pe_arr = [0 for i in xrange(n)]
s_arr = [1 for i in xrange(n)]
mx_arr = [-1 for i in xrange(n)]
z_arr = [i for i in xrange(n)]
for i in p_arr:
if i > 0:
pe_arr[i] += 1
arr = [i for i in xrange(n) if pe_arr[i] == 0]
while arr:
i = arr.pop()
while z_arr[i] != i and (s_arr[i] - s_arr[z_arr[i]]) * 2 > s_arr[i]:
z_arr[i] = p_arr[z_arr[i]]
if i == 0:
continue
fa = p_arr[i]
s_arr[fa] += s_arr[i]
if mx_arr[fa] < s_arr[i]:
mx_arr[fa] = s_arr[i]
z_arr[fa] = z_arr[i]
pe_arr[fa] -= 1
if pe_arr[fa] == 0:
arr.append(fa)
q_arr = [int(raw_input()) - 1 for i in xrange(q)]
for i in q_arr:
print z_arr[i] + 1
|
1466699700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["2000", "1000"]
|
991a9b3904884c8d19ec7c665f2fcd95
| null |
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi,βyi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends dΒ·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xiβ-βxj|β+β|yiβ-βyj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.
|
In a single line print an integer β the answer to the problem.
|
The first line contains integers n and d (3ββ€βnββ€β100,β103ββ€βdββ€β105) β the number of stations and the constant from the statement. The second line contains nβ-β2 integers: a2,βa3,β...,βanβ-β1 (1ββ€βaiββ€β103). The next n lines contain the coordinates of the stations. The i-th of them contains two integers xi, yi (-100ββ€βxi,βyiββ€β100). It is guaranteed that no two stations are located at the same point.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_000.jsonl
|
da6a787390c2b5025ea1359b968c96ce
|
256 megabytes
|
["3 1000\n1000\n0 0\n0 1\n0 3", "3 1000\n1000\n1 0\n1 1\n1 2"]
|
PASSED
|
f = lambda: list(map(int, input().split()))
n, d = f()
a = [0] + f() + [0]
p = [f() for i in range(n)]
r = range(n)
s = [[d * (abs(p[i][0] - p[j][0]) + abs(p[i][1] - p[j][1])) - a[j] * (i != j) for j in r] for i in r]
for k in r: s = [[min(s[i][j], s[i][k] + s[k][j]) for i in r] for j in r]
print(s[-1][0])
|
1367769900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["0 1\n-1 2 \n1 2 \n1 3 \n18 22\n-2 7\n999999999999 1000000000001"]
|
a4628208668e9d838cd019e9dc03e470
|
NoteIn the first test case, $$$0 + 1 = 1$$$.In the second test case, $$$(-1) + 0 + 1 + 2 = 2$$$.In the fourth test case, $$$1 + 2 + 3 = 6$$$.In the fifth test case, $$$18 + 19 + 20 + 21 + 22 = 100$$$.In the sixth test case, $$$(-2) + (-1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 25$$$.
|
Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.
|
For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$. It can be proven that an answer always exists. If there are multiple answers, print any.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_097.jsonl
|
364a2d0fb8cffc63689d7ed21bcd8526
|
256 megabytes
|
["7\n1\n2\n3\n6\n100\n25\n3000000000000"]
|
PASSED
|
t=int(input())
for t in range (0,t):
p=int(input())
a=(p-1)
print(int(-a),int(a+1))
|
1633705500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["aba", "a", "cbaaacbcaaabc"]
|
3bebb50d1c2ef9f80e78715614f039d7
|
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
|
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
|
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
|
The input consists of a single string $$$s$$$Β ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_002.jsonl
|
953c99e6c500fa842ee93adb4e7fa241
|
256 megabytes
|
["cacbac", "abc", "cbacacacbcbababacbcb"]
|
PASSED
|
sre = input()
pre = 0
kre = len(sre) - 1
pointeree = 0
plotttt = []
while (pre + 1 < kre - 1):
if( sre[ pre ] == sre[ kre ]):
plotttt.append( sre[ pre ])
pre += 1
kre -= 1
pointeree += 2
elif (sre[ pre ] == sre[ kre - 1]):
plotttt.append( sre[ pre ])
pre += 1
kre -= 2
elif( sre[ pre + 1] == sre[ kre ]):
plotttt.append( sre[ pre + 1 ])
pre += 2
kre -= 1
else:
plotttt.append( sre[ pre + 1 ])
pre += 2
kre -= 2
dfdkngkfgjfb = 0
if (kre - pre == 2):
xrere = [ sre[ pre ], sre[ pre + 1], sre[ pre + 2 ]]
xrere.sort()
if( xrere[0] == xrere[1]):
plotttt.append( xrere[ 0 ])
elif (xrere[ 1 ] == xrere[ 2 ]):
plotttt.append( xrere[ 1 ])
else:
dfdkngkfgjfb = xrere[ 1 ]
if( kre - pre == 1):
if( sre[ pre] == sre[ pre + 1 ]):
plotttt.append( sre[ pre ])
else:
dfdkngkfgjfb = sre[ pre ]
if (kre == pre):
dfdkngkfgjfb = sre[ pre ]
if( dfdkngkfgjfb == 0):
if ( len( plotttt) * 2 >= len( sre )//2):
for i in plotttt:
print(i, end = "")
for i in range(len(plotttt)):
j = len( plotttt ) - 1 - i
print(plotttt[j], end = "")
else:
print("IMPOSSIBLE")
else:
if ( 2 * len( plotttt ) + 1) >= len( sre )//2:
for i in plotttt:
print(i, end = "")
print( dfdkngkfgjfb, end = "")
for i in range(len( plotttt )):
j = len( plotttt ) - 1 - i
print( plotttt[ j ], end = "")
else:
print("IMPOSSIBLE")
|
1563636900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1 1 1 1\n2 2 2 1\n2 2 2 2\n2 4 2 1\n3 5 1 1"]
|
f9f803c6850da1838d62a0cf85bb13f2
|
NoteIn the first test case $$$\gcd(1, 1) = \operatorname{lcm}(1, 1) = 1$$$, $$$1 + 1 + 1 + 1 = 4$$$.In the second test case $$$\gcd(2, 2) = \operatorname{lcm}(2, 1) = 2$$$, $$$2 + 2 + 2 + 1 = 7$$$.In the third test case $$$\gcd(2, 2) = \operatorname{lcm}(2, 2) = 2$$$, $$$2 + 2 + 2 + 2 = 8$$$.In the fourth test case $$$\gcd(2, 4) = \operatorname{lcm}(2, 1) = 2$$$, $$$2 + 4 + 2 + 1 = 9$$$.In the fifth test case $$$\gcd(3, 5) = \operatorname{lcm}(1, 1) = 1$$$, $$$3 + 5 + 1 + 1 = 10$$$.
|
You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that $$$a + b + c + d = n$$$, and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.
|
For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.
|
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \le n \le 10^9$$$)Β β the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_096.jsonl
|
4351fb2fc0e87665e46579a35f9d5ec9
|
256 megabytes
|
["5\n4\n7\n8\n9\n10"]
|
PASSED
|
for __ in range(int(input())):
b = int(input())
if b==4:
print(1,1,1,1)
elif b==6:
print(1,3,1,1)
elif b%2==1:
b=int(b//2)
print(b-1,b,1,1)
else:
if b%4==0:
print(int(b/4),int(b/4),int(b/4),int(b/4))
else:
b-=2
b=int(b/2)
print(b+1,b-1,1,1)
|
1649428500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "4", "-10"]
|
e83b559d99a0a41c690c68fd76f40ed3
| null |
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print xβ-βy.
|
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
|
The first line of input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,900 |
train_038.jsonl
|
79b84c9a8ffa23c09e01e70e80e5ebd8
|
256 megabytes
|
["2\n12 3 4 7\n1 15 9 1", "2\n5 4 8 8\n4 12 14 0", "1\n0 10 0 10"]
|
PASSED
|
p=[];s=0
for i in range(input()):
a,b,c,d=map(int,raw_input().split())
if a+b>c+d:p+=[a+b,c+d];s-=b+d
elif a>d:s+=a-d
elif b>c:s-=b-c
print s+sum(sorted(p)[1::2])
|
1477148700
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["1028\n1\n3\n729229716\n652219904"]
|
fc8381e8c97190749b356f10cf80209e
| null |
There are $$$n$$$ bags, each bag contains $$$m$$$ balls with numbers from $$$1$$$ to $$$m$$$. For every $$$i \in [1, m]$$$, there is exactly one ball with number $$$i$$$ in each bag.You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $$$1$$$ from the first bag and the ball $$$2$$$ from the second bag is not the same as taking the ball $$$2$$$ from the first bag and the ball $$$1$$$ from the second bag). After that, you calculate the number of balls with odd numbers among the ones you have taken. Let the number of these balls be $$$F$$$.Your task is to calculate the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag.
|
For each test case, print one integerΒ β the sum of $$$F^k$$$ over all possible ways to take $$$n$$$ balls, one from each bag. Since it can be huge, print it modulo $$$998244353$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$)Β β the number of test cases. Each test case consists of one line containing three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 998244352$$$; $$$1 \le k \le 2000$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,500 |
train_109.jsonl
|
1728526b7ec7c9ac31e5a00a1ec65327
|
512 megabytes
|
["5\n\n2 3 8\n\n1 1 1\n\n1 5 10\n\n3 7 2000\n\n1337666 42424242 2000"]
|
PASSED
|
from sys import stdin
input=lambda :stdin.readline()[:-1]
mod=998244353
m=2010
S=[[0]*m for i in range(m)]
for n in range(1,m):
for k in range(1,n+1):
if k==1 or n==k:
S[n][k]=1
else:
S[n][k]=S[n-1][k-1]+k*S[n-1][k]
S[n][k]%=mod
def fpow(x,k):
res=1
if k<0:
return 0
while k:
if k&1:
res=res*x%mod
x=x*x%mod
k>>=1
return res
def solve():
N,M,K=map(int,input().split())
ans=0
res=fpow(M,N)
Minv=fpow(M,mod-2)
for i in range(1,K+1):
res*=(N-i+1)*((M+1)//2)%mod*Minv%mod
res%=mod
ans+=res*S[K][i]%mod
ans%=mod
print(ans)
for _ in range(int(input())):
solve()
|
1659623700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2\n1 2\n1 2\n3\n1 3\n2 3\n2 3\n5\n1 3\n2 4\n2 4\n3 4\n3 4\n0\n2\n1 2\n1 2\n0\n4\n1 2\n1 5\n1 4\n1 2\n1\n5 2"]
|
5c013cdc91f88c102532a86058893f0d
| null |
An important meeting is to be held and there are exactly $$$n$$$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the $$$i$$$-th person is a non-negative integer $$$a_i$$$. This means that after exactly $$$a_i$$$ talks this person leaves the meeting (and does not talk to anyone else anymore). If $$$a_i = 0$$$, the $$$i$$$-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability $$$a$$$, determine which people should talk to each other so that the total number of talks is as large as possible.
|
Print $$$t$$$ answers to all test cases. On the first line of each answer print the number $$$k$$$Β β the maximum number of talks possible in a meeting. On each of the next $$$k$$$ lines print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$ and $$$i \neq j$$$)Β β the numbers of people who will have another talk. If there are several possible answers, you may print any of them.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β βthe number of people in the meeting. The second line consists of $$$n$$$ space-separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$)Β β the sociability parameters of all people. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of all $$$a_i$$$ (over all test cases and all $$$i$$$) does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_095.jsonl
|
4cc35dd5568df63acf848804ebbac953
|
256 megabytes
|
["8\n2\n2 3\n3\n1 2 3\n4\n1 2 3 4\n3\n0 0 2\n2\n6 2\n3\n0 0 2\n5\n8 2 0 1 1\n5\n0 1 0 0 6"]
|
PASSED
|
import sys, math, collections
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()
MOD = 1000000007
for _ in range(int(input())):
n = int(input())
arr = get_array()
A = [[arr[i], i + 1] for i in range(n)]
A.sort()
# s = sum([A[i][0] for i in range(n - 1)])
s = 0
for i in range(n - 1):
s += A[i][0]
mx = A[-1][0]
ans = []
for i in range(n - 1):
if s <= mx:
break
while s > mx and A[i][0]:
ans.append((A[i][1], A[i + 1][1]))
A[i][0] -= 1
A[i + 1][0] -= 1
s -= 2
for i in range(n - 1):
while A[i][0] and mx:
ans.append((A[i][1], A[-1][1]))
A[i][0] -= 1
mx -= 1
print(len(ans))
for ele in ans:
print(*ele)
|
1632839700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 3 2 4 \n1 2 3 \n1 3 2 \n1 2 \n1 2"]
|
5afa0e4f34ab8c8c67bc8ecb7d6d2d7a
|
NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement.
|
In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{1}, 3]$$$ in it;$$$\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \color{red}{2}]$$$ in it;$$$\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \ldots, y_n]$$$ if there exists such $$$i \leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.
|
Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbersΒ β the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.
|
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$)Β β permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; all $$$p_i$$$ are all unique)Β β elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_095.jsonl
|
29f88df583e0c2a598f857f6ea82ff62
|
256 megabytes
|
["5\n4\n3 1 2 4\n3\n3 2 1\n3\n3 1 2\n2\n1 2\n2\n2 1"]
|
PASSED
|
from collections import deque
def arrange(arr, n):
d = deque()
for i in range(n):
if not d or arr[i] < d[0]:
d.appendleft(arr[i])
else:
d.append(arr[i])
return d
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
print(*arrange(a, n))
|
1632839700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO"]
|
8e448883014bf7cd35fcca3fe0128af0
|
NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.
|
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.
|
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 two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even) Β β the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_008.jsonl
|
8d6a98127ecab401e63cae89d2926741
|
256 megabytes
|
["9\n6 4\n100110\n3 2\n1?1\n3 2\n1?0\n4 4\n????\n7 4\n1?0??1?\n10 10\n11??11??11\n4 2\n1??1\n4 4\n?0?0\n6 2\n????00"]
|
PASSED
|
for ad in range(int(input())):
n,k=list(map(int,input().split()))
s=list(input())
l=[]
for i in range(1,n//k+1):
l.append(s[k*(i-1):k*i])
l.append(s[(n//k)*k:])
a=l[0]
t=0
#print(l)
for i in l:
if t==1:
break
for j in range(len(i)):
if a[j]==i[j]:
continue
elif i[j]=="?":
continue
elif a[j]=="?":
a[j]=i[j]
else:
t=1
break
if t==1:
print("NO")
else:
if abs(a.count("0")-a.count("1"))<=a.count("?"):
print("YES")
else:
print("NO")
|
1599402900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["-1", "1", "2"]
|
8237ac3f3c2e79f5f70be1595630207e
|
NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.
|
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left. An 'R' indicates he should move one unit right. A 'U' indicates he should move one unit up. A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.
|
If there is a string satisfying the conditions, output a single integerΒ β the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.
|
The first and only line contains the string s (1ββ€β|s|ββ€β100β000)Β β the instructions Memory is given.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,100 |
train_014.jsonl
|
341580318e853b075fd400ec857979a8
|
256 megabytes
|
["RRU", "UDUR", "RUUR"]
|
PASSED
|
y=raw_input()
if len(y)%2!=0:
print -1
else:
print (abs(y.count('R')-y.count('L'))+abs(y.count('U')-y.count('D')))/2
|
1473525900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["Yes\n1\n1 4\nNo\nNo\nYes\n3\n1 2\n3 1\n2 3"]
|
4985f4d65d636a006f2619ed821368ad
| null |
This problem is different from the easy version. In this version Ujan makes at most $$$2n$$$ swaps. In addition, $$$k \le 1000, n \le 50$$$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $$$2n$$$ times: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$.Ujan's goal is to make the strings $$$s$$$ and $$$t$$$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $$$2n$$$ or shorter is suitable.
|
For each test case, output "Yes" if Ujan can make the two strings equal with at most $$$2n$$$ operations and "No" otherwise. You can print each letter in any case (upper or lower). In the case of "Yes" print $$$m$$$ ($$$1 \le m \le 2n$$$) on the next line, where $$$m$$$ is the number of swap operations to make the strings equal. Then print $$$m$$$ lines, each line should contain two integers $$$i, j$$$ ($$$1 \le i, j \le n$$$) meaning that Ujan swaps $$$s_i$$$ and $$$t_j$$$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $$$2n$$$ is suitable.
|
The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 1000$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 50$$$), the length of the strings $$$s$$$ and $$$t$$$. Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_001.jsonl
|
e8db55221e0cb3c474cb5ba4080e6ce2
|
256 megabytes
|
["4\n5\nsouse\nhouhe\n3\ncat\ndog\n2\naa\naz\n3\nabc\nbca"]
|
PASSED
|
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
def swap(s, t, i, j):
p.append((i+1,j+1))
s[i],t[j] = t[j],s[i]
def find(s, v, i):
for j in range(i,len(s)):
if s[j] == v:
return j
return -1
def solve():
global p
n = mint()
s = list(minp())
t = list(minp())
c = [0]*26
for i in s:
c[ord(i)-ord('a')] += 1
for i in t:
c[ord(i)-ord('a')] += 1
same = True
for i in range(26):
if c[i] % 2 != 0:
print("No")
return
p = []
for i in range(n):
if s[i] != t[i]:
if find(s,s[i],i+1) != -1:
swap(s,t,find(s,s[i],i+1), i)
elif find(t,t[i],i+1) != -1:
swap(s,t,i,find(t,t[i],i+1))
else:
swap(s,t,i,i)
if find(s,s[i],i+1) != -1:
swap(s,t,find(s,s[i],i+1), i)
elif find(t,t[i],i+1) != -1:
swap(s,t,i,find(t,t[i],i+1))
#print(s,t)
if len(p) <= 2*n:
print("Yes")
print(len(p))
for i in p:
print(*i)
return
print("No")
for i in range(mint()):
solve()
|
1573052700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1111", "01010", "1011011"]
|
7e8baa4fb780f11e66bb2b7078e34c04
|
NoteIn the first test, it's easy to see, that the only unique substring of string $$$s = $$$"1111" is all string $$$s$$$, which has length $$$4$$$.In the second test a string $$$s = $$$"01010" has minimal unique substring $$$t =$$$"101", which has length $$$3$$$.In the third test a string $$$s = $$$"1011011" has minimal unique substring $$$t =$$$"110", which has length $$$3$$$.
|
Let $$$s$$$ be some string consisting of symbols "0" or "1". Let's call a string $$$t$$$ a substring of string $$$s$$$, if there exists such number $$$1 \leq l \leq |s| - |t| + 1$$$ that $$$t = s_l s_{l+1} \ldots s_{l + |t| - 1}$$$. Let's call a substring $$$t$$$ of string $$$s$$$ unique, if there exist only one such $$$l$$$. For example, let $$$s = $$$"1010111". A string $$$t = $$$"010" is an unique substring of $$$s$$$, because $$$l = 2$$$ is the only one suitable number. But, for example $$$t = $$$"10" isn't a unique substring of $$$s$$$, because $$$l = 1$$$ and $$$l = 3$$$ are suitable. And for example $$$t =$$$"00" at all isn't a substring of $$$s$$$, because there is no suitable $$$l$$$.Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.You are given $$$2$$$ positive integers $$$n$$$ and $$$k$$$, such that $$$(n \bmod 2) = (k \bmod 2)$$$, where $$$(x \bmod 2)$$$ is operation of taking remainder of $$$x$$$ by dividing on $$$2$$$. Find any string $$$s$$$ consisting of $$$n$$$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $$$k$$$.
|
Print a string $$$s$$$ of length $$$n$$$, consisting of symbols "0" and "1". Minimal length of the unique substring of $$$s$$$ should be equal to $$$k$$$. You can find any suitable string. It is guaranteed, that there exists at least one such string.
|
The first line contains two integers $$$n$$$ and $$$k$$$, separated by spaces ($$$1 \leq k \leq n \leq 100\,000$$$, $$$(k \bmod 2) = (n \bmod 2)$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_003.jsonl
|
825b99735298852deeb5725b991d0dfd
|
256 megabytes
|
["4 4", "5 3", "7 3"]
|
PASSED
|
N, K = map(int, input().split())
if N == K:
print("0"*N)
elif K == 1:
print("0"*(N-1) + "1")
elif K == 3:
print("1" + "0"*(N-4) + "101")
else:
res = ["0"]*N
for i in range(0, N, N//2-K//2+1):
res[i] = "1"
print(''.join(res))
|
1557671700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
5 seconds
|
["? 1 2\n40\n? 2 5\n90\n? 3 1\n56\n? 4 5\n18\n! 8 10 7 6 9\n? 1 5\n312\n? 2 4\n675\n! 24 25 28 27 26\n? 1 4\n4\n? 2 5\n10\n? 3 7\n21\n? 6 2\n6\n? 2 5\n10\n? 1 2\n2\n? 1 2\n2\n? 1 2\n2\n? 1 2\n2\n? 1 2\n2\n! 1 2 3 4 5 6 7"]
|
d66b80cd06c28d2a62167be699996285
| null |
Do you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells.Mike has tubular bells, too! They consist of $$$n$$$ tubes, and each of the tubes has a length that can be expressed by a integer from $$$l$$$ to $$$r$$$ inclusive. It is clear that the lengths of all the tubes are different (it makes no sense to make the same tubes). It is also known that $$$r-l+1 = n$$$.Formally, we can say that Mike's tubular bells are described by a permutation $$$a$$$ of length $$$n$$$ that contains all numbers from $$$l$$$ to $$$r$$$ inclusive, with $$$a_i$$$ denoting the length of the $$$i$$$-th tube.You are offered an interesting task: to guess what Mike's instrument looks like. Simply, you must guess the permutation.Mike won't tell you $$$l$$$ or $$$r$$$. He will only tell you $$$n$$$, and will allow you to ask no more than $$$n + 5000$$$ queries.In each query, you name two positive integers $$$x$$$, $$$y$$$ such that $$$1 \le x, y \le n, x \neq y$$$. In response to this query, the program written by Mike will give you $$$\mathrm{lcm}(a_x, a_y)$$$, where $$$\mathrm{lcm}(c,d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.Solve Mike's problem!
| null |
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 20$$$), denoting the number of test cases. Description of the test cases follows. The single line of each test case contains one positive integer $$$n$$$ ($$$3 \le n \le 10^5$$$)Β β number of tubes in Mike's tubular bells. Also $$$1 \le l \le r \le 2 \cdot 10^5$$$, i.e. the lengths of the tubes do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that the sum of maximal number of queries (i.e. $$$n + 5000$$$) over all test cases does not exceed $$$10^5 + 5000$$$. It means that sum of $$$n$$$ does not exceed $$$10^5 + 5000 - t \cdot 5000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,900 |
train_086.jsonl
|
c5702665f8d601c84bc7f7c259bd1fa0
|
512 megabytes
|
["3\n5\n8 10 7 6 9\n5\n24 25 28 27 26\n7\n1 2 3 4 5 6 7"]
|
PASSED
|
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")
from random import shuffle, randint
from math import gcd
def lcm(a, b): return (a * b) // gcd(a, b)
from collections import Counter
def gcd(x, y):
"""greatest common divisor of x and y"""
while y:
x, y = y, x % y
return x
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
def get_prime_factors(n, isPrime):
"""Returns prime factorisation of n!"""
if n < 2:
return []
result = []
while isPrime[n] != 1:
result += [isPrime[n]]
n //= isPrime[n]
result += [n]
return result
for _ in range(int(input())):
n = int(input())
def query(i, j):
print("?", i + 1, j + 1, flush=True)
return int(input())
if (n * (n - 1)) // 2 <= n + 5000:
a = ['!']
qx = {}
for i in range(n):
g = 0
for j in range(n):
if i == j: continue
if j > i:
qx[i, j] = query(i, j)
g = gcd(g, qx[(i, j)])
else:
g = gcd(g, qx[(j, i)])
a += [g]
if n == 3:
d = False
for i in range(1, 4):
for j in range(1, 4):
if i == j: continue
if abs(a[i] - a[j]) == 2:
k = 1 + 2 + 3 - i - j
a[k] = (a[i] + a[j]) // 2
d = True
break
if d: break
print(*a, flush=True)
continue
a = [-1] * n
indexes = list(range(n))
shuffle(indexes)
mx = 0
if n <= 9999:
di = {}
while indexes:
i = indexes.pop()
if not indexes:
j = n - 1 - i
else:
j = indexes.pop()
q = max(prime_factors(query(i, j)))
mx = max(mx, q)
di[q] = (i, j)
p, q = di[mx]
for i in range(n):
if i == p or i == q: continue
if query(i, q) % mx == 0:
p = q
break
a[p] = mx
for i in range(n):
if i != p:
a[i] = query(i, p) // mx
print(*['!'] + a, flush=True)
continue
idx2 = list(range(n))
shuffle(idx2)
while 1:
i = idx2.pop()
j = idx2.pop()
o = query(i, j)
pf = prime_factors(o)
if len(pf) == 2 and min(pf) ** 2 > 200000:
mx = max(pf)
p, q = i, j
for qq in range(30):
i = p
while i == p or i == q:
i = idx2.pop()
if query(i, p) % mx:
p = q
break
break
a[p] = mx
mx2 = (mx, p)
for i in range(n):
if i != p:
a[i] = query(i, p) // mx
if a[i] * a[i] <= 220000:
a[i] = -1
else:
mp = max(prime_factors(a[i]))
if mp != a[i]: continue
if mp > mx2[0]:
mx2 = (mp, i)
for i in range(n):
if a[i] == -1:
a[i] = query(i, mx2[1]) // mx2[0]
print(*['!'] + a, flush=True)
continue
|
1629988500
|
[
"number theory",
"math",
"probabilities"
] |
[
0,
0,
0,
1,
1,
1,
0,
0
] |
|
2 seconds
|
["2\n2\n2\n31680"]
|
667e320912f115d0b598bb45129b5845
| null |
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112β=β1192βΓβ11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
|
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
|
Input data contains multiple test cases. The first line of the input data contains an integer tΒ β the number of test cases (1ββ€βtββ€β100). The descriptions of test cases follow. Each test is described by two lines. The first line contains an integer n (1ββ€βnββ€β2000)Β β the number of cards in Borya's present. The second line contains n integers ai (1ββ€βaiββ€β109)Β β numbers written on the cards. It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_040.jsonl
|
c3903c246feff93bdb1eab67735760cd
|
512 megabytes
|
["4\n2\n1 1\n3\n1 31 12\n3\n12345 67 84\n9\n1 2 3 4 5 6 7 8 9"]
|
PASSED
|
mod = 998244353
f0 = [ [0 for i in range(11)] for j in range(2010) ]
f1 = [ [0 for i in range(11)] for j in range(2010) ]
fac = [0 for i in range(2010)]
tab = [0 for i in range(11)]
C = [ [0 for i in range(2010)] for j in range(2010) ]
def Init() :
fac[0] = 1
for i in range(2010) :
if i > 0 : fac[i] = fac[i - 1] * i % mod
C[i][0] = 1
for j in range(1, 2010) :
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod
def len(x) :
res = 0
while x > 0 :
res += 1
x = x // 10
return res
def solve() :
n = int(input())
f0[0][0] = f1[0][0] = 1
a = list(map(int, input().split()))
c0, c1 = 0, 0
s0, s1 = 0, 0
for nu in a :
m = nu % 11
if len(nu) & 1 :
c1 += 1
s1 += m
for i in range(11) :
f1[c1][i] = 0
for i in range(c1 - 1, -1, -1) :
for j in range(11) :
if f1[i][j] == 0 : continue
f1[i + 1][(j + m) % 11] += f1[i][j]
f1[i + 1][(j + m) % 11] %= mod
else :
c0 += 1
s0 += m
for i in range(11) :
f0[c0][i] = 0
for i in range(c0 - 1, -1, -1) :
for j in range(11) :
if f0[i][j] == 0 : continue
f0[i + 1][(j + m) % 11] += f0[i][j]
f0[i + 1][(j + m) % 11] %= mod
s1 %= 11
s0 %= 11
part = c1 // 2
for i in range(11) :
tab[i] = 0
for i in range(11) :
tab[(i + i + 11 - s1) % 11] = f1[c1 - part][i]
for i in range(11) :
tab[i] = tab[i] * fac[part] % mod * fac[c1 - part] % mod
ans = 0
if c1 == 0 :
ans = f0[c0][0] * fac[c0]
elif c0 == 0 :
ans = tab[0]
else :
for i in range(c0 + 1) :
for j in range(11) :
if f0[i][j] == 0 : continue
# print(f0[i][j], tab[(j + j + 11 - s0) % 11] \
# , fac[i] % mod * fac[c0 - i] % mod, C[j + (c1 - part) - 1][(c1 - part) - 1] % mod * C[part + c0 - i][part] % mod )
ans = ( ans \
+ fac[i] % mod * fac[c0 - i] % mod \
* f0[i][j] * tab[(j + j + 11 - s0) % 11] % mod \
* C[i + (c1 - part) - 1][(c1 - part) - 1] % mod \
* C[part + c0 - i][part]
) % mod
print(ans)
Init()
T = int(input())
for ttt in range(T) : solve()
|
1505050500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["14.0000000000\n12.0000000000\n8.0000000000\n6.0000000000\n4.0000000000", "19.6000000000\n18.6000000000\n16.6000000000\n13.6000000000\n12.6000000000"]
|
38388446f5c265f77124132caa3ce4d2
|
NoteConsider the first sample. There are 6 triples: (1,β2,β3),β(1,β3,β2),β(2,β1,β3),β(2,β3,β1),β(3,β1,β2),β(3,β2,β1). Because nβ=β3, the cost needed to build the network is always d(1,β2)β+βd(2,β3)β+βd(3,β1) for all the triples. So, the expected cost equals to d(1,β2)β+βd(2,β3)β+βd(3,β1).
|
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by nβ-β1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to nβ-β1. Let's define d(u,βv) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1ββ€βkββ€β3) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1,βc2)β+βd(c2,βc3)β+βd(c3,βc1) dollars. Santas are too busy to find the best place, so they decided to choose c1,βc2,βc3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.
|
Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10β-β6.
|
The first line contains an integer n (3ββ€βnββ€β105) β the number of cities in Tree World. Next nβ-β1 lines describe the roads. The i-th line of them (1ββ€βiββ€βnβ-β1) contains three space-separated integers ai, bi, li (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βliββ€β103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1ββ€βqββ€β105) β the number of road length changes. Next q lines describe the length changes. The j-th line of them (1ββ€βjββ€βq) contains two space-separated integers rj, wj (1ββ€βrjββ€βnβ-β1, 1ββ€βwjββ€β103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_030.jsonl
|
de9db05d6b113ff724fdfe4039da4f39
|
256 megabytes
|
["3\n2 3 5\n1 3 3\n5\n1 4\n2 2\n1 2\n2 1\n1 1", "6\n1 5 3\n5 3 2\n6 1 7\n1 4 4\n5 2 3\n5\n1 2\n2 1\n3 5\n4 1\n5 2"]
|
PASSED
|
from queue import Queue
import sys
cost = []
def readarray(): return map(int, input().split(' '))
n = int(input())
graph = [[] for i in range(n)]
for i in range(n - 1):
u, v, c = readarray()
u, v = u - 1, v - 1
cost.append(c)
graph[u].append((v, i))
graph[v].append((u, i))
order = []
used = [0] * n
q = [0] * (n + n)
qh = qt = 0
used[qh] = 1
qh += 1
while qt < qh:
v = q[qt]
qt += 1
order.append(v)
for (to, e) in graph[v]:
if used[to]:
continue
used[to] = 1
q[qh] = to
qh += 1
order.reverse()
sz = [0 for x in range(n)]
for v in order:
sz[v] = 1
for (to, e) in graph[v]:
sz[v] += sz[to]
"""
sz = [0] * n
sys.setrecursionlimit(100505)
def dfs(v, p):
sz[v] = 1
for (to, e) in graph[v]:
if to != p:
dfs(to, v)
sz[v] += sz[to]
dfs(0, -1)
"""
distanceSum = 0.0
edgeMult = [0] * n
for v in range(n):
for (to, e) in graph[v]:
x = min(sz[v], sz[to])
edgeMult[e] = x
distanceSum += 1.0 * cost[e] * x * (n - x)
distanceSum /= 2.0
queryCnt = int(input())
ans = []
for i in range(queryCnt):
x, y = readarray()
x -= 1
distanceSum -= 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x])
cost[x] = y
distanceSum += 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x])
ans.append('%.10lf' % (distanceSum / n / (n - 1) * 6.0))
print('\n'.join(ans))
|
1419951600
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR", "RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"]
|
7cec27879b443ada552a6474c4e45c30
|
NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.
|
Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match Β β it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.
|
For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) Β β the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,000 |
train_110.jsonl
|
3b47818779008796e93449d845f4f38c
|
256 megabytes
|
["3\n7 4 3\n6 5 1\n19 13 6", "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2"]
|
PASSED
|
t = int(input())
for _ in range(t):
n, r, b = [int(c) for c in input().split()]
if b == 1:
print('R' * (r // 2) + 'B' + 'R' * (r - r // 2))
continue
s = ['R' * (r // (b + 1)) + 'B'] * b + ['R' * (r // (b + 1))]
left = r % (b + 1)
for i in range(left):
s[i] += 'R'
print(''.join(s))
|
1650206100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n0\n3"]
|
e75b88ce4341062c20b6014da1152d29
|
NoteIn the first test case, you can, for example, put one extra block into the first box and make $$$a = [4, 2, 2]$$$. If your nephew chooses the box with $$$4$$$ blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with $$$2$$$ blocks then he will move these two blocks to the other box with $$$2$$$ blocks.In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.In the third test case, you should put $$$3$$$ extra blocks. For example, you can put $$$2$$$ blocks in the first box and $$$1$$$ block in the third box. You'll get array $$$a = [2, 3, 1]$$$.
|
You are asked to watch your nephew who likes to play with toy blocks in a strange way.He has $$$n$$$ boxes and the $$$i$$$-th box has $$$a_i$$$ blocks. His game consists of two steps: he chooses an arbitrary box $$$i$$$; he tries to move all blocks from the $$$i$$$-th box to other boxes. If he can make the same number of blocks in each of $$$n - 1$$$ other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box $$$i$$$ he chooses he won't be sad. What is the minimum number of extra blocks you need to put?
|
For each test case, print a single integerΒ β the minimum number of blocks you need to put. It can be proved that the answer always exists, i.Β e. the number of blocks is finite.
|
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 the integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the number of boxes. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)Β β the number of blocks in each box. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_002.jsonl
|
6dfaf6a3ea6472d1dfbce0a6ae5656d7
|
256 megabytes
|
["3\n3\n3 2 2\n4\n2 2 3 2\n3\n0 3 0"]
|
PASSED
|
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
m=max(a)
an=0
if n==2:print(0)
else:
an=0
s=sum(a)
p=m*(n-1)
if p<s:
i=s//(n-1)
p=i*(n-1)
if p<s:
p=(i+1)*(n-1)
an=p-sum(a)
print(abs(an))
|
1605796500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["2 3 4 5 6", "5", "9 11 13 15 17 19 21 25 27 33"]
|
1bdcc566e5593429136cf216d361508b
| null |
A thief made his way to a shop.As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai.The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind).Find all the possible total costs of products the thief can nick into his knapsack.
|
Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order.
|
The first line contains two integers n and k (1ββ€βn,βkββ€β1000) β the number of kinds of products and the number of products the thief will take. The second line contains n integers ai (1ββ€βaiββ€β1000) β the costs of products for kinds from 1 to n.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_079.jsonl
|
df4ae64febda31308aea5eabafc9b42b
|
512 megabytes
|
["3 2\n1 2 3", "5 5\n1 1 1 1 1", "3 3\n3 5 11"]
|
PASSED
|
n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
a = list(set(a))
a.sort()
mn, mx = a[0], a[-1]
lo = mn * k
hi = mx * k
D = [t - mn for t in a]
modify_cnt = [k+1] * 1000010
modify_cnt[0] = 0
for d in D:
if d == 0: continue
for i in xrange(0, hi - d + 1):
modify_cnt[i+d] = min(modify_cnt[i+d], modify_cnt[i]+1)
ans = [j+mn*k for j in xrange(hi+1) if modify_cnt[j] <= k]
print ' '.join(map(str, ans))
|
1456844400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0.800000000000", "0.260000000000"]
|
b4ac594755951e84001dfd610d420eb5
|
NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1Β·0.8β+β0.9Β·0.2β=β0.26.
|
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
|
Print a single real number β the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10β-β9.
|
The first line contains a single integer n (1ββ€βnββ€β100) β the number of Andrey's friends. The second line contains n real numbers pi (0.0ββ€βpiββ€β1.0) β the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_011.jsonl
|
7b4b90215bc3d513f37d8fdb27ec05fc
|
256 megabytes
|
["4\n0.1 0.2 0.3 0.8", "2\n0.1 0.2"]
|
PASSED
|
def C():
n = int(input())
tmp = input()
tmp = tmp.split()
probability = list(map(float,tmp))
probability.sort()
current = probability[n-1]
pre = 1 - probability[n-1]
for i in range(n-2,-1,-1):
tmp = current * (1-probability[i]) + pre * (probability[i])
if (tmp > current):
current = tmp
pre = pre * (1-probability[i])
print("%.12f" % current)
if __name__ == "__main__":
C()
|
1403191800
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["1, 2, 3, ..., 10", "1, , , 4 ...5 ... ...6", "..., 1, 2, 3, ..."]
|
c7d8c71a1f7e6c7364cce5bddd488a2f
| null |
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2Β ,3,...,Β Β Β 10" will be corrected to "1,Β 2,Β 3,Β ...,Β 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be: a positive integer of an arbitrary length (leading zeroes are not allowed), a "comma" symbol (","), a "space" symbol (" "), "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following: each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it), each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term), if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left, there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.
|
Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.
|
The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_014.jsonl
|
90370fc6a182c2bf23753c1f5c34101b
|
256 megabytes
|
["1,2 ,3,..., 10", "1,,,4...5......6", "...,1,2,3,..."]
|
PASSED
|
ans = input()
while " ," in ans:
ans = ans.replace(" ,", ",")
ans = ans.replace("...", " ...").replace(",", ", ")
while " " in ans:
ans = ans.replace(" ", " ")
for d in "0123456789": ans = ans.replace(". " + d, "." + d)
print(ans.strip(), end="")
|
1304485200
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["20\n1 2 3 4 5 \n5 2 4 3 1", "8\n1 2 3 \n3 2 1", "-1"]
|
5659275a002a3e6fc45b79ded33202e2
|
NoteIn the first example the order of runners on the first track should be $$$[5, 3, 2, 1, 4]$$$, and the order of runners on the second track should be $$$[1, 4, 2, 5, 3]$$$. Then the duration of the competition is $$$max(5, 1) + max(3, 4) + max(2, 2) + max(1, 5) + max(4, 3) = 5 + 4 + 2 + 5 + 4 = 20$$$, so it is equal to the maximum allowed duration.In the first example the order of runners on the first track should be $$$[2, 3, 1]$$$, and the order of runners on the second track should be $$$[2, 1, 3]$$$. Then the duration of the competition is $$$8$$$, and it is the maximum possible duration for $$$n = 3$$$.
|
Demonstrative competitions will be held in the run-up to the $$$20NN$$$ Berlatov Olympic Games. Today is the day for the running competition!Berlatov team consists of $$$2n$$$ runners which are placed on two running tracks; $$$n$$$ runners are placed on each track. The runners are numbered from $$$1$$$ to $$$n$$$ on each track. The runner with number $$$i$$$ runs through the entire track in $$$i$$$ seconds.The competition is held as follows: first runners on both tracks start running at the same time; when the slower of them arrives at the end of the track, second runners on both tracks start running, and everyone waits until the slower of them finishes running, and so on, until all $$$n$$$ pairs run through the track.The organizers want the run to be as long as possible, but if it lasts for more than $$$k$$$ seconds, the crowd will get bored. As the coach of the team, you may choose any order in which the runners are arranged on each track (but you can't change the number of runners on each track or swap runners between different tracks).You have to choose the order of runners on each track so that the duration of the competition is as long as possible, but does not exceed $$$k$$$ seconds.Formally, you want to find two permutations $$$p$$$ and $$$q$$$ (both consisting of $$$n$$$ elements) such that $$$sum = \sum\limits_{i=1}^{n} max(p_i, q_i)$$$ is maximum possible, but does not exceed $$$k$$$. If there is no such pair, report about it.
|
If it is impossible to reorder the runners so that the duration of the competition does not exceed $$$k$$$ seconds, print $$$-1$$$. Otherwise, print three lines. The first line should contain one integer $$$sum$$$ β the maximum possible duration of the competition not exceeding $$$k$$$. The second line should contain a permutation of $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ should be pairwise distinct) β the numbers of runners on the first track in the order they participate in the competition. The third line should contain a permutation of $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ should be pairwise distinct) β the numbers of runners on the second track in the order they participate in the competition. The value of $$$sum = \sum\limits_{i=1}^{n} max(p_i, q_i)$$$ should be maximum possible, but should not exceed $$$k$$$. If there are multiple answers, print any of them.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6, 1 \le k \le n^2$$$) β the number of runners on each track and the maximum possible duration of the competition, respectively.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_009.jsonl
|
23a73b0cdc9d21e18a74799019aca3f9
|
256 megabytes
|
["5 20", "3 9", "10 54"]
|
PASSED
|
import sys
input = sys.stdin.readline
def sum1n(n):
return (n*(n+1))//2
def count_max(n):
k1 = n//2
k2 = n - k1
return 2*sum1n(n) - sum1n(k1) - sum1n(k2)
n, k = map(int, input().split())
mn = n*(n+1) // 2
if k < mn:
print("-1")
else:
mx = count_max(n)
target = min(k, mx)
print(str(target)+"\n")
a = [i for i in range(1, n+1)]
b = [i for i in range(1, n+1)]
cur = mn
i = n-1
while cur != target:
f = a[i]
s = n+1-a[i]
if f-s < target-cur:
## print(i)
## print(a)
## print(b)
b[i], b[n-1-i] = b[n-1-i], b[i]
cur += f-s
i -= 1
else:
j = a[i] - (target-cur) - 1
b[i], b[j] = b[j], b[i]
cur = target
## print("11")
print(" ".join(map(str, a)))
print(" ".join(map(str, b)))
|
1570957500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4 3 1 2", "4 3 2 5 1", "2 1"]
|
a133b2c63e1025bdf13d912497f9b6a4
| null |
Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1ββ€βiββ€βn) has a best friend p[i] (1ββ€βp[i]ββ€βn). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who iβ=βp[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: on the first day of revising each student studies his own Mathematical Analysis notes, in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1ββ€βiββ€βn) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising: a1,βa2,β...,βan, where ai means the student who gets the i-th student's notebook on the third day of revising; b1,βb2,β...,βbn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.
|
Print sequence n of different integers p[1],βp[2],β...,βp[n] (1ββ€βp[i]ββ€βn). It is guaranteed that the solution exists and that it is unique.
|
The first line contains integer n (1ββ€βnββ€β105) β the number of students in the group. The second line contains sequence of different integers a1,βa2,β...,βan (1ββ€βaiββ€βn). The third line contains the sequence of different integers b1,βb2,β...,βbn (1ββ€βbiββ€βn).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_030.jsonl
|
06a431c9d2e10121b872af9ab0d48d38
|
256 megabytes
|
["4\n2 1 4 3\n3 4 2 1", "5\n5 2 3 1 4\n1 3 2 4 5", "2\n1 2\n2 1"]
|
PASSED
|
x = input()
a = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]
bestFriends = {}
for i,j in zip(a,b):
bestFriends[i] = j
for i in range(len(a)):
print(bestFriends[i+1],end=" ")
|
1335078000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4", "1", "-1"]
|
6946f088e462d12da47419f492ad51ea
|
NoteNote to the first example. If you delete the $$$4$$$-th element, you can get the arithmetic progression $$$[2, 4, 6, 8]$$$.Note to the second example. The original sequence is already arithmetic progression, so you can delete $$$1$$$-st or last element and you will get an arithmetical progression again.
|
A sequence $$$a_1, a_2, \dots, a_k$$$ is called an arithmetic progression if for each $$$i$$$ from $$$1$$$ to $$$k$$$ elements satisfy the condition $$$a_i = a_1 + c \cdot (i - 1)$$$ for some fixed $$$c$$$.For example, these five sequences are arithmetic progressions: $$$[5, 7, 9, 11]$$$, $$$[101]$$$, $$$[101, 100, 99]$$$, $$$[13, 97]$$$ and $$$[5, 5, 5, 5, 5]$$$. And these four sequences aren't arithmetic progressions: $$$[3, 1, 2]$$$, $$$[1, 2, 4, 8]$$$, $$$[1, -1, 1, -1]$$$ and $$$[1, 2, 3, 3, 3]$$$.You are given a sequence of integers $$$b_1, b_2, \dots, b_n$$$. Find any index $$$j$$$ ($$$1 \le j \le n$$$), such that if you delete $$$b_j$$$ from the sequence, you can reorder the remaining $$$n-1$$$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.
|
Print such index $$$j$$$ ($$$1 \le j \le n$$$), so that if you delete the $$$j$$$-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.
|
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) β length of the sequence $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$) β elements of the sequence $$$b$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_002.jsonl
|
58502abe75e2f867247347d1ca1b0688
|
256 megabytes
|
["5\n2 6 8 7 4", "8\n1 2 3 4 5 6 7 8", "4\n1 2 4 8"]
|
PASSED
|
def main():
buf = input()
n = int(buf)
buf = input()
buflist = buf.split()
if n == 2 or n == 3:
print(1) # corner
return
b = list(map(int, buflist))
for i in range(n):
b[i] = (b[i], i)
b.sort()
delta = []
for i in range(n-1):
delta.append(b[i+1][0] - b[i][0])
deltamap = dict()
for x in delta:
if x in deltamap:
deltamap[x] += 1
else:
deltamap[x] = 1
if len(deltamap) == 1:
print(b[0][1] + 1) # arithmetic progression already
return
#print(delta)
#print(deltamap, len(deltamap))
zero_candidate = []
norm_candidate = []
for k, v in deltamap.items():
if v == n - 2:
zero_candidate.append(k)
elif v == n - 3:
norm_candidate.append(k)
if zero_candidate:
if delta[0] != zero_candidate[0]:
print(b[0][1] + 1) # delete first
return
elif delta[-1] != zero_candidate[0]:
print(b[-1][1] + 1) # delete last
return
elif 0 in deltamap:
if zero_candidate[0] == 0:
print(-1)
return
for i, x in enumerate(delta):
if x == 0:
print(b[i][1] + 1) # delete same num
return
print(-1) # impossible
return
elif norm_candidate:
if 0 in deltamap:
print(-1)
return
for x in norm_candidate:
for i in range(n-2):
if delta[i] + delta[i+1] == x:
print(b[i+1][1] + 1)
return
print(-1) # impossible
return
else:
print(-1) # impossible
return
if __name__ == '__main__':
main()
|
1560955500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["6 -3"]
|
a01e1c545542c1641eca556439f0692e
| null |
A line on the plane is described by an equation Axβ+βByβ+βCβ=β0. You are to find any point on this line, whose coordinates are integer numbers from β-β5Β·1018 to 5Β·1018 inclusive, or to find out that such points do not exist.
|
If the required point exists, output its coordinates, otherwise output -1.
|
The first line contains three integers A, B and C (β-β2Β·109ββ€βA,βB,βCββ€β2Β·109) β corresponding coefficients of the line equation. It is guaranteed that A2β+βB2β>β0.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_002.jsonl
|
917234d6fbbb0ad6d14506948dfd7760
|
256 megabytes
|
["2 5 3"]
|
PASSED
|
def extgcd(a, b):
if b == 0:
return 1, 0, a
x, y, g = extgcd(b, a % b)
return y, x - y * (a // b), g
a, b, c = map(int, raw_input().split())
x, y, g = extgcd(a, b)
if c % g != 0:
print -1
else:
t = c // g
print -x * t, -y * t
|
1270136700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1\n4\n2"]
|
bdce4761496c88a3de00aa863ba7308d
| null |
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and iβ+β1 for all i: 1ββ€βiββ€βnβ-β1) on every floor x, where aββ€βxββ€βb. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta,βfa), (tb,βfb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
|
For each query print a single integer: the minimum walking time between the locations in minutes.
|
The first line of the input contains following integers: n: the number of towers in the building (1ββ€βnββ€β108), h: the number of floors in each tower (1ββ€βhββ€β108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1ββ€βaββ€βbββ€βh), k: total number of queries (1ββ€βkββ€β104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1ββ€βta,βtbββ€βn, 1ββ€βfa,βfbββ€βh). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,000 |
train_004.jsonl
|
b117097a1241bdc521744c31456d4bc9
|
256 megabytes
|
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
|
PASSED
|
from sys import stdin
n,h,a,b,k = map(int,stdin.readline().split())
for _ in xrange(k):
t1,f1,t2,f2 = map(int,stdin.readline().split())
ans = abs(t1-t2)
if t1 !=t2:
if f1 < a:
ans += a-f1
f1 = a
if f1 > b:
ans += f1 - b
f1 = b
ans += abs(f1-f2)
print ans
|
1533994500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5\n1\n2\n1\n0\n3"]
|
a544dd9fd96379f66a960de6f973dd50
|
NoteThe first test case is explained in the statements.In the second test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},3]$$$.In the third test case, you can insert two elements, $$$a=[6,\underline{\textbf{4}},\underline{\textbf{2}},1]$$$.In the fourth test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},4,2]$$$.In the fifth test case, the array $$$a$$$ is already dense.
|
Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $$$i$$$ ($$$1 \le i \le n-1$$$), this condition must be satisfied: $$$$$$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$$$$$For example, the arrays $$$[1, 2, 3, 4, 3]$$$, $$$[1, 1, 1]$$$ and $$$[5, 10]$$$ are dense. And the arrays $$$[5, 11]$$$, $$$[1, 4, 2]$$$, $$$[6, 6, 1]$$$ are not dense.You are given an array $$$a$$$ of $$$n$$$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if $$$a=[4,2,10,1]$$$, then the answer is $$$5$$$, and the array itself after inserting elements into it may look like this: $$$a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$$$ (there are other ways to build such $$$a$$$).
|
For each test case, output one integerΒ β the minimum number of numbers that must be added to the array to make it dense.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$)Β β the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 50$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_098.jsonl
|
bdb2106e2a28a3ad09b8eabdc0f4af38
|
256 megabytes
|
["6\n4\n4 2 10 1\n2\n1 3\n2\n6 1\n3\n1 4 2\n5\n1 2 3 4 3\n12\n4 31 25 50 30 20 34 46 42 16 15 16"]
|
PASSED
|
import math
n = int(input())
for x in range(n):
l = int(input())
a = list(map(int,input().split()))
f = 0
for i in range(len(a) - 1):
low = min(a[i],a[i+1])
high = max(a[i],a[i+1])
while high > low * 2:
low *= 2
f += 1
print(f)
|
1613486100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nNO\nYES\nYES\nYES"]
|
8b926a19f380a56018308668c17c6928
|
NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again.
|
Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \le i \le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.
|
Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output "YES" if Vlad can eat candy as planned, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) β the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_105.jsonl
|
2614f01e6c86016d68b84a0a38ee655c
|
256 megabytes
|
["6\n2\n2 3\n1\n2\n5\n1 6 2 4 3\n4\n2 2 2 1\n3\n1 1000000000 999999999\n1\n1"]
|
PASSED
|
for t in range(int(input())):
n = input()
candies = sorted(list(map(int, input().split())))
if len(candies) == 1:
res = 'Yes' if candies[0] == 1 else 'No'
else:
res = 'Yes' if candies[-1] - candies[-2] <= 1 else 'No'
print(res)
|
1648737300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["9\n297\n0\n14"]
|
1e54530bc8cff81199b9cc1a6e51d638
|
NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
|
You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
|
For each testcase print a single integer β the maximum beauty of a proper subsegment.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_098.jsonl
|
accd1ab314ec8506510d9f43430ec28b
|
256 megabytes
|
["4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8"]
|
PASSED
|
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int,input().split()))
maxpos=0
minpos=1
ans=0
for i in range(n):
if a[i]>=a[maxpos]:
maxpos=i
if a[i]<=a[minpos]:
minpos=i
min1=999999999999999
max1=0
#print(maxpos,minpos)
for i in range(min(minpos,maxpos)):
if a[i]<min1:
min1=a[i]
if a[i]>max1:
max1=a[i]
min2=999999999999999
max2=0
for i in range(min(minpos,maxpos)+1,max(minpos,maxpos)):
if a[i]<min2:
min2=a[i]
if a[i]>max2:
max2=a[i]
min3=9999999999999
max3=0
for i in range(max(minpos,maxpos)+1,n):
if a[i]<min3:
min3=a[i]
if a[i]>max3:
max3=a[i]
mina = min(min1,min2,min3)
maxa = max(max1,max2,max3)
ans = a[maxpos]-a[minpos]+maxa-mina
print(ans)
|
1660829700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n2 1 2\n1 1 2", "3\n2 2 3\n1 1 3\n1 1 2", "0"]
|
3b2c5410441e588806690056693514a8
| null |
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (nβ-β1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: Swap i-th and j-th rows of the matrix; Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if iβ>βj.
|
Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (mββ€β105) β the number of actions. In each of the next m lines print three space-separated integers t,βi,βj (1ββ€βtββ€β2,β1ββ€βi,βjββ€βn,βiββ βj), where tβ=β1 if you want to swap rows, tβ=β2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
|
The first line contains an integer n (2ββ€βnββ€β1000) β the number of rows and columns. Then follow nβ-β1 lines that contain one's positions, one per line. Each position is described by two integers xk,βyk (1ββ€βxk,βykββ€βn), separated by a space. A pair (xk,βyk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_037.jsonl
|
f05be1c61c7cca535779b5762517d3db
|
256 megabytes
|
["2\n1 2", "3\n3 1\n1 3", "3\n2 1\n3 2"]
|
PASSED
|
n = int(input())
a = []
b = [0] * (n+1)
c = [10000] * (n+1)
for i in range(0,n-1):
p1,p2 = list(map(int,input().split()))
a.append((p1,p2))
b[p1] = max(b[p1],p2)
ans = []
for i in range(1,n+1):
if b[i]==0: continue
k = 0
for j in range(i,n+1):
if b[j]==0:
k=j
break
if k==0:break
b[j]=b[i]
b[i]=0
for j in range(0,n-1):
if a[j][0]==i: a[j]=(k,a[j][1])
ans.append((1,i,k))
for i in a:
c[i[1]]=min(c[i[1]],i[0])
for i in range(1,n+1):
k=i
for j in range(i+1,n+1):
if c[j]<c[i]: i=j
if (i==k): continue
ans.append((2,i,k))
c[0]=c[i];c[i]=c[k];c[k]=c[0]
print(len(ans))
for i in ans:print(i[0],i[1],i[2])
|
1358868600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "274201", "12"]
|
1e55358988db2fce66b8a53daae50d83
| null |
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract kββ₯β1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1,βa2,β...,βak and b1,βb2,β...,βbk satisfying the following requirements: kββ₯β1 Β Β t is a substring of string saisaiβ+β1... sbi (string s is considered as 1-indexed). As the number of ways can be rather large print it modulo 109β+β7.
|
Print the answer in a single line.
|
Input consists of two lines containing strings s and t (1ββ€β|s|,β|t|ββ€β105). Each string consists of lowercase Latin letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_009.jsonl
|
5c845e8e5f301a93b10b94b6d558b7e9
|
256 megabytes
|
["ababa\naba", "welcometoroundtwohundredandeightytwo\nd", "ddd\nd"]
|
PASSED
|
s, t = input(), input()
n, m = len(t), len(s) + 1
d = 1000000007
g = [1] * m
f = k = 0
for i in range(1, m):
if s[i - n:i] == t: k = i
if k: f = (f + g[k - n]) % d
g[i] += (g[i - 1] + f) % d
print(f)
|
1418488200
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["LDL", "NO", "WLLLLLWWWWWWWWLWLWDW"]
|
1321013edb706b2e3f3946979c4a5916
| null |
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.Last evening Roma started to play poker. He decided to spend no more than k virtual bourles β he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: In the end the absolute difference between the number of wins and loses is equal to k; There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.
|
If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO. Otherwise print this sequence. If there are multiple answers, print any of them.
|
The first line contains two numbers n (the length of Roma's sequence) and k (1ββ€βn,βkββ€β1000). The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_023.jsonl
|
e1bd8a077099a2545813381fb0a9eb67
|
256 megabytes
|
["3 2\nL??", "3 1\nW??", "20 5\n?LLLLLWWWWW?????????"]
|
PASSED
|
n, k = [int(i) for i in input().split()]
s = input()
dp = [[False] * 2100 for i in range(1001)]
dp[0][0] = True
for i in range(n):
l = -k + 1
r = k
if i == n - 1:
l -= 1
r += 1
for b in range(l, r):
if s[i] == 'L':
dp[i + 1][b] = dp[i][b + 1]
elif s[i] == 'W':
dp[i + 1][b] = dp[i][b - 1]
elif s[i] == 'D':
dp[i + 1][b] = dp[i][b]
else:
dp[i + 1][b] = dp[i][b + 1] or dp[i][b - 1] or dp[i][b]
ans = []
i = n
b = -1
if dp[i][k]:
b = k
elif dp[i][-k]:
b = -k
if b == -1:
print("NO")
else:
while i > 0:
if (s[i - 1] == 'L' or s[i - 1] == '?') and dp[i][b] == dp[i - 1][b + 1]:
ans.append('L')
b += 1
elif (s[i - 1] == 'W' or s[i - 1] == '?') and dp[i][b] == dp[i - 1][b - 1]:
ans.append('W')
b -= 1
else:
ans.append('D')
i -= 1
for j in reversed(ans):
print(j, end='')
|
1493391900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["0\n1\n2\n0"]
|
d0c50562764f2008045fe57e5da5de1c
| null |
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $$$h$$$, and there is a moving platform on each height $$$x$$$ from $$$1$$$ to $$$h$$$.Each platform is either hidden inside the cliff or moved out. At first, there are $$$n$$$ moved out platforms on heights $$$p_1, p_2, \dots, p_n$$$. The platform on height $$$h$$$ is moved out (and the character is initially standing there).If you character is standing on some moved out platform on height $$$x$$$, then he can pull a special lever, which switches the state of two platforms: on height $$$x$$$ and $$$x - 1$$$. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.Your character is quite fragile, so it can safely fall from the height no more than $$$2$$$. In other words falling from the platform $$$x$$$ to platform $$$x - 2$$$ is okay, but falling from $$$x$$$ to $$$x - 3$$$ (or lower) is certain death. Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $$$h$$$, which is unaffected by the crystals). After being used, the crystal disappears.What is the minimum number of magic crystal you need to buy to safely land on the $$$0$$$ ground level?
|
For each query print one integer β the minimum number of magic crystals you have to spend to safely come down on the ground level (with height $$$0$$$).
|
The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) β the number of queries. Each query contains two lines and is independent of all other queries. The first line of each query contains two integers $$$h$$$ and $$$n$$$ ($$$1 \le h \le 10^9$$$, $$$1 \le n \le \min(h, 2 \cdot 10^5)$$$) β the height of the cliff and the number of moved out platforms. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$h = p_1 > p_2 > \dots > p_n \ge 1$$$) β the corresponding moved out platforms in the descending order of their heights. The sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,600 |
train_000.jsonl
|
b084f1988c923dff4a8b4fa95dc6f846
|
256 megabytes
|
["4\n3 2\n3 1\n8 6\n8 7 6 5 3 2\n9 6\n9 8 5 4 3 1\n1 1\n1"]
|
PASSED
|
#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from random import randint
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
import sys
import os
import re
sys.setrecursionlimit(9999)
inf = float('inf')
mod = int(1e9) + 7
mod_ = 998244353
N = 5001
'''
Check for special cases (n=1)
One wrong submission = 10 mins penalty!
do smth instead of nothing and stay organized
'''
def main():
for _ in range(int(input())):
h, n = map(int, input().split())
arr = list(set(map(int, input().split())))
if n == 1:
print(0)
continue
cnt = 0
ind = 0
while arr[ind] > 2:
gap = arr[ind]-arr[ind+1]
# if gap == 2:
# ind += 1
# else:
arr[ind] = arr[ind+1]+1
if ind+2 > n-1:
if arr[ind] > 2 and arr[ind+1]+1 > 2:
cnt += 1
break
if arr[ind]-arr[ind+2] > 2:
arr[ind+1] = arr[ind+2]+1
cnt += 1
ind += 1
else:
ind += 2
if ind+1 > n-1 or arr[ind] <= 2:
break
# print(arr)
print(cnt)
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(
b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def gcd(x, y):
while y:
x, y = y, x % y
return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
def bootstrap(cont):
call, arg = cont.switch()
while True:
call, arg = cont.switch(to=continulet(
lambda _, f, args: f(*args), call, arg))
cont = continulet(bootstrap)
cont.switch()
main()
|
1570545300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nYES"]
|
a4a69a5fbf35781ff0849332a45566ca
|
NoteIn the first testcase, the first stick can be broken into parts of length $$$1$$$ and $$$5$$$. We can construct a rectangle with opposite sides of length $$$1$$$ and $$$5$$$.In the second testcase, breaking the stick of length $$$2$$$ can only result in sticks of lengths $$$1, 1, 2, 5$$$, which can't be made into a rectangle. Breaking the stick of length $$$5$$$ can produce results $$$2, 3$$$ or $$$1, 4$$$ but neither of them can't be put into a rectangle.In the third testcase, the second stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$2$$$ (which is a square).In the fourth testcase, the third stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$5$$$.
|
There are three sticks with integer lengths $$$l_1, l_2$$$ and $$$l_3$$$.You are asked to break exactly one of them into two pieces in such a way that: both pieces have positive (strictly greater than $$$0$$$) integer length; the total length of the pieces is equal to the original length of the stick; it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.
|
For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of testcases. The only line of each testcase contains three integers $$$l_1, l_2, l_3$$$ ($$$1 \le l_i \le 10^8$$$)Β β the lengths of the sticks.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_085.jsonl
|
59f885d8666a7c2192a772a8d8713fa9
|
256 megabytes
|
["4\n6 1 5\n2 5 2\n2 4 2\n5 5 4"]
|
PASSED
|
n=int(input())
for i in range(n):
a, b, c=map(int, input().split())
if a+b==c or a+c==b or b+c==a or a==b and c%2==0 or a==c and b%2==0 or b==c and a%2==0:
print("YES")
else:
print("NO")
# Tue Jan 25 2022 07:44:44 GMT+0000 (Coordinated Universal Time)
|
1640615700
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["16", "21"]
|
2022f53e5a88d5833e133dc3608a122c
|
NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$.
|
A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.
|
Print a single integerΒ β the maximum possible total score of the class.
|
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$)Β β the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le 1000$$$)Β β the number of points for the correct answer for every question.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 900 |
train_010.jsonl
|
ec3859373986b1f46e5a80b7a78b3978
|
256 megabytes
|
["2 4\nABCD\nABCE\n1 2 3 4", "3 3\nABC\nBCD\nCDE\n5 4 12"]
|
PASSED
|
stu_ex = input().split(" ")
student, exam = [int(a) for a in stu_ex]
ans = [[0, 0, 0, 0, 0] for i in range(0, exam)]
#print(ans)
for i in range(0, student):
std_ans = input()
for j in range(0, exam):
choose = 0
if std_ans[j] == 'B':
choose = 1
elif std_ans[j] == 'C':
choose = 2
elif std_ans[j] == 'D':
choose = 3
elif std_ans[j] == 'E':
choose = 4
ans[j][choose] += 1
score = [int(a) for a in input().split(" ")]
max_score = 0
for i in range(0, exam):
max_score += score[i] * max(ans[i])
print(max_score)
|
1564936500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1\n4\n0\n8"]
|
293f9b996eee9f76d4bfdeda85685baa
|
NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side.
|
Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.
|
For each test case, output one integerΒ β how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.
|
The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \leq p, a, b, c \leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_109.jsonl
|
a792a60220a904f70f86e099cc76d0ad
|
512 megabytes
|
["4\n9 5 4 8\n2 6 10 9\n10 2 5 10\n10 9 9 9"]
|
PASSED
|
# import sys
# sys.stdout = open('DSA/Stacks/output.txt', 'w')
# sys.stdin = open('DSA/Stacks/input.txt', 'r')
for _ in range(int(input())):
p,a,b,c = map(int, input().split())
zz = [a,b,c]
for i in range(len(zz)):
if p%zz[i]==0:
zz[i]=0
else:
zz[i] = zz[i]-(p%zz[i])
print(min(zz))
|
1614071100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2"]
|
4431081cd58c4e0fdc40e55116f5b2e6
|
NoteFor the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
|
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1ββ€βaiββ€βn). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (akβ=βk). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109β+β7).
|
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109β+β7).
|
The first line contains integer n (2ββ€βnββ€β2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_037.jsonl
|
4de53861104c3b008bcb9bac5a202344
|
256 megabytes
|
["5\n-1 -1 4 3 -1"]
|
PASSED
|
def fact(x):
ans=1
for i in range(2,x+1):
ans*=i
return ans
n=int(input())
a=[int(x) for x in input().split()]
s=set(a)
x=0
y=0
for i in range(1,n+1):
if a[i-1]==-1:
g=i in s
(x,y)=(x+1-g,y+g)
otv=fact(x+y)
currf=fact(x+y-1)//fact(x-1)*fact(x)
if x:
otv-=currf
for i in range(2,x+1):
currf//=i
currf*=x-i+1
currf//=x+y-i+1
if i&1:
otv-=currf
else:
otv+=currf
otv%=1000000007
print(otv)
# Made By Mostafa_Khaled
|
1377876600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n2\n1", "1\n1\n-1\n-1"]
|
e6ce5b7211a6680ebce5250edfc59e72
|
NoteIn the first example there are three queries: query $$$[1; 3]$$$ can be covered by interval $$$[1; 3]$$$; query $$$[1; 4]$$$ can be covered by intervals $$$[1; 3]$$$ and $$$[2; 4]$$$. There is no way to cover $$$[1; 4]$$$ by a single interval; query $$$[3; 4]$$$ can be covered by interval $$$[2; 4]$$$. It doesn't matter that the other points are covered besides the given query. In the second example there are four queries: query $$$[1; 2]$$$ can be covered by interval $$$[1; 3]$$$. Note that you can choose any of the two given intervals $$$[1; 3]$$$; query $$$[1; 3]$$$ can be covered by interval $$$[1; 3]$$$; query $$$[1; 4]$$$ can't be covered by any set of intervals; query $$$[1; 5]$$$ can't be covered by any set of intervals. Note that intervals $$$[1; 3]$$$ and $$$[4; 5]$$$ together don't cover $$$[1; 5]$$$ because even non-integer points should be covered. Here $$$3.5$$$, for example, isn't covered.
|
You are given $$$n$$$ intervals in form $$$[l; r]$$$ on a number line.You are also given $$$m$$$ queries in form $$$[x; y]$$$. What is the minimal number of intervals you have to take so that every point (not necessarily integer) from $$$x$$$ to $$$y$$$ is covered by at least one of them? If you can't choose intervals so that every point from $$$x$$$ to $$$y$$$ is covered, then print -1 for that query.
|
Print $$$m$$$ integer numbers. The $$$i$$$-th number should be the answer to the $$$i$$$-th query: either the minimal number of intervals you have to take so that every point (not necessarily integer) from $$$x_i$$$ to $$$y_i$$$ is covered by at least one of them or -1 if you can't choose intervals so that every point from $$$x_i$$$ to $$$y_i$$$ is covered.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) β the number of intervals and the number of queries, respectively. Each of the next $$$n$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i < r_i \le 5 \cdot 10^5$$$) β the given intervals. Each of the next $$$m$$$ lines contains two integer numbers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i < y_i \le 5 \cdot 10^5$$$) β the queries.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_042.jsonl
|
9220c3e1057cd55003561e7e1b6d2f44
|
256 megabytes
|
["2 3\n1 3\n2 4\n1 3\n1 4\n3 4", "3 4\n1 3\n1 3\n4 5\n1 2\n1 3\n1 4\n1 5"]
|
PASSED
|
from __future__ import division, print_function
DEBUG = 0
import os, sys
from atexit import register
from io import BytesIO
import itertools
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
if DEBUG:
debug_print = print
else:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
debug_print = lambda *x, **y: None
def input_as_list():
return list(map(int, input().split()))
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
def build_binary_lifting_array(tree):
""" Tree is represented as parent of node n = tree[n].
Parent of the root node should be -1.
"""
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
size = len(tree)
max_depth = size.bit_length()
result = array_of(lambda:-1, max_depth, size)
result[0] = list(tree)
for depth in range(1, max_depth):
for node in range(0, size):
try:
result[depth][node] = result[depth - 1][result[depth - 1][node]]
except:
pass
return result
def main():
n, m = input_as_list()
segs = [input_as_list() for _ in range(n)]
queries = [input_as_list() for _ in range(m)]
MAX = 500001
if DEBUG: MAX = 101
endpoints = array_of(lambda: -1, MAX)
for s, e in segs:
endpoints[s] = max(endpoints[s], e)
cur_max = -1
for i, e in enumerate(endpoints):
if cur_max <= i:
cur_max = -1
cur_max = max(cur_max, e)
endpoints[i] = cur_max
blt = build_binary_lifting_array(endpoints)
debug_print(*blt, sep='\n')
max_depth = len(blt)
pow2 = [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024,
2048, 4096, 8192, 16384, 32768, 65536, 131072,
262144, 524288]
out = []
for s, e in queries:
cnt, depth = 0, 0
while True:
if blt[depth][s] == -1:
if depth == 0:
if s < e: cnt = -1
break
else:
s = blt[depth-1][s]
depth = 0
elif blt[depth][s] == e:
cnt += pow2[depth]
break
elif blt[depth][s] > e:
if depth == 0:
cnt += 1
break
else:
s = blt[depth-1][s]
depth = 0
else:
cnt += pow2[depth]
if depth == max_depth-1:
s = blt[depth][s]
depth = 0
else:
depth += 1
out.append(str(cnt))
print('\n'.join(out))
main()
|
1559745300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["48\n42\n8000000000"]
|
9802646ecc8890bb046d5ec1a4262d70
|
NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be $$$17 + 17$$$) and remaining integers to the second friend (his happiness will be $$$13 + 1$$$).In the second test case, Lee should give $$$\{10, 10, 11\}$$$ to the first friend and to the second friend, so the total happiness will be equal to $$$(11 + 10) + (11 + 10)$$$In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends.
|
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $$$n$$$ integers, now it's time to distribute them between his friends rationally...Lee has $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in his backpack and he has $$$k$$$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $$$i$$$-th friend will get exactly $$$w_i$$$ integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.
|
For each test case, print a single integerΒ β the maximum sum of happiness Lee can achieve.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Next $$$3t$$$ lines contain test casesΒ β one per three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$)Β β the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)Β β the integers Lee has. The third line contains $$$k$$$ integers $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$)Β β the number of integers Lee wants to give to each friend. It's guaranteed that the sum of $$$n$$$ over test cases is less than or equal to $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_005.jsonl
|
ada7a3a332735f0da833756f037141bf
|
256 megabytes
|
["3\n4 2\n1 13 7 17\n1 3\n6 2\n10 10 10 10 11 11\n3 3\n4 4\n1000000000 1000000000 1000000000 1000000000\n1 1 1 1"]
|
PASSED
|
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
a = list(map(int, input().split()))
w = list(map(int, input().split()))
a.sort(reverse = True)
w.sort()
ii = k
l, r = 0, n - 1
ans = 0
for i in range(k):
if w[i] == 1:
ans += a[l] * 2
l += 1
else:
ii = i
break
for i in range(k-1, ii-1, -1):
ans += a[l] + a[r]
l += 1
r -= (w[i] - 1)
print(ans)
|
1592921100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0\n\n2\n2 3 \n1\n1 \n2\n3 4 \n2\n3 4 \n-1"]
|
a5f496c5cfe471049eddb3a35d0c2d98
| null |
You are given a table $$$a$$$ of size $$$2 \times n$$$ (i.e. two rows and $$$n$$$ columns) consisting of integers from $$$1$$$ to $$$n$$$.In one move, you can choose some column $$$j$$$ ($$$1 \le j \le n$$$) and swap values $$$a_{1, j}$$$ and $$$a_{2, j}$$$ in it. Each column can be chosen no more than once.Your task is to find the minimum number of moves required to obtain permutations of size $$$n$$$ in both first and second rows of the table or determine if it is impossible to do that.You have to answer $$$t$$$ independent test cases.Recall that the permutation of size $$$n$$$ is such an array of size $$$n$$$ that contains each integer from $$$1$$$ to $$$n$$$ exactly once (the order of elements doesn't matter).
|
For each test case print the answer: -1 if it is impossible to obtain permutation of size $$$n$$$ in both first and the second rows of the table, or one integer $$$k$$$ in the first line, where $$$k$$$ is the minimum number of moves required to obtain permutations in both rows, and $$$k$$$ distinct integers $$$pos_1, pos_2, \dots, pos_k$$$ in the second line ($$$1 \le pos_i \le n$$$) in any order β indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of columns in the table. The second line of the test case contains $$$n$$$ integers $$$a_{1, 1}, a_{1, 2}, \dots, a_{1, n}$$$ ($$$1 \le a_{1, i} \le n$$$), where $$$a_{1, i}$$$ is the $$$i$$$-th element of the first row of the table. The third line of the test case contains $$$n$$$ integers $$$a_{2, 1}, a_{2, 2}, \dots, a_{2, n}$$$ ($$$1 \le a_{2, i} \le n$$$), where $$$a_{2, i}$$$ is the $$$i$$$-th element of the second row of the table. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_050.jsonl
|
c16d185c19467f10b90d1549512f00a5
|
256 megabytes
|
["6\n4\n1 2 3 4\n2 3 1 4\n5\n5 3 5 1 4\n1 2 3 2 4\n3\n1 2 1\n3 3 2\n4\n1 2 2 1\n3 4 3 4\n4\n4 3 1 4\n3 2 2 1\n3\n1 1 2\n3 2 2"]
|
PASSED
|
import sys
def input():
return sys.stdin.readline().strip()
def solve():
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
pos = [[] for i in range(n+1)]
for i in range(n):
pos[a[i]].extend((i,0))
pos[b[i]].extend((i,1))
if len(pos[a[i]]) > 4 \
or len(pos[b[i]]) > 4:
print(-1)
return
was = [False]*(n+1)
res = []
for i in range(1, n):
if not was[i]:
x = i
p = pos[i][0]
if pos[i][1] == 1:
one, two = [p], []
else:
one, two = [], [p]
first = p
while True:
was[x] = True
if pos[x][0] == p:
p = pos[x][2]
if p == first:
break
r = pos[x][3]
else:
p = pos[x][0]
if p == first:
break
r = pos[x][1]
if r == 0:
one.append(p)
x = b[p]
else:
two.append(p)
x = a[p]
if len(one) > len(two):
one = two
res.extend(one)
'''for i in res:
a[i], b[i] = b[i], a[i]
if len(set(a)) != n:
print(-1)
return'''
print(len(res))
print(' '.join([str(i+1) for i in res]))
for i in range(int(input())):
solve()
|
1594996500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
8 seconds
|
["6", "10", "0", "25"]
|
256409988d0132de2144e423eaa8bf34
|
NoteIn the first sample, all substrings of $$$s$$$ are awesome.In the second sample, we have the following awesome substrings of $$$s$$$: 1 ($$$2$$$ times), 01 ($$$2$$$ times), 10 ($$$2$$$ times), 010 ($$$2$$$ times), 1010, 0101In the third sample, no substring is awesome.
|
Let's call a binary string $$$s$$$ awesome, if it has at least $$$1$$$ symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.You are given a binary string $$$s$$$. Count the number of its awesome substrings.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
Output a single numberΒ β the number of awesome substrings of $$$s$$$.
|
The first line contains the string $$$s$$$ ($$$1 \leq |s|\le 200\,000$$$) consisting only of zeros and ones.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,600 |
train_014.jsonl
|
eac131a4fd384f0cb10eecee5cd8d993
|
512 megabytes
|
["111", "01010", "0000", "1111100000"]
|
PASSED
|
def add(dic, k ,v):
if not k in dic:
dic[k] = v
else:
dic[k] += v
s = map(int,raw_input())
n = len(s)
psum = [0]*(1+n)
for i in range(n):
psum[i+1] = psum[i] + s[i]
K = 350
dic = [0]*((n+1)*(K+1))
ans = 0
for j in range(1,min(n+1,K+1)):
tmp = []
for i in range(n+1):
v = j*psum[i]-i+n
tmp.append(v)
dic[v] += 1
for v in tmp:
ans += dic[v]*(dic[v]-1)/2
dic[v] = 0
ans1 = ans
pos = [i for i in range(n) if s[i]]
if len(pos) == 0:
print 0
exit()
p,l1,lastp = 0,len(pos),max(pos)
for i in range(n):
cnt = 0
if i > lastp:
break
for j in range(p,l1):
v = pos[j]
if v < i :
p += 1
continue
else:
cnt += 1
if cnt > 1:
if (cnt-1)*K+i> n:
break
start = max((pos[j-1]-i+1+cnt-2)/(cnt-1)-1,K)
diff = max((v-i)/(cnt-1)-start,0)
ans += diff
start = max((lastp-i+1+cnt-1)/(cnt)-1,K)
diff = max(min((n-i)/(cnt)-start,n-lastp),0)
ans += diff
print ans
|
1577628300
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
1 second
|
["<", "=", ">"]
|
7c0a288a2777894bdfd75cb9703346e9
|
NoteIn the first example first number equals to , while second number is approximately 1.6180339882β+β1.618033988β+β1βββ5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is βββ2.618.
|
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2β=βqβ+β1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.
|
Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.
|
Input consists of two lines β one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_049.jsonl
|
c215083cb49a3201466d305036461618
|
256 megabytes
|
["1000\n111", "00100\n11", "110\n101"]
|
PASSED
|
from itertools import dropwhile, chain
def main():
zeroes = lambda a: not a
a, b = [list(chain([0, 0], dropwhile(zeroes, map(int, input()))))
for _ in range(2)]
def tofib(l):
i = 0
while i < len(l) - 1:
if l[i] > 0 and l[i + 1] > 0:
l[i] -= 1
l[i + 1] -= 1
l[i - 1] += 1
i -= 3
i += 1
return l
a = list(dropwhile(zeroes, tofib(a)))
b = list(dropwhile(zeroes, tofib(b)))
if len(a) < len(b):
print('<')
return
if len(a) > len(b):
print('>')
return
for i in range(len(a)):
if a[i] < b[i]:
print('<')
return
if a[i] > b[i]:
print('>')
return
print('=')
if __name__ == '__main__':
main()
|
1407690000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES"]
|
d8a5578de51d6585d434516da6222204
|
NoteOn the picture below, the two polygons are well-connected, as the edges of the vertical polygon cross the area of the horizontal one exactly once in one direction (for example, from above to below), and zero times in the other (in this case, from below to above). Note that the polygons do not have to be parallel to any of the xy-,xz-,yz- planes in general.
|
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1stβ―vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point β just like when two links of a chain are connected. The polygons' edges do not intersect or overlap. To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since heβs busy playing with his dog, Zwei, heβd like you to figure it out for him. He promised you some sweets if you help him!
|
Your output should contain only one line, with the words "YES" or "NO", depending on whether the two given polygons are well-connected.
|
The first line of input contains an integer n (3ββ€βnββ€β100β000), which denotes the number of edges of the first polygon. The next N lines each contain the integers x, y and z (β-β1β000β000ββ€βx,βy,βzββ€β1β000β000)Β β coordinates of the vertices, in the manner mentioned above. The next line contains an integer m (3ββ€βmββ€β100β000) , denoting the number of edges of the second polygon, followed by m lines containing the coordinates of the second polygonβs vertices. It is guaranteed that both polygons are simple (no self-intersections), and in general that the obtained polygonal lines do not intersect each other. Also, you can assume that no 3 consecutive points of a polygon lie on the same line.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,800 |
train_006.jsonl
|
f53ddde251732f334ce1b246b608a19b
|
256 megabytes
|
["4\n0 0 0\n2 0 0\n2 2 0\n0 2 0\n4\n1 1 -1\n1 1 1\n1 3 1\n1 3 -1"]
|
PASSED
|
from math import gcd, sqrt
from functools import reduce
import sys
input = sys.stdin.readline
EPS = 0.000000001
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def GCD(args):
return reduce(gcd, args)
def plane_value(plane, point):
A, B, C, D = plane
x, y, z = point
return A*x + B*y + C*z + D
def plane(p1, p2, p3):
x1, y1, z1 = p1
x2, y2, z2 = p2
x3, y3, z3 = p3
a1, b1, c1 = x2 - x1, y2 - y1, z2 - z1
a2, b2, c2 = x3 - x1, y3 - y1, z3 - z1
a, b, c = b1 * c2 - b2 * c1, a2 * c1 - a1 * c2, a1 * b2 - b1 * a2
d = (- a * x1 - b * y1 - c * z1)
g = GCD([a,b,c,d])
return a//g, b//g, c//g, d//g
def cross(a, b):
return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])
def intersection_of_two_planes(p1, p2):
A1, B1, C1, D1 = p1
A2, B2, C2, D2 = p2
crossprod = cross([A1,B1,C1],[A2,B2,C2])
if (A1*B2-A2*B1) != 0:
x = ((B1*D2-B2*D1)/(A1*B2-A2*B1), crossprod[0])
y = ((A2*D1-A1*D2)/(A1*B2-A2*B1), crossprod[1])
z = (0,crossprod[2])
elif (B1*C2-B2*C1) != 0:
x = (0,crossprod[0])
y = ((C1*D2-C2*D1)/(B1*C2-B2*C1), crossprod[1])
z = ((B2*D1-B1*D2)/(B1*C2-B2*C1), crossprod[2])
elif (A1*C2-A2*C1) != 0:
x = ((C1*D2-C2*D1)/(A1*C2-A2*C1), crossprod[0])
y = (0,crossprod[1])
z = ((A2*D1-A1*D2)/(A1*C2-A2*C1), crossprod[2])
else:
return None
return x, y, z
def line_parametric(p1, p2):
x1, y1, z1 = p1
x2, y2, z2 = p2
return (x2,x1-x2), (y2,y1-y2), (z2,z1-z2)
def solve_2_by_2(row1, row2):
a1, b1, c1 = row1
a2, b2, c2 = row2
if a1*b2-b1*a2:
return (c1*b2-b1*c2)/(a1*b2-b1*a2), (a1*c2-c1*a2)/(a1*b2-b1*a2)
else:
return None
def sgn(x):
return 1 if x>0 else 0 if x==0 else -1
def lines_intersection_point(i1, i2):
x1, y1, z1 = i1
x2, y2, z2 = i2
try:
t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [y1[1], -y2[1], y2[0]-y1[0]])
if abs(t1*z1[1] - t2*z2[1] - z2[0] + z1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
try:
t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
if abs(t1*y1[1] - t2*y2[1] - y2[0] + y1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
try:
t1, t2 = solve_2_by_2([y1[1], -y2[1], y2[0]-y1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
if abs(t1*x1[1] - t2*x2[1] - x2[0] + x1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
return None
def foo(points):
down_cnt, up_cnt = 0, 0
first = points[0]
other = 1-first
down = True
intrusion = True
for p in points[1:]:
if p==first:
intrusion = not intrusion
else:
if intrusion:
if down:
down_cnt+=1
else:
up_cnt+=1
down = not down
return down_cnt==up_cnt
def populate(plane, poly, tag):
res = []
prev = plane_value(plane,poly[-1])
prev_serious = plane_value(plane,poly[-2]) if not prev else prev
p_prev = poly[-1]
for i in range(len(poly)+1):
p = poly[i%len(poly)]
curr = plane_value(plane,p)
if sgn(curr) == -sgn(prev_serious):
intersector = line_parametric(p_prev,p)
point, t = lines_intersection_point(intersector,intersectee)
res.append((t,tag))
prev_serious = curr
if sgn(curr):
prev_serious = curr
prev, p_prev = curr, p
return res
x_poly, y_poly = [], []
for _ in range(inp()):
x_poly.append(inlt())
for _ in range(inp()):
y_poly.append(inlt())
x_plane = plane(*x_poly[:3])
y_plane = plane(*y_poly[:3])
intersectee = intersection_of_two_planes(x_plane,y_plane)
if intersectee:
points = sorted(set(populate(y_plane,x_poly,0) + populate(x_plane,y_poly,1)))
points = [i[1] for i in points]
print('NO' if foo(points) else 'YES')
else:
print('NO')
|
1473584400
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "42"]
|
bd6f4859e3c3ce19b8e89c431f2e65fb
|
NoteIn the first example Yura needs to reach $$$(5, 5)$$$ from $$$(1, 1)$$$. He can do that in $$$5$$$ minutes by first using the second instant-movement location (because its $$$y$$$ coordinate is equal to Yura's $$$y$$$ coordinate), and then walking $$$(4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5)$$$.
|
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.Let's represent the city as an area of $$$n \times n$$$ square blocks. Yura needs to move from the block with coordinates $$$(s_x,s_y)$$$ to the block with coordinates $$$(f_x,f_y)$$$. In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are $$$m$$$ instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate $$$x$$$ or with the same coordinate $$$y$$$ as the location.Help Yura to find the smallest time needed to get home.
|
In the only line print the minimum time required to get home.
|
The first line contains two integers $$$n$$$ and $$$m$$$Β β the size of the city and the number of instant-movement locations ($$$1 \le n \le 10^9$$$, $$$0 \le m \le 10^5$$$). The next line contains four integers $$$s_x$$$ $$$s_y$$$ $$$f_x$$$ $$$f_y$$$Β β the coordinates of Yura's initial position and the coordinates of his home ($$$ 1 \le s_x, s_y, f_x, f_y \le n$$$). Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ $$$y_i$$$Β β coordinates of the $$$i$$$-th instant-movement location ($$$1 \le x_i, y_i \le n$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_009.jsonl
|
79447fe19beac92ac0d84869bcf86286
|
256 megabytes
|
["5 3\n1 1 5 5\n1 2\n4 1\n3 3", "84 5\n67 59 41 2\n39 56\n7 2\n15 3\n74 18\n22 7"]
|
PASSED
|
import heapq
def main():
n, m = map(int, input().split())
sx, sy, fx, fy = map(int, input().split())
sub = [0]*(m+2)
sub[0] = (sx,sy)
dx = []
dy = []
for i in range(m):
x, y = map(int, input().split())
dx.append((x, i+1))
dy.append((y, i+1))
sub[i+1] = (x, y)
dx.append((sx,0))
dy.append((sy,0))
dx.sort()
dy.sort()
G = [[] for i in range(m+2)]
d = [2*10**9]*(m+2)
for i in range(m):
px, pindex = dx[i]
nx, nindex = dx[i+1]
G[pindex].append((nx-px, nindex))
G[nindex].append((nx-px, pindex))
for i in range(m):
py, pindex = dy[i]
ny, nindex = dy[i+1]
G[pindex].append((ny-py, nindex))
G[nindex].append((ny-py, pindex))
for i in range(m+1):
x, y = sub[i]
min_cost = abs(y-fy)+abs(x-fx)
G[m+1].append((min_cost, i))
G[i].append((min_cost, m+1))
que = []
heapq.heapify(que)
d[0] = 0
heapq.heappush(que, (0, 0))
while que:
cost, v = heapq.heappop(que)
if d[v] < cost:
continue
for cost, node in G[v]:
if d[node] > d[v] + cost:
d[node] = d[v] + cost
heapq.heappush(que, (d[node], node))
ans = d[m+1]
print(ans)
return
if __name__ == "__main__":
main()
|
1601827500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"]
|
32096eff277f19d227bccca1b6afc458
|
NoteBelow you can see trees printed to the output in the first sample and the third sample.
|
A tree is a connected undirected graph consisting of n vertices and nββ-ββ1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the treeΒ β he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable treeΒ β in this case print "-1".
|
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print nβ-β1 lines, each with two space-separated integersΒ β indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
|
The first line contains three integers n, d and h (2ββ€βnββ€β100β000,β1ββ€βhββ€βdββ€βnβ-β1)Β β the number of vertices, diameter, and height after rooting in vertex 1, respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_019.jsonl
|
c325132c06f85f853cb09ef544992323
|
256 megabytes
|
["5 3 2", "8 5 2", "8 4 2"]
|
PASSED
|
def solve(n,d,h) :
if n<d+1 :
return False
if d>2*h :
return False
if d-h<0 :
return False
if d==1 and n>=3 :
return False
cnt=1
h0=d-h
for i in range(h) :
print(cnt,cnt+1)
cnt+=1
if h0 :
print(1,cnt+1)
cnt+=1
for i in range(h0-1) :
print(cnt,cnt+1)
cnt+=1
if h0 :
for i in range(n-d-1) :
print(1,cnt+1)
cnt+=1
else :
for i in range(n-d-1) :
print(2,cnt+1)
cnt+=1
return True
n,d,h=[int(i) for i in input().split()]
if not solve(n,d,h) :
print(-1)
|
1459182900
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["0.500000000000000", "0.833333333333333"]
|
ad4bdd6cee78cbcd357e048cd342a42b
| null |
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law).Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are N random variables, the i-th of which can take any integer value from some segment [Li;Ri] (all numbers from this segment are equiprobable). It means that the value of the i-th quantity can be equal to any integer number from a given interval [Li;Ri] with probability 1β/β(Riβ-βLiβ+β1).The Hedgehog wants to know the probability of the event that the first digits of at least K% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD β most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least K per cent of those N values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.
|
Print the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10β-β9.
|
The first line contains number N which is the number of random variables (1ββ€βNββ€β1000). Then follow N lines containing pairs of numbers Li,βRi, each of whom is a description of a random variable. It is guaranteed that 1ββ€βLiββ€βRiββ€β1018. The last line contains an integer K (0ββ€βKββ€β100). All the numbers in the input file are integers. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_080.jsonl
|
f6959f7bf197695ef58db5865880688a
|
256 megabytes
|
["1\n1 2\n50", "2\n1 2\n9 11\n50"]
|
PASSED
|
import math
def get_count(x):
if x == 0:
return 0
y = 10 ** (len(str(x)) - 1)
d = x // y
if d == 1:
count = x - y + 1
else:
count = y
#print(x, math.log10(x), int(math.log10(x)), y, d, count)
while y > 1:
y //= 10
count += y
#print('get_count(%d) -> %d' % (x, count))
return count
n = int(input())
total = [ 1.0 ]
for i in range(n):
low, high = map(int, input().split())
count = get_count(high) - get_count(low - 1)
p = count / (high - low + 1)
new_total = [ 0.0 for i in range(len(total) + 1) ]
for i, q in enumerate(total):
new_total[i] += (1 - p) * q
new_total[i + 1] += p * q
total = new_total
k = int(input())
result = 1.0
for i in range(math.ceil(n * k / 100)):
result -= total[i]
#print(total)
print(result)
|
1294733700
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second
|
["4", "4"]
|
d03ad531630cbecc43f8da53b02d842e
|
NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.
|
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (nβ+β1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (iβ>β0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be kβ+β1). When the player have made such a move, its energy increases by hkβ-βhkβ+β1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
|
Print a single number representing the minimum number of dollars paid by Caisa.
|
The first line contains integer n (1ββ€βnββ€β105). The next line contains n integers h1, h2,β..., hn (1βββ€ββhiβββ€ββ105) representing the heights of the pylons.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,100 |
train_019.jsonl
|
bded34133e5ceca245328945d41c647c
|
256 megabytes
|
["5\n3 4 3 2 4", "3\n4 4 4"]
|
PASSED
|
import math
import sys
#imgur.com/Pkt7iIf.png
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
n = ii()
print(max(li()))
|
1409383800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["7\n9\n6"]
|
07eecfe948aa78623586b5e30e84e415
| null |
You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur < 0 ok = false break if ok breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.
|
For each test case print one integer β the value of the $$$res$$$ after the process ends.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_028.jsonl
|
75425791a6d2f4e6319a22315e7f18ec
|
256 megabytes
|
["3\n--+-\n---\n++--+-"]
|
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
# 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)
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect
input = lambda: sys.stdin.readline().rstrip("\r\n")
read = lambda: list(map(int, input().strip().split(" ")))
def func(x):
t = 0
for i in arr:
if i <= x:
t += i
return(t)
def solve():
for _ in range(int(input())):
s = input();
arr = [[-1, 1][i=="+"] for i in s]
for i in range(1, len(s)):arr[i] += arr[i-1]
ans = 0; sett = set()
for i in range(len(s)):
if arr[i] < 0 and arr[i] not in sett:
ans += i+1
sett.add(arr[i])
# print(arr, sett)
# if ans:
print(ans+len(s))
# else:
# print(len(s))
if __name__ == "__main__":
solve()
|
1593095700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["8\n5\n11880\n351025663"]
|
5f44c5eed653c150476b7fc6fa5d373b
|
NoteIn the first test case, the following $$$8$$$ arrays satisfy the conditions from the statement: $$$[1,2,1]$$$; $$$[1,2,2]$$$; $$$[1,3,1]$$$; $$$[1,3,2]$$$; $$$[1,3,3]$$$; $$$[2,3,1]$$$; $$$[2,3,2]$$$; $$$[2,3,3]$$$. In the second test case, the following $$$5$$$ arrays satisfy the conditions from the statement: $$$[1,1,1,1]$$$; $$$[2,1,1,1]$$$; $$$[2,2,1,1]$$$; $$$[2,2,2,1]$$$; $$$[2,2,2,2]$$$.
|
The position of the leftmost maximum on the segment $$$[l; r]$$$ of array $$$x = [x_1, x_2, \ldots, x_n]$$$ is the smallest integer $$$i$$$ such that $$$l \le i \le r$$$ and $$$x_i = \max(x_l, x_{l+1}, \ldots, x_r)$$$.You are given an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of length $$$n$$$. Find the number of integer arrays $$$b = [b_1, b_2, \ldots, b_n]$$$ of length $$$n$$$ that satisfy the following conditions: $$$1 \le b_i \le m$$$ for all $$$1 \le i \le n$$$; for all pairs of integers $$$1 \le l \le r \le n$$$, the position of the leftmost maximum on the segment $$$[l; r]$$$ of the array $$$b$$$ is equal to the position of the leftmost maximum on the segment $$$[l; r]$$$ of the array $$$a$$$. Since the answer might be very large, print its remainder modulo $$$10^9+7$$$.
|
For each test case print one integerΒ β the number of arrays $$$b$$$ that satisfy the conditions from the statement, modulo $$$10^9+7$$$.
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 2 \cdot 10^5$$$, $$$n \cdot m \le 10^6$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le m$$$)Β β the array $$$a$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases doesn't exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_083.jsonl
|
df6622606291bb3cdc8dc4e9889fdf3a
|
512 megabytes
|
["4\n\n3 3\n\n1 3 2\n\n4 2\n\n2 2 2 2\n\n6 9\n\n6 9 6 9 6 9\n\n9 100\n\n10 40 20 20 100 60 80 60 60"]
|
PASSED
|
import sys
def solve():
inp = sys.stdin.readline
n, m = map(int, inp().split())
g = [[] for i in range(n + 1)]
ginv = [[] for i in range(n + 1)]
idx = 0
st = []
for v in map(int, inp().split()):
while st:
pv, pidx = st[-1]
if pv < v:
st.pop()
g[idx].append(pidx)
ginv[pidx].append(idx)
else:
break
st.append((v, idx))
idx += 1
while st:
pv, pidx = st[-1]
st.pop()
g[n].append(pidx)
ginv[pidx].append(n)
degree = [0] * (n + 1)
st = []
for i in range(n + 1):
degree[i] = len(g[i])
if degree[i] == 0:
st.append(i)
dp = [None] * (n + 1)
MOD = int(1e9 + 7)
while st:
x = st[-1]
st.pop()
if g[x]:
vec = g[x]
d = dp[vec[0]]
for i in range(1, m + 2):
d[i] = (d[i] + d[i - 1]) % MOD
for j in range(1, len(vec)):
dd = dp[vec[j]]
nd = [0] * (m + 2)
for i in range(1, m + 2):
nd[i] = (dd[i] * d[i] + nd[i - 1]) % MOD
d = nd
d.insert(0, 0)
d.pop()
else:
d = [1] * (m + 2)
d[0] = 0
dp[x] = d
for v in ginv[x]:
degree[v] -= 1
if degree[v] == 0:
st.append(v)
print(dp[n][m + 1])
def main():
for i in range(int(sys.stdin.readline())):
solve()
if __name__ == '__main__':
main()
|
1668263700
|
[
"math",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
0,
1
] |
|
1 second
|
["2 5 11 18 30 43 62 83 121", "7"]
|
af8ac55aa2594350226653c8d5ff47e4
|
NoteLet's analyze the answer for $$$k = 5$$$ in the first example. Here is one of the possible ways to eat $$$5$$$ sweets that minimize total sugar penalty: Day $$$1$$$: sweets $$$1$$$ and $$$4$$$ Day $$$2$$$: sweets $$$5$$$ and $$$3$$$ Day $$$3$$$ : sweet $$$6$$$ Total penalty is $$$1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$$$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $$$5$$$ sweets, hence $$$x_5 = 30$$$.
|
Tsumugi brought $$$n$$$ delicious sweets to the Light Music Club. They are numbered from $$$1$$$ to $$$n$$$, where the $$$i$$$-th sweet has a sugar concentration described by an integer $$$a_i$$$.Yui loves sweets, but she can eat at most $$$m$$$ sweets each day for health reasons.Days are $$$1$$$-indexed (numbered $$$1, 2, 3, \ldots$$$). Eating the sweet $$$i$$$ at the $$$d$$$-th day will cause a sugar penalty of $$$(d \cdot a_i)$$$, as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly $$$k$$$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of $$$k$$$ between $$$1$$$ and $$$n$$$.
|
You have to output $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ on a single line, separed by spaces, where $$$x_k$$$ is the minimum total sugar penalty Yui can get if she eats exactly $$$k$$$ sweets.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 200\ 000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\ 000$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_007.jsonl
|
e571db87ee73c7a7563865e8b493ed29
|
256 megabytes
|
["9 2\n6 19 3 4 4 2 6 7 8", "1 1\n7"]
|
PASSED
|
t=lambda:map(int,input().split())
n,m=t()
a=sorted(t())
x,s=[0]*n,0
for i in range(n):s+=a[i];x[i]=s if i<m else s+x[i-m]
print(*x)
|
1573914900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\n1 2 1", "YES\n2 3 2 1 2"]
|
f097cc7057bb9a6b9fc1d2a11ee99835
| null |
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$. Each of its vertices also has an integer $$$a_i$$$ written on it. For each vertex $$$i$$$, Evlampiy calculated $$$c_i$$$Β β the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. Illustration for the second example, the first integer is $$$a_i$$$ and the integer in parentheses is $$$c_i$$$After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $$$c_i$$$, but he completely forgot which integers $$$a_i$$$ were written on the vertices.Help him to restore initial integers!
|
If a solution exists, in the first line print "YES", and in the second line output $$$n$$$ integers $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $$$a_i$$$ are between $$$1$$$ and $$$10^9$$$. If there are no solutions, print "NO".
|
The first line contains an integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$ β the number of vertices in the tree. The next $$$n$$$ lines contain descriptions of vertices: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), where $$$p_i$$$ is the parent of vertex $$$i$$$ or $$$0$$$ if vertex $$$i$$$ is root, and $$$c_i$$$ is the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. It is guaranteed that the values of $$$p_i$$$ describe a rooted tree with $$$n$$$ vertices.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_005.jsonl
|
e90e7a54127337b2cce02c51de519a8e
|
256 megabytes
|
["3\n2 0\n0 2\n2 0", "5\n0 1\n1 3\n2 1\n3 0\n2 0"]
|
PASSED
|
# https://codeforces.com/contest/1287/problem/D
def push(g, u, v):
if u not in g:
g[u] = []
g[u].append(v)
def build():
S = [root]
i = 0
order = {}
while i < len(S):
u = S[i]
if u in g:
for v in g[u]:
S.append(v)
i+=1
for u in S[::-1]:
order[u] = []
flg=False
if u not in g:
if cnt[u]==0:
order[u].append(u)
flg=True
else:
return False, root, order
else:
cur = 0
for v in g[u]:
for x in order[v]:
if cur==cnt[u]:
flg=True
order[u].append(u)
cur+=1
order[u].append(x)
cur+=1
if flg == False:
if cnt[u] > len(order[u]):
return False, root, order
else:
order[u].append(u)
return True, root, order
n = int(input())
g = {}
cnt = {}
for i in range(1, n+1):
p, c = map(int, input().split())
cnt[i] = c
if p==0:
root = i
else:
push(g, p, i)
flg, root, order = build()
if flg==False:
print('NO')
else:
ans = [-1] * n
for val, u in zip(list(range(n)), order[root]):
ans[u-1] = val + 1
print('YES')
print(' '.join([str(x) for x in ans]))
#5
#0 1
#1 3
#2 1
#3 0
#2 0
#3
#2 0
#0 2
#2 0
|
1578233100
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
4 seconds
|
["0\n1 2 3 4 5\n2\n2 2\n1\n3 11\n3\n3 1 1 1"]
|
4d0b2fe22b4870b15d63e9fb778bcb7b
|
NoteIn the first test case, the graph is already connected.In the second test case, we can increment $$$0$$$ twice and end up with the array $$$[2,2]$$$. Since $$$2 \& 2 = 2 > 0$$$, the graph is connected. It can be shown that one operation is not enough.In the third test case, we can decrement $$$12$$$ once and we end up with an array $$$[3,11]$$$. $$$3 \& 11 = 3 > 0$$$ hence the graph is connected. One operation has to be done since the graph is not connected at the beginning.
|
Bit Lightyear, to the ANDfinity and beyond!After graduating from computer sciences, Vlad has been awarded an array $$$a_1,a_2,\ldots,a_n$$$ of $$$n$$$ non-negative integers. As it is natural, he wanted to construct a graph consisting of $$$n$$$ vertices, numbered $$$1, 2,\ldots, n$$$. He decided to add an edge between $$$i$$$ and $$$j$$$ if and only if $$$a_i \& a_j > 0$$$, where $$$\&$$$ denotes the bitwise AND operation.Vlad also wants the graph to be connected, which might not be the case initially. In order to satisfy that, he can do the following two types of operations on the array: Choose some element $$$a_i$$$ and increment it by $$$1$$$. Choose some element $$$a_i$$$ and decrement it by $$$1$$$ (possible only if $$$a_i > 0$$$). It can be proven that there exists a finite sequence of operations such that the graph will be connected. So, can you please help Vlad find the minimum possible number of operations to do that and also provide the way how to do that?
|
For each test case, print a single integer $$$m$$$ in the first lineΒ β the minimum number of operations. In the second line print the array after a valid sequence of operations that have been done such that the graph from the task becomes connected. If there are multiple solutions, output any.
|
There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of test cases. This is followed by the test cases description. The first line of each test case contains an integer $$$n$$$ ($$$2\leq n \leq 2000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i < 2^{30}$$$)Β β the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_096.jsonl
|
e8cf0e97abc4c680abd130f3f84b3031
|
256 megabytes
|
["4\n5\n1 2 3 4 5\n2\n0 2\n2\n3 12\n4\n3 0 0 0"]
|
PASSED
|
from collections import deque
def connected(n, arr):
g = [[] for i in range(n)]
for k in range(30):
ind = []
for i, a in enumerate(arr):
if a&(1<<k):
ind.append(i)
if len(ind) > 1:
a = ind.pop()
for i in ind:
g[i].append(a)
g[a].append(i)
v = [0]*n
v[0] = 1
q = deque()
q.append(0)
while q:
x = q.popleft()
for y in g[x]:
if v[y] == 0:
v[y] = 1
q.append(y)
return 0 not in v
def solve():
n = int(input())
arr = list(map(int, input().split()))
ans = 0
for i, a in enumerate(arr):
if a == 0:
ans += 1
arr[i] = 1
if connected(n, arr):
print(ans)
print(*arr)
return
for i in range(n):
for j in (-1, 1):
arr1 = arr[:]
arr1[i] += j
if connected(n, arr1):
print(ans+1)
print(*arr1)
return
m = max(a&-a for a in arr)
L = []
for i, a in enumerate(arr):
if a&-a == m:
L.append(i)
arr[L[0]] -= 1
arr[L[1]] += 1
print(ans+2)
print(*arr)
import sys
input = lambda: sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
solve()
|
1654878900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["3", "4"]
|
18cf79b50d0a389e6c3afd5d2f6bd9ed
|
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
|
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
|
Print a single integerΒ β the number of citizens the bandit will catch if both sides act optimally.
|
The first line contains a single integer $$$n$$$Β β the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i < i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$Β β the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_004.jsonl
|
4ed9a34f0cfd404a03c54d6e1c00ade1
|
256 megabytes
|
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
|
PASSED
|
n = int(input())
p = list(map(int, input().split()))
a = list(map(int, input().split()))
tree = {}
for i, pp in enumerate(p, start=2):
tree.setdefault(pp, []).append(i)
cache = {}
for s in range(n, 0, -1):
children = tree.get(s, [])
if len(children) == 0:
cache[s] = (a[s - 1], a[s - 1], 1)
continue
ch_p = [cache[c] for c in children]
ch_max = max(pp[0] for pp in ch_p)
ch_sum = sum(pp[1] for pp in ch_p)
ch_l = sum(pp[2] for pp in ch_p)
sm = ch_sum + a[s - 1]
m = sm // ch_l
if sm % ch_l != 0:
m += 1
cache[s] = (max(ch_max, m), sm, ch_l)
print(cache[1][0])
|
1603548300
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["3", "4"]
|
1a37e42263fdd1cb62e2a18313eed989
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
Output a single line containing one integerΒ β the maximum number of times the operation can be performed on the given array.
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_109.jsonl
|
d218548d1bade7ce888cb18780fea4f5
|
256 megabytes
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
PASSED
|
# import sys, os
# if not os.environ.get("ONLINE_JUDGE"):
# sys.stdin = open('in.txt', 'r')
# sys.stdout = open('out.txt', 'w')
import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import math
n = int(input())
arr = list(map(int, input().split()))
m = max(arr)
avail = {i:False for i in range(1, m+1)}
for i in arr:
avail[i] = True
ans = 0
for i in range(1, m+1):
if not avail[i]:
g = 0
for j in range(2*i, m+1, i):
if avail[j]:
g = math.gcd(g, j)
if g == i:
ans += 1
print(ans)
|
1642257300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["10 9 3 4", "6 5 4 3 2 3 3 1 1 3 2 2 1 2 3"]
|
fe01ddb5bd5ef534a6a568adaf738151
| null |
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.For each vertex v find the sum of all dominating colours in the subtree of vertex v.
|
Print n integers β the sums of dominating colours for each vertex.
|
The first line contains integer n (1ββ€βnββ€β105) β the number of vertices in the tree. The second line contains n integers ci (1ββ€βciββ€βn), ci β the colour of the i-th vertex. Each of the next nβ-β1 lines contains two integers xj,βyj (1ββ€βxj,βyjββ€βn) β the edge of the tree. The first vertex is the root of the tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,300 |
train_004.jsonl
|
e4aa09f18c3693b7eb68dddcffdd421a
|
256 megabytes
|
["4\n1 2 3 4\n1 2\n2 3\n2 4", "15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13"]
|
PASSED
|
def main():
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
color = list(map(int, input().split()))
color.insert(0, 0)
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
que = deque()
que.append(1)
seen = [-1] * (N+1)
seen[1] = 0
par = [0] * (N+1)
child = [[] for _ in range(N+1)]
seq = []
while que:
v = que.popleft()
seq.append(v)
for u in adj[v]:
if seen[u] == -1:
seen[u] = seen[v] + 1
par[u] = v
child[v].append(u)
que.append(u)
seq.reverse()
cnt = [{color[i]: 1} for i in range(N+1)]
cnt_size = [1] * (N+1)
dom_num = [1] * (N+1)
ans = [color[i] for i in range(N+1)]
for v in seq:
big = cnt[v]
size_big = cnt_size[v]
for u in child[v]:
small = cnt[u]
size_small = cnt_size[u]
if size_big < size_small:
small, big = big, small
dom_num[v] = dom_num[u]
ans[v] = ans[u]
size_big += size_small
for c in small:
if c not in big:
big[c] = small[c]
else:
big[c] += small[c]
cnt_size[v] += small[c]
if big[c] > dom_num[v]:
dom_num[v] = big[c]
ans[v] = c
elif big[c] == dom_num[v]:
ans[v] += c
cnt_size[v] = size_big
cnt[v] = big
print(*ans[1:])
#print(child)
#print(cnt)
#print(cnt_size)
if __name__ == '__main__':
main()
|
1448636400
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["0\n0\n1\n1\n0\n0\n2"]
|
803e5ccae683b91a4cc486fbc558b330
|
NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: "001" can be achieved by flipping the first character Β β and is one of the possible ways to get a good string.For the $$$4$$$th test case: "000" can be achieved by flipping the second character Β β and is one of the possible ways to get a good string.For the $$$7$$$th test case: "000000" can be achieved by flipping the third and fourth characters Β β and is one of the possible ways to get a good string.
|
Shubham has a binary string $$$s$$$. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence Β β for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
|
For every string, output the minimum number of operations required to make it good.
|
The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$Β β the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \le |s| \le 1000)$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,400 |
train_019.jsonl
|
a0f8f3d61643e5f9d4b4bed4dbec1a66
|
256 megabytes
|
["7\n001\n100\n101\n010\n0\n1\n001100"]
|
PASSED
|
T = input()
for _ in xrange(T):
s = raw_input()
soms = [[0, 0]]
for elem in s:
zc, oc = soms[-1]
if elem == "1":
soms.append([zc, oc+1])
else:
soms.append([zc+1, oc])
#print s
#print soms
result = None
for i in xrange(len(s)+1):
lz, lo = soms[i]
if i == 0:
rz, ro = soms[-1]
elif i == len(s):
rz, ro = 0, 0
else:
rz = soms[-1][0] - soms[i][0]
ro = soms[-1][1] - soms[i][1]
cost = min(lo + rz, lz + ro)
#print i, cost, lz, lo, rz, ro
if result is None or result > cost:
result = cost
print result
|
1590935700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["2\n99\n1"]
|
1fd2619aabf4557093a59da804fd0e7b
|
NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.
|
You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.
|
For each test case print one integer β the maximum distance between two rivaling students which you can obtain.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) β the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_019.jsonl
|
acdd5dfab732a98bdf3eeff97f3b2c4d
|
256 megabytes
|
["3\n5 1 3 2\n100 33 100 1\n6 0 2 3"]
|
PASSED
|
for i in range(int(input())):
n,x,a,b=map(int,input().split())
if(((min(a,b)-1)+(n-max(a,b)))>=x):
print(max(a,b)-min(a,b)+x)
else:
print(n-1)
|
1573655700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3 abc\n2 bc\n1 c\n0 \n1 d", "18 abbcd...tw\n17 bbcdd...tw\n16 bcddd...tw\n15 cddde...tw\n14 dddea...tw\n13 ddeaa...tw\n12 deaad...tw\n11 eaadf...tw\n10 aadfortytw\n9 adfortytw\n8 dfortytw\n9 fdfortytw\n8 dfortytw\n7 fortytw\n6 ortytw\n5 rtytw\n6 urtytw\n5 rtytw\n4 tytw\n3 ytw\n2 tw\n1 w\n0 \n1 o"]
|
7d6faccc88a6839822fa0c0ec8c00251
|
NoteConsider the first example. The longest suffix is the whole string "abcdd". Choosing one pair $$$(4, 5)$$$, Lesha obtains "abc". The next longest suffix is "bcdd". Choosing one pair $$$(3, 4)$$$, we obtain "bc". The next longest suffix is "cdd". Choosing one pair $$$(2, 3)$$$, we obtain "c". The next longest suffix is "dd". Choosing one pair $$$(1, 2)$$$, we obtain "" (an empty string). The last suffix is the string "d". No pair can be chosen, so the answer is "d". In the second example, for the longest suffix "abbcdddeaaffdfouurtytwoo" choose three pairs $$$(11, 12)$$$, $$$(16, 17)$$$, $$$(23, 24)$$$ and we obtain "abbcdddeaadfortytw"
|
Some time ago Lesha found an entertaining string $$$s$$$ consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.Lesha chooses an arbitrary (possibly zero) number of pairs on positions $$$(i, i + 1)$$$ in such a way that the following conditions are satisfied: for each pair $$$(i, i + 1)$$$ the inequality $$$0 \le i < |s| - 1$$$ holds; for each pair $$$(i, i + 1)$$$ the equality $$$s_i = s_{i + 1}$$$ holds; there is no index that is contained in more than one pair. After that Lesha removes all characters on indexes contained in these pairs and the algorithm is over. Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string.
|
In $$$|s|$$$ lines print the lengths of the answers and the answers themselves, starting with the answer for the longest suffix. The output can be large, so, when some answer is longer than $$$10$$$ characters, instead print the first $$$5$$$ characters, then "...", then the last $$$2$$$ characters of the answer.
|
The only line contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) β the initial string consisting of lowercase English letters only.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,700 |
train_011.jsonl
|
00750c7d58b33d3ac03785c4a39a4ff9
|
256 megabytes
|
["abcdd", "abbcdddeaaffdfouurtytwoo"]
|
PASSED
|
s = input().strip();N = len(s)
if len(s) == 1:print(1, s[0]);exit()
X = [s[-1], s[-2]+s[-1] if s[-2]!=s[-1] else ""];Y = [1, 2 if s[-2]!=s[-1] else 0]
for i in range(N-3, -1, -1):
c = s[i];k1 = c+X[-1];ng = Y[-1]+1
if ng > 10:k1 = k1[:5] + "..." + k1[-2:]
if c == s[i+1] and k1 > X[-2]:k1 = X[-2];ng = Y[-2]
X.append(k1);Y.append(ng)
for i in range(N-1, -1, -1):print(Y[i], X[i])
|
1601827500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["YES\nNO\nYES"]
|
6639e9a289fa76e3aae6f309ab26c049
|
NoteIn the first query Alice can select substring $$$s_3 \dots s_5$$$. After that $$$s$$$ turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move.In the second query Alice can not win because she cannot even make one move.In the third query Alice can choose substring $$$s_2 \dots s_6$$$. After that $$$s$$$ turns into .XXXXX.X..X, and Bob can't make a move after that.
|
Alice and Bob play a game. Initially they have a string $$$s_1, s_2, \dots, s_n$$$, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length $$$a$$$, and Bob must select a substring of length $$$b$$$. It is guaranteed that $$$a > b$$$.For example, if $$$s =$$$ ...X.. and $$$a = 3$$$, $$$b = 2$$$, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string $$$s =$$$ ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally.You have to answer $$$q$$$ independent queries.
|
For each test case print YES if Alice can win 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 3 \cdot 10^5$$$) β the number of queries. The first line of each query contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le b < a \le 3 \cdot 10^5$$$). The second line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 3 \cdot 10^5$$$), consisting of only characters . and X. It is guaranteed that sum of all $$$|s|$$$ over all queries not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,500 |
train_003.jsonl
|
12ee1594ca82caccae9911559ccebde1
|
256 megabytes
|
["3\n3 2\nXX......XX...X\n4 2\nX...X.X..X\n5 3\n.......X..X"]
|
PASSED
|
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
q = int(input())
for _ in range(q):
a,b = map(int ,input().split(" "))
s = map(lambda x: 0 if x == "." else 1,input())
lengths = []
cnt = 0
for i in range(len(s)):
if s[i] == 0:
cnt += 1
else:
if cnt >0:
lengths.append(cnt)
cnt = 0
if cnt >0:
lengths.append(cnt)
lengths.sort()
flag = True
cnt = 0
used = 0
tod = 0
for l in lengths:
if l<b:
continue
elif a>l>=b:
flag = False
break
elif a<=l<2*b:
cnt += 1
elif l>=2*b and not used:
if l>=a:
used = 1
tod = l-a
else:
flag = False
break
else:
flag = False
break
# print flag
if not flag:
print "NO"
else:
if tod != 0:
flag = False
for i in range(tod/2+1):
s1 = i
s2 = tod-i
if s1>s2:
continue
if a>s1>=b or s1>=2*b or a>s2>=b or s2>=2*b:
continue
if (cnt+used+(2*b>s1>=a)*1+(2*b>s2>=a)*1)%2 == 1:
# print tod,cnt,used,s1,s2,(2*b>s1>=a)*1,(b>s2>=a)*1
flag = True
break
# print "tod",flag
if flag:
print "YES"
else:
print "NO"
elif (cnt+used) %2 == 0:
print "NO"
else:
print "YES"
|
1568903700
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["30021", "3036366999"]
|
5c3cec98676675355bb870d818704be6
| null |
Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer kΒ β the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).
|
Print the smalles integer n which Vasya could pass to Kate.
|
The first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1β000β000. The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes. It is guaranteed that the input data is correct, and the answer always exists.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_008.jsonl
|
f212734180961a1b67416873754493c6
|
256 megabytes
|
["003512\n021", "199966633300\n63"]
|
PASSED
|
import sys
def main():
a = sys.stdin.readline().strip()
b = sys.stdin.readline().strip()
if a == "01" or a == "10":
print("0")
return
cnt = [0] * 256
for i in map(ord, a):
cnt[i] += 1
n = sum(cnt)
l = 0
for i in range(1, 8):
if i == len(str(n - i)):
l = n - i
break;
for s in b, str(l):
for i in map(ord, s):
cnt[i] -= 1
res = ["".join([b] + [chr(k) * v for k, v in enumerate(cnt) if v > 0 ])] if b[0] > "0" else []
for i in range(ord("1"), ord("9") + 1):
if cnt[i] > 0:
cnt[i] -= 1
others = [chr(k) * v for k, v in enumerate(cnt) if v > 0]
others.append(b)
res.append("".join([chr(i)] + sorted(others)))
break
print(min(res))
if __name__ == "__main__":
main()
|
1462464300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["524848", "121", "-1"]
|
206eb67987088843ef42923b0c3939d4
| null |
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.
|
In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.
|
The first line contains three integers: a,βb,βn (1ββ€βa,βb,βnββ€β105).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_006.jsonl
|
a2090b0a897a64a03cfff88931c197ba
|
256 megabytes
|
["5 4 5", "12 11 1", "260 150 10"]
|
PASSED
|
'''
260A
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.
Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.
Input
The first line contains three integers: a,b, n
Output
In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.
'''
values = (input(""))
values = values.split(' ')
a = int(values[0])
b = int(values[1])
n = int(values[2])
#print(a,b,n)
''' My first answer
while n>0:
digit = 0
while digit<10:
if (a*10+digit)%b == 0:
a=(a*10+digit)
break
else:
digit+=1
if digit == 10 and a%b != 0:
a=-1
break
else:
n=n-1
print(a)
'''
''' effective answer in terms of execution time '''
a=a*10+9
if (a%b)<10:
print (str(a-a%b)+"0"*(n-1))
else:
print (-1)
|
1356622500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n-1\n3"]
|
c2f3d09674190f90c940f134c3e22afe
|
NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is $$$2$$$. The substring "a" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is $$$3$$$.
|
Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions: Length of the substring is at least $$$2$$$ 'a' occurs strictly more times in this substring than 'b' 'a' occurs strictly more times in this substring than 'c' Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^{5})$$$ Β β the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 10^{6})$$$ Β β the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_097.jsonl
|
e850887386580646915532098e6222ed
|
256 megabytes
|
["3\n2\naa\n5\ncbabb\n8\ncacabccc"]
|
PASSED
|
t = int(input())
for case in range(t):
n = int(input())
s = input()
ans = -1
tests = ['aa', 'aba', 'aca', 'abca', 'acba', 'abbacca', 'accabba']
for i in tests:
if i in s:
ans = len(i)
break
print(ans)
|
1636727700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["11", "2", "0"]
|
b267f69cc4af3e319fc59e3ccd8b1c9d
|
NoteIn the first sample, at first you need to reverse substring $$$[1 \dots 2]$$$, and then you need to invert substring $$$[2 \dots 5]$$$. Then the string was changed as follows:Β«01000Β» $$$\to$$$ Β«10000Β» $$$\to$$$ Β«11111Β».The total cost of operations is $$$1 + 10 = 11$$$.In the second sample, at first you need to invert substring $$$[1 \dots 1]$$$, and then you need to invert substring $$$[3 \dots 5]$$$. Then the string was changed as follows:Β«01000Β» $$$\to$$$ Β«11000Β» $$$\to$$$ Β«11111Β».The overall cost is $$$1 + 1 = 2$$$.In the third example, string already consists only of ones, so the answer is $$$0$$$.
|
You've got a string $$$a_1, a_2, \dots, a_n$$$, consisting of zeros and ones.Let's call a sequence of consecutive elements $$$a_i, a_{iβ+β1}, \ldots,βa_j$$$ ($$$1\leqβi\leqβj\leqβn$$$) a substring of string $$$a$$$. You can apply the following operations any number of times: Choose some substring of string $$$a$$$ (for example, you can choose entire string) and reverse it, paying $$$x$$$ coins for it (for example, Β«0101101Β» $$$\to$$$ Β«0111001Β»); Choose some substring of string $$$a$$$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and onesΒ β by zeros), paying $$$y$$$ coins for it (for example, Β«0101101Β» $$$\to$$$ Β«0110001Β»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?
|
Print a single integerΒ β the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $$$0$$$, if you do not need to perform any operations.
|
The first line of input contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1β\leqβnβ\leqβ300\,000, 0 \leq x, y \leq 10^9$$$)Β β length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring). The second line contains the string $$$a$$$ of length $$$n$$$, consisting of zeros and ones.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_011.jsonl
|
e44565c5ca3a2d9439e794034a467582
|
256 megabytes
|
["5 1 10\n01000", "5 10 1\n01000", "7 2 3\n1111111"]
|
PASSED
|
n, x, y = map(int, input().split())
s = input()
i, intervals = 0, 0
while i < n:
j = i
if s[i] == '0':
curr_len = 0
while j < n and s[j] == '0':
j += 1
curr_len += 1
intervals += 1
i = j + 1
if intervals == 0:
print(intervals)
else:
print(min(intervals * y, (intervals - 1) * x + y))
|
1530453900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n2.0000000000\n3.0000000000"]
|
84372885f2263004b74ae753a2f358ac
| null |
You are given an equation: Ax2β+βBxβ+βCβ=β0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
|
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
|
The first line contains three integer numbers A,βB and C (β-β105ββ€βA,βB,βCββ€β105). Any coefficient may be equal to 0.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_001.jsonl
|
a1d827a7a3476ced8d289ac0adb442af
|
256 megabytes
|
["1 -5 6"]
|
PASSED
|
import math
a, b, c = map(int, input().split())
delta = (b*b) - (4*a*c)
# print(delta)
if delta < 0:
print("0")
# elif a+b+c == 0:
# print("-1")
else:
if a != 0:
x1 = (-b + math.sqrt(delta))/(a*2)
x2 = (-b - math.sqrt(delta))/(a*2)
if delta == 0:
print("1")
print("%.5f" % x1)
else:
print("2")
if x1 > x2:
x1, x2 = x2, x1
print("%.5f" % x1)
print("%.5f" % x2)
elif b != 0:
x = -c/b
print("1")
print("%.5f" % x)
elif c!=0:
print("0")
else:
print("-1")
|
1276875000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n2\n1"]
|
1f80d1b61d76ba7725b6e4208a4f735e
|
NoteIn the first test case it is possible to change the array this way: $$$[\underline{3}, 6, 2, 4, \underline{5}]$$$ (changed elements are underlined). After that the array does not need to be divided, so the answer is $$$1$$$.In the second test case it is possible to change the array this way: $$$[6, 2, \underline{3}, 8, 9, \underline{5}, 3, 6, \underline{10}, \underline{11}, 7]$$$. After that such division is optimal: $$$[6, 2, 3]$$$ $$$[8, 9, 5, 3, 6, 10, 11, 7]$$$
|
This is the hard version of the problem. The only difference is that in this version $$$0 \leq k \leq 20$$$.There is an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most $$$k$$$ such operations before the division: choose a number in the array and change its value to any positive integer.What is the minimum number of continuous segments you should use if you will make changes optimally?
|
For each test case print a single integer Β β the answer to the problem.
|
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$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \leq k \leq 20$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^7$$$). It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_087.jsonl
|
36e89991f9cd8a8aa62454e19673e22a
|
256 megabytes
|
["3\n\n5 2\n\n18 6 2 4 1\n\n11 4\n\n6 2 2 8 9 1 3 6 3 9 7\n\n1 0\n\n1"]
|
PASSED
|
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import sqrt,ceil
max_n=10**7+1
spf = [i for i in range(max_n)]
for i in range(4,max_n,2):
spf[i]=2
for i in range(3,ceil(sqrt(max_n))):
if (spf[i]==i):
for j in range(i*i,max_n,i):
if(spf[j]==j):
spf[j]=i
from collections import Counter,defaultdict
from bisect import insort
def f(x):
c=Counter()
ans=1
while(x!=1):
c[spf[x]]+=1
x//=spf[x]
for i in c:
if(c[i]%2==1):
ans*=i
return(ans)
#https://www.geeksforgeeks.org/prime-factorization-using-sieve-olog-n-multiple-queries/
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
a[i]=f(a[i])
dp_depth=[[n for j in range(k+1)] for i in range(n)] #Maximum length that can be tranversed in list, starting from index i with atmost j repeated elements(default is entire length of list(max possible)
recent=[n for i in range(k+1)] #Stores position of most recent repeated element in the suffix(default is one more that maximum index(when no sufficient repeats))
closest=defaultdict(lambda: -1) #Stores index of first repetition for a particular ai
for i in range(n-1,-1,-1):
if(closest[a[i]]>=0):
insort(recent,closest[a[i]])
recent.pop()
dp_depth[i]=recent.copy()
closest[a[i]]=i
dp=[[i for j in range(k+1)] for i in range(n+1)]
#dp=[[float('inf') for j in range(k+1)] for i in range(n+1)] #Minimum number of sets in the prefix segment upto(and **excluding**) index i after atmost k changes(which is also = number of partitions/splits(number of element changes) upto and **excluding** index i).
#Note we could have changed the float('inf') to "i" but that's tougher to debug.
dp[0]=[0 for j in range(k+1)] #base case(don't need to divide at all before element at index 0(first element))
for i in range(n):
for x in range(k+1):
end=dp_depth[i][x] #The end point of our segment(upto and exluding this index position)
#We are dividing each segment into subsegments: prefix consisting of [0,i), suffix consisting from [i,end)
#x is the number of partitions/splits(number of elements we change) in the suffix subsegment(Number of repeated elements starting from index i)
for y in range(k-x+1): #y is the number of partitions/splits(number of elements we change) in the prefix subsegment
dp[end][x+y]=min(dp[end][x+y],dp[i][y]+1) #after using the previously calculated value dp[i][y](<=y changes), with <= x more "changes"(equality holds iff end=n) in the suffix segment, this gives an extra set starting from [i,end). So overall, we get number of sets of dp[i][y]+1.
print(dp[n][k])
|
1615991700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["YES\n3 1 3 \nYES\n1 \nNO\nYES\n5 5 4 1 4 5"]
|
21fed74be8462143d77bbbee48dc8a12
|
NoteLet's consider the $$$1$$$-st test case of the example: the $$$1$$$-st singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd β for $$$6$$$ minutes, in the $$$3$$$-rd β for $$$9$$$ minutes; the $$$2$$$-nd singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd β for $$$1$$$ minute, in the $$$3$$$-rd - for $$$2$$$ minutes; the $$$3$$$-rd singer in the $$$1$$$-st city will give a concert for $$$6$$$ minutes, in the $$$2$$$-nd β for $$$9$$$ minutes, in the $$$3$$$-rd β for $$$3$$$ minutes.
|
$$$n$$$ towns are arranged in a circle sequentially. The towns are numbered from $$$1$$$ to $$$n$$$ in clockwise order. In the $$$i$$$-th town, there lives a singer with a repertoire of $$$a_i$$$ minutes for each $$$i \in [1, n]$$$.Each singer visited all $$$n$$$ towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the $$$i$$$-th singer got inspired and came up with a song that lasts $$$a_i$$$ minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.Hence, for the $$$i$$$-th singer, the concert in the $$$i$$$-th town will last $$$a_i$$$ minutes, in the $$$(i + 1)$$$-th town the concert will last $$$2 \cdot a_i$$$ minutes, ..., in the $$$((i + k) \bmod n + 1)$$$-th town the duration of the concert will be $$$(k + 2) \cdot a_i$$$, ..., in the town $$$((i + n - 2) \bmod n + 1)$$$ β $$$n \cdot a_i$$$ minutes.You are given an array of $$$b$$$ integer numbers, where $$$b_i$$$ is the total duration of concerts in the $$$i$$$-th town. Reconstruct any correct sequence of positive integers $$$a$$$ or say that it is impossible.
|
For each test case, print the answer as follows: If there is no suitable sequence $$$a$$$, print NO. Otherwise, on the first line print YES, on the next line print the sequence $$$a_1, a_2, \dots, a_n$$$ of $$$n$$$ integers, where $$$a_i$$$ ($$$1 \le a_i \le 10^{9}$$$) is the initial duration of repertoire of the $$$i$$$-th singer. If there are multiple answers, print any of them.
|
The first line contains one integer $$$t$$$ $$$(1 \le t \le 10^3$$$) β the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^4$$$) β the number of cities. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^{9}$$$) β the total duration of concerts in $$$i$$$-th city. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_087.jsonl
|
e1efd267d1b30eda865bed7b68fd0687
|
256 megabytes
|
["4\n3\n12 16 14\n1\n1\n3\n1 2 3\n6\n81 75 75 93 93 87"]
|
PASSED
|
'''import requests
import leaf
import pandas as pd
dict = {'ΠΠ²ΠΈΠ°ΡΡΡΠΎΠΈΡΠ΅Π»ΡΠ½ΡΠΉ': 'https://edu.tatar.ru/aviastroit/type/1',
'ΠΠ°Ρ
ΠΈΡΠΎΠ²ΡΠΊΠΈΠΉ': 'https://edu.tatar.ru/vahit/type/1',
'ΠΠΈΡΠΎΠ²ΡΠΊΠΈΠΉ':'https://edu.tatar.ru/kirov/type/1',
'ΠΠΎΡΠΊΠΎΠ²ΡΠΊΠΈΠΉ':'https://edu.tatar.ru/moskow/type/1',
'ΠΠΎΠ²ΠΎ-Π‘Π°Π²ΠΈΠ½ΠΎΠ²ΡΠΊΠΈΠΉ':'https://edu.tatar.ru/nsav/type/1',
'ΠΡΠΈΠ²ΠΎΠ»ΠΆΡΠΊΠΈΠΉ':'https://edu.tatar.ru/priv/type/1',
'Π‘ΠΎΠ²Π΅ΡΡΠΊΠΈΠΉ':'https://edu.tatar.ru/sovetcki/type/1'}
school_links = {'Π Π°ΠΉΠΎΠ½':[], 'ΠΠ΄ΡΠ΅Ρ':[], 'ΠΠ°Π·Π²Π°Π½ΠΈΠ΅':[]}
for key, url in dict.items():
response = requests.get(url)
leaf_doc = leaf.parse(response.text)
leaf_a = leaf_doc('div.panel-body li a')
for i in leaf_a:
print(i.inner_html())
school_links['Π Π°ΠΉΠΎΠ½'].append(key)
school_links['ΠΠ°Π·Π²Π°Π½ΠΈΠ΅'].append(i.inner_html())
school_response = requests.get('https://edu.tatar.ru' + i.href)
leaf_school_doc = leaf.parse(school_response.text)
place = leaf_school_doc.get('div.sp_block.contacts > div.col > table > tr:nth-child(1) > td:nth-child(2)')
school_links['ΠΠ΄ΡΠ΅Ρ'].append(place.inner_html())
df = pd.DataFrame(school_links)
df.to_excel('schools.xlsx')'''
t = int(input())
for i in range(t):
n = int(input())
b = [int(i) for i in input().split()]
a = [0 for i in range(n)]
answer = 'YES'
sumA = int(2 * sum(b) / n / (n + 1))
if sum(b) % (n*(n+1)/2) != 0:
answer = 'NO'
for i in range(1, n):
if answer == 'NO':
break
a[i] = (sumA - b[i] + b[i - 1])
if a[i] % n != 0 or a[i] <= 0:
answer = 'NO'
break
else:
a[i] = int(a[i] / n)
a[0] = sumA - sum(a[1:])
if a[0] <= 0:
answer = 'NO'
print(answer)
if answer == 'YES':
print(*a)
|
1639492500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nYES\nNO\nYES\nNO"]
|
ff95cd4632b2ddf8bb54981634badcae
|
NoteThe first test case is shown in the statement.In the second test case, we transform $$$a$$$ into $$$b$$$ by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform $$$a$$$ into $$$b$$$.In the fourth test case, here is one such transformation: Select the length $$$2$$$ prefix to get $$$100101010101$$$. Select the length $$$12$$$ prefix to get $$$011010101010$$$. Select the length $$$8$$$ prefix to get $$$100101011010$$$. Select the length $$$4$$$ prefix to get $$$011001011010$$$. Select the length $$$6$$$ prefix to get $$$100110011010$$$. In the fifth test case, the only legal operation is to transform $$$a$$$ into $$$111000$$$. From there, the only legal operation is to return to the string we started with, so we cannot transform $$$a$$$ into $$$b$$$.
|
There is a binary string $$$a$$$ of length $$$n$$$. In one operation, you can select any prefix of $$$a$$$ with an equal number of $$$0$$$ and $$$1$$$ symbols. Then all symbols in the prefix are inverted: each $$$0$$$ becomes $$$1$$$ and each $$$1$$$ becomes $$$0$$$.For example, suppose $$$a=0111010000$$$. In the first operation, we can select the prefix of length $$$8$$$ since it has four $$$0$$$'s and four $$$1$$$'s: $$$[01110100]00\to [10001011]00$$$. In the second operation, we can select the prefix of length $$$2$$$ since it has one $$$0$$$ and one $$$1$$$: $$$[10]00101100\to [01]00101100$$$. It is illegal to select the prefix of length $$$4$$$ for the third operation, because it has three $$$0$$$'s and one $$$1$$$. Can you transform the string $$$a$$$ into the string $$$b$$$ using some finite number of operations (possibly, none)?
|
For each test case, output "YES" if it is possible to transform $$$a$$$ into $$$b$$$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).
|
The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$) β the length of the strings $$$a$$$ and $$$b$$$. The following two lines contain strings $$$a$$$ and $$$b$$$ of length $$$n$$$, consisting of symbols $$$0$$$ and $$$1$$$. The sum of $$$n$$$ across all test cases does not exceed $$$3\cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_100.jsonl
|
b8c56965606eb0ef9b60e3748f4dff4b
|
256 megabytes
|
["5\n10\n0111010000\n0100101100\n4\n0000\n0000\n3\n001\n000\n12\n010101010101\n100110011010\n6\n000111\n110100"]
|
PASSED
|
import math
import string
def main_function():
test_cases = range(int(input()))
answers = []
for test_case in test_cases:
n = int(input())
equal_counter = 0
s_1 = list(input())
s_2 = list(input())
for i in range(n):
j = n - 1 - i
if s_1[j] == s_2[j]:
equal_counter += 1
else:
break
counter_1 = 0
counter_0 = 0
is_equal_mode = False
counter_for_completeness = False
good_for = True
for i in range(len(s_1)):
if i == 0:
if s_1[i] == s_2[i]:
is_equal_mode = True
else:
is_equal_mode = False
if s_1[i] == "1":
counter_1 += 1
else:
counter_0 += 1
else:
if is_equal_mode:
if s_1[i] != s_2[i]:
good_for = False
break
else:
if s_1[i] == s_2[i]:
good_for = False
break
if s_1[i] == "1":
counter_1 += 1
else:
counter_0 += 1
if counter_1 == counter_0:
#print(i)
counter_for_completeness = True
if i + 1 < len(s_1):
if s_1[i + 1] == s_2[i + 1]:
is_equal_mode = True
else:
is_equal_mode = False
if i + equal_counter >= len(s_1) - 1:
# print("break worked")
break
else:
counter_for_completeness = False
# print(good_for)
# print(equal_counter)
# print(counter_for_completeness)
if not counter_for_completeness:
good_for = False
# print(good_for)
if equal_counter == len(s_1):
good_for = True
# print(equal_counter)
# print(good_for)
if good_for:
print("YES")
else:
print("NO")
main_function()
|
1617460500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["NO", "YES", "YES", "NO"]
|
8b61213e2ce76b938aa68ffd1e4c1429
|
NoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it.
|
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations yβ=βkiΒ·xβ+βbi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1β<βx2. In other words, is it true that there are 1ββ€βiβ<βjββ€βn and x',βy', such that: y'β=βkiβ*βx'β+βbi, that is, point (x',βy') belongs to the line number i; y'β=βkjβ*βx'β+βbj, that is, point (x',βy') belongs to the line number j; x1β<βx'β<βx2, that is, point (x',βy') lies inside the strip bounded by x1β<βx2. You can't leave Anton in trouble, can you? Write a program that solves the given task.
|
Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).
|
The first line of the input contains an integer n (2ββ€βnββ€β100β000)Β β the number of lines in the task given to Anton. The second line contains integers x1 and x2 (β-β1β000β000ββ€βx1β<βx2ββ€β1β000β000) defining the strip inside which you need to find a point of intersection of at least two lines. The following n lines contain integers ki, bi (β-β1β000β000ββ€βki,βbiββ€β1β000β000)Β β the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two iββ βj it is true that either kiββ βkj, or biββ βbj.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_007.jsonl
|
e3947f6b1ab23bbd5aad75badaac0902
|
256 megabytes
|
["4\n1 2\n1 2\n1 0\n0 1\n0 2", "2\n1 3\n1 0\n-1 3", "2\n1 3\n1 0\n0 2", "2\n1 3\n1 0\n0 3"]
|
PASSED
|
# -*- coding: utf-8 -*-
from operator import itemgetter
n = int(raw_input())
x1, x2 = map(int, raw_input().split(' '))
x1 += 0.0000001
x2 -= 0.0000001
k = []
b = []
positive = False
starts, ends = [], []
for i in xrange(n):
new_k, new_b = map(int, raw_input().split(' '))
starts.append({
'index': i,
'value': new_k * x1 + new_b
})
ends.append({
'index': i,
'value': new_k * x2 + new_b
})
starts.sort(key=itemgetter('value'))
ends.sort(key=itemgetter('value'))
for i in xrange(n):
if starts[i]['index'] != ends[i]['index']:
print('YES')
break
else:
print('NO')
|
1446655500
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["HelloVKCup2017", "7uduGUDUUDUgudu7"]
|
d6f01ece3f251b7aac74bf3fd8231a80
| null |
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.
|
Print the text if the same keys were pressed in the second layout.
|
The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout. The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout. The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_010.jsonl
|
58b311fd628bb8c2ea62905e3a5cdb8b
|
256 megabytes
|
["qwertyuiopasdfghjklzxcvbnm\nveamhjsgqocnrbfxdtwkylupzi\nTwccpQZAvb2017", "mnbvcxzlkjhgfdsapoiuytrewq\nasdfghjklqwertyuiopzxcvbnm\n7abaCABAABAcaba7"]
|
PASSED
|
a=input()
b=input()
c=input()
f=""
for i in c:
if(ord(i)>=65):
for j in range(len(a)):
if(i.lower()==a[j]):
if(i.isupper()):
f+=b[j].upper()
else:
f+=b[j]
else:
f+=i
print(f)
|
1499958300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES", "NO", "YES"]
|
f110b9351fe8ff20676d11ecfc92aee3
|
NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.
|
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.
|
In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.
|
The first line of input contains two integers n and m (1ββ€βn,βmββ€β104) β number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, kβ>β0) followed by k integers vi,β1,βvi,β2,β...,βvi,βk. If vi,βj is negative, it means that Rick from universe number β-βvi,βj has joined this group and otherwise it means that Morty from universe number vi,βj has joined it. Sum of k for all groups does not exceed 104.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_004.jsonl
|
50bf784254eb3f10682b6f9529468e73
|
256 megabytes
|
["4 2\n1 -3\n4 -2 3 2 -3", "5 2\n5 3 -2 1 -1 5\n3 -5 2 5", "7 2\n3 -1 6 7\n7 -5 4 2 4 7 -3 4"]
|
PASSED
|
n, m = map(int, input().split())
for i in range(m):
bad = True
l = set(map(int, input().split()[1:]))
for j in l:
if -j in l:
bad = False
break
if bad:
break
print("YES" if bad else "NO")
|
1490281500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3.5 seconds
|
["3\n1\n78975\n969\n109229059713337"]
|
6a3043daecdb0442f4878ee08a8b70ba
|
NoteIn the first test case, there are $$$3$$$ suitable triplets: $$$(1,2,3)$$$, $$$(1,3,4)$$$, $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet: $$$(3,4,5)$$$.
|
We are sum for we are manySome NumberThis version of the problem differs from the previous one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \le i < j < k \le r$$$ and $$$\operatorname{lcm}(i,j,k) \ge i + j + k$$$.Here $$$\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.
|
For each test case print one integerΒ β the number of suitable triplets.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\bf{1 \le t \le 10^5}$$$). Description of the test cases follows. The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 2 \cdot 10^5$$$, $$$l + 2 \le r$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,500 |
train_102.jsonl
|
8dd855bd44801ba57fb9761711999bb8
|
512 megabytes
|
["5\n\n1 4\n\n3 5\n\n8 86\n\n68 86\n\n6 86868"]
|
PASSED
|
n = int(2e5+5)
ft = [0]*n
def update(i, val):
while i<n:
ft[i]-=val
i+=(i&(-i))
return
def query(i):
ans = 0
while i!=0:
ans += ft[i]
i -=(i&(-i))
return ans
cnt = [0 for i in range(n)]
pre = [0 for i in range(n)]
for i in range(1,n):
for j in range(i+i, n, i):
cnt[j] += 1
pre[i] = pre[i-1] + (cnt[i]*(cnt[i]-1))/2
for i in range(1, n):
ft[i]=pre[i]-pre[i-(i&(-i))]
vec = []
t = int(input())
ans = [0 for i in range(t+1)]
for _ in range(t):
arr = list(map(int, input().split()))
arr.append(_)
vec.append(arr)
vec.sort()
l = 1
for i in range(t):
r = vec[i][1]
while l< vec[i][0]:
for j in range(2*l, n, l):
cnt[j]-=1
update(j, cnt[j])
l+=1
m = r-l+1
ans[vec[i][2]]=query(r);
ans[vec[i][2]]+=max(r//6-(l+2)//3+1,0)
ans[vec[i][2]]+=max(r//15-(l+5)//6+1,0)
ans[vec[i][2]]=(m*(m-1)*(m-2))//6-ans[vec[i][2]]
for i in range(t):
print(int(ans[i]))
|
1660401300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
|
d17c9f91504e1d4c4eae7294bf09dcfc
|
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
|
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to helpΒ β print the sequence of indices of string $$$s$$$ on which he should jump.
|
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$)Β β the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
|
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$Β β is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,100 |
train_110.jsonl
|
9367b1d5ef8ed4bf00a07cd1c9f849ac
|
256 megabytes
|
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
|
PASSED
|
from string import ascii_lowercase as asc
import sys
input = lambda: sys.stdin.buffer.readline().decode().strip()
print = sys.stdout.write
for _ in range(int(input())):
word = list(input())
ci, ti = asc.index(word[0]) + 1, asc.index(word[-1]) + 1
ans = []
if ci <= ti:
for i in range(ci, ti + 1):
[ans.append(j + 1) for j, l in enumerate(word) if l == chr(i + 96)]
else:
for i in range(ci, ti - 1, -1):
[ans.append(k + 1) for k, l in enumerate(word) if l == chr(i + 96)]
print(str(abs(ti - ci)) + " " + str(len(ans)) + "\n" + ' '.join(map(str, ans)) + "\n")
|
1662993300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["2", "19", "0"]
|
f8f84cec87b3bb8c046d8a45f2c4a071
|
NoteIn the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2,β1,β2) turns off, it disrupts the control by CPU (2,β1,β3) over CPU (2,β1,β1), and when CPU (2,β2,β2) is turned off, it disrupts the control over CPU (2,β2,β3) by CPU (2,β2,β1).In the second sample all processors except for the corner ones are critical.In the third sample there is not a single processor controlling another processor, so the answer is 0.
|
A super computer has been built in the Turtle Academy of Sciences. The computer consists of nΒ·mΒ·k CPUs. The architecture was the paralellepiped of size nβΓβmβΓβk, split into 1βΓβ1βΓβ1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x,βy,βz) can send messages to CPUs (xβ+β1,βy,βz), (x,βyβ+β1,βz) and (x,βy,βzβ+β1) (of course, if they exist), there is no feedback, that is, CPUs (xβ+β1,βy,βz), (x,βyβ+β1,βz) and (x,βy,βzβ+β1) cannot send messages to CPU (x,βy,βz).Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a,βb,βc) controls CPU (d,βe,βf) , if there is a chain of CPUs (xi,βyi,βzi), such that (x1β=βa,βy1β=βb,βz1β=βc), (xpβ=βd,βypβ=βe,βzpβ=βf) (here and below p is the length of the chain) and the CPU in the chain with number i (iβ<βp) can send messages to CPU iβ+β1.Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x,βy,βz) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x,βy,βz) CPUs: (a,βb,βc) and (d,βe,βf), such that (a,βb,βc) controls (d,βe,βf) before (x,βy,βz) is turned off and stopped controlling it after the turning off.
|
Print a single integer β the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.
|
The first line contains three integers n, m and k (1ββ€βn,βm,βkββ€β100)Β β the dimensions of the Super Computer. Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each β the description of a layer in the format of an mβΓβk table. Thus, the state of the CPU (x,βy,βz) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_059.jsonl
|
b40f5d2b84e935c9ec128a4dabaac81d
|
256 megabytes
|
["2 2 3\n000\n000\n\n111\n111", "3 3 3\n111\n111\n111\n\n111\n111\n111\n\n111\n111\n111", "1 1 10\n0101010101"]
|
PASSED
|
def main():
s = input().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])
processor = []
for x in range(n):
for y in range(m):
s = input()
for z in s:
processor.append(int(z) == 1)
if x < n - 1:
emptyLine = input()
counter = 0
mk = m * k
nmk = n * mk
for i in range(nmk):
if not processor[i]:
continue
# back
if i >= mk:
if processor[i - mk]:
# front
if i < (nmk - mk):
if processor[i + mk]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
if not processor[i - mk + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
if not processor[i - mk + k]:
counter += 1
continue
# left
if (i % k) > 0:
if processor[i - 1]:
# front
if i < (nmk - mk):
if processor[i + mk]:
if not processor[i + mk - 1]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
if not processor[i + k - 1]:
counter += 1
continue
# up
if (i % mk) >= k:
if processor[i - k]:
# front
if i < (nmk - mk):
if processor[i + mk]:
if not processor[i + mk - k]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
if not processor[i - k + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
counter += 1
continue
print(counter)
main()
|
1458475200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1801", "11"]
|
08bce37778b7bfe478340d5c222ae362
|
NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros.
|
Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.
|
Print a single integerΒ β the smallest number Dima can obtain.
|
The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$)Β β the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_008.jsonl
|
5720543951a5bfb7cdf2a5a71d18aadd
|
512 megabytes
|
["7\n1234567", "3\n101"]
|
PASSED
|
n=int(input())
s=input()
mid=len(s)//2
l=mid
r=mid+1
while l>=0 and s[l]=='0':
l-=1
while r<n and s[r]=='0':
r+=1
if l==0:
print(int(s[:r])+int(s[r:]))
elif r==n:
print(int(s[:l])+int(s[l:]))
else:
print(min(int(s[:r])+int(s[r:]),int(s[:l])+int(s[l:])))
|
1560677700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nYES\nNO"]
|
235ddb32dbe19c0da1f77069e36128bb
| null |
You are given two strings $$$s$$$ and $$$t$$$, both of length $$$n$$$. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions: choose an occurrence of "ab" in $$$s$$$ and replace it with "ba"; choose an occurrence of "bc" in $$$s$$$ and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $$$s$$$ to make it equal to string $$$t$$$?
|
For each testcase, print "YES" if you can change string $$$s$$$ to make it equal to string $$$t$$$ by performing an arbitrary amount of moves (possibly, zero). Otherwise, print "NO".
|
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$)Β β the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the length of strings $$$s$$$ and $$$t$$$. The second line contains string $$$s$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The third line contains string $$$t$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_083.jsonl
|
5f1b8b6a0acb88992dddd16d063df98d
|
256 megabytes
|
["5\n\n3\n\ncab\n\ncab\n\n1\n\na\n\nb\n\n6\n\nabbabc\n\nbbaacb\n\n10\n\nbcaabababc\n\ncbbababaac\n\n2\n\nba\n\nab"]
|
PASSED
|
import collections
q = int(input())
for _ in range(q):
n = int(input())
s = list(input())
t = list(input())
occ_s = collections.defaultdict(int)
occ_t = collections.defaultdict(int)
s2 = ""
t2 = ""
for i in range(n):
occ_s[s[i]] += 1
occ_t[t[i]] += 1
if s[i] != "b": s2 += s[i]
if t[i] != "b": t2 += t[i]
if s2 != t2:
print("NO")
continue
l, r = 0, 0
i = 0
flag = True
while i < occ_s["a"]:
while s[l] != "a":
l += 1
while t[r] != "a":
r += 1
i += 1
l += 1
r += 1
if l > r:
flag = False
break
if not flag:
print("NO")
continue
l, r = 0, 0
i = 0
while i < occ_s["c"]:
while s[l] != "c":
l += 1
while t[r] != "c":
r += 1
i += 1
l += 1
r += 1
if r > l:
flag = False
break
print("NO") if not flag else print("YES")
|
1655044500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1 1 1 1 1 \n3 3 3 \n2 3 3 2 1 3 \n1 \n2 2 2 2 \n4 4 4 1 4"]
|
345e76bf67ae4342e850ab248211eb0b
| null |
The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids: after the $$$1$$$-st day it will belong to the $$$5$$$-th kid, after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid, after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid, after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.
|
For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.
|
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) β the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) β the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_008.jsonl
|
bcb2521e572c526e43616689013059c8
|
256 megabytes
|
["6\n5\n1 2 3 4 5\n3\n2 3 1\n6\n4 6 2 1 5 3\n1\n1\n4\n3 4 1 2\n5\n5 1 2 4 3"]
|
PASSED
|
from sys import stdin, stdout
t = int(stdin.readline())
def getRoot(i,par):
while i!=par[i]:
i = par[i]
return i
def find(a,b,par):
return getRoot(a,par)==getRoot(b,par)
def doUnion(a,b,par,size):
if find(a,b,par):
return False
r1 = getRoot(a,par)
r2 = getRoot(b,par)
s1 = size[r1]
s2 = size[r2]
if s1 > s2:
par[r2] = r1
size[r1] += s2
else:
par[r1] = r2
size[r2] += s1
return True
while t>0:
n = int(stdin.readline())
a = list( map(int,stdin.readline().split()) )
par,size = [ i for i in range(n+1) ], [ 1 for i in range(n+1) ]
for i in range(n):
x,y = i+1,a[i]
doUnion(x,y,par,size)
ans = []
for i in range(n):
c = size[ getRoot(i+1,par) ]
ans.append(c)
for i in range(len(ans)):
stdout.write("{} ".format(ans[i]))
stdout.write("\n")
t-=1
|
1571754900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\n01\n11\nYES\n0011\n1111\n1111\n1100\nNO\nYES\n01111\n11000\n10000\n10000\n10000"]
|
95e2ea3e270af683706b9832557c3442
|
NoteFor the first test case, you only have to delete cell $$$(1, 1)$$$.For the second test case, you could choose to delete cells $$$(1,1)$$$, $$$(1,2)$$$, $$$(4,3)$$$ and $$$(4,4)$$$.For the third test case, it is no solution because the cells in the diagonal will always form a strictly increasing sequence of length $$$5$$$.
|
You are given an $$$n \times n$$$ grid. We write $$$(i, j)$$$ to denote the cell in the $$$i$$$-th row and $$$j$$$-th column. For each cell, you are told whether yon can delete it or not. Given an integer $$$k$$$, you are asked to delete exactly $$$(n-k+1)^2$$$ cells from the grid such that the following condition holds. You cannot find $$$k$$$ not deleted cells $$$(x_1, y_1), (x_2, y_2), \dots, (x_k, y_k)$$$ that are strictly increasing, i.e., $$$x_i < x_{i+1}$$$ and $$$y_i < y_{i+1}$$$ for all $$$1 \leq i < k$$$. Your task is to find a solution, or report that it is impossible.
|
For each test case, if there is no way to delete exactly $$$(n-k+1)^2$$$ cells to meet the condition, output "NO" (without quotes). Otherwise, output "YES" (without quotes). Then, output $$$n$$$ lines. The $$$i$$$-th line should contain a binary string $$$t_i$$$ of length $$$n$$$. The $$$j$$$-th character of $$$t_i$$$ is 0 if cell $$$(i, j)$$$ is deleted, and 1 otherwise. If there are multiple solutions, you can output any of them. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) β the number of test cases. The following lines contain the description of each test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 1000$$$). Then $$$n$$$ lines follow. The $$$i$$$-th line contains a binary string $$$s_i$$$ of length $$$n$$$. The $$$j$$$-th character of $$$s_i$$$ is 1 if you can delete cell $$$(i, j)$$$, and 0 otherwise. It's guaranteed that the sum of $$$n^2$$$ over all test cases does not exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,900 |
train_103.jsonl
|
0a79b53880ffffbb8485731019bba663
|
512 megabytes
|
["4\n\n2 2\n\n10\n\n01\n\n4 3\n\n1110\n\n0101\n\n1010\n\n0111\n\n5 5\n\n01111\n\n10111\n\n11011\n\n11101\n\n11110\n\n5 2\n\n10000\n\n01111\n\n01111\n\n01111\n\n01111"]
|
PASSED
|
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")
def solve():
n, K = map(int, input().split())
S = [list(input()) for _ in range(n)]
A = [[] for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(n):
if S[i][j] == "0":
A[j].append(i)
used = [[False] * n for _ in range(n)]
add = n - K + 2
cc = 0
for j in range(K - 1):
x = n - 1
for i in range(j, j + add):
if not A[i] or A[i][-1] > x:
nx = x
else:
nx = A[i][-1]
while A[i] and A[i][-1] <= x:
A[i].pop()
nx = min(nx, n - 1 - (K - 2 - j))
if i == j + add - 1:
nx = 0
for k in range(nx, x + 1):
if used[k][i]:
print("NO")
return
used[k][i] = True
cc += 1
x = nx
for i in range(n):
if A[i]:
print("NO")
return
ans = [[1] * n for _ in range(n)]
c = (n - K + 1) ** 2
assert c + cc == n ** 2
for i in range(n):
for j in range(n):
if used[i][j]:
continue
if S[i][j] == "1":
c -= 1
ans[i][j] = 0
else:
print("NO")
return
if c != 0:
print("NO")
else:
print("YES")
for row in ans:
print(*row, sep="")
for _ in range(int(input())):
solve()
|
1664548500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.