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
|
["4\n2 1 1 1\n1 1 1 2\n1 2 2 2\n2 2 2 1", "4\n2 2 1 2\n1 2 2 2\n1 2 1 3\n1 3 1 2"]
|
3cc8a5fcd612e9328e5d2c8d824d792a
|
NoteConsider the first example. The current state of the table:00 1001 11The first operation. The cell $$$(2, 1)$$$ contains the string $$$01$$$. Applying the operation to cells $$$(2, 1)$$$ and $$$(1, 1)$$$, we move the $$$1$$$ from the end of the string $$$01$$$ to the beginning of the string $$$00$$$ and get the string $$$100$$$. The current state of the table:100 100 11The second operation. The cell $$$(1, 1)$$$ contains the string $$$100$$$. Applying the operation to cells $$$(1, 1)$$$ and $$$(1, 2)$$$, we move the $$$0$$$ from the end of the string $$$100$$$ to the beginning of the string $$$10$$$ and get the string $$$010$$$. The current state of the table:10 0100 11The third operation. The cell $$$(1, 2)$$$ contains the string $$$010$$$. Applying the operation to cells $$$(1, 2)$$$ and $$$(2, 2)$$$, we move the $$$0$$$ from the end of the string $$$010$$$ to the beginning of the string $$$11$$$ and get the string $$$011$$$. The current state of the table:10 010 011The fourth operation. The cell $$$(2, 2)$$$ contains the string $$$011$$$. Applying the operation to cells $$$(2, 2)$$$ and $$$(2, 1)$$$, we move the $$$1$$$ from the end of the string $$$011$$$ to the beginning of the string $$$0$$$ and get the string $$$10$$$. The current state of the table:10 0110 01 It's easy to see that we have reached the final state of the table.
|
Egor came up with a new chips puzzle and suggests you to play.The puzzle has the form of a table with $$$n$$$ rows and $$$m$$$ columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state.To do this, you can use the following operation. select 2 different cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$: the cells must be in the same row or in the same column of the table, and the string in the cell $$$(x_1, y_1)$$$ must be non-empty; in one operation you can move the last character of the string at the cell $$$(x_1, y_1)$$$ to the beginning of the string at the cell $$$(x_2, y_2)$$$. Egor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as $$$s$$$ the number of characters in each of the tables (which are the same). Then you should use no more than $$$4 \cdot s$$$ operations.
|
On the first line print $$$q$$$ — the number of operations used. You should find such a solution that $$$0 \leq q \leq 4 \cdot s$$$. In each the next $$$q$$$ lines print 4 integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$. On the $$$i$$$-th line you should print the description of the $$$i$$$-th operation. These integers should satisfy the conditions $$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$, $$$(x_1, y_1) \neq (x_2, y_2)$$$, $$$x_1 = x_2$$$ or $$$y_1 = y_2$$$. The string in the cell $$$(x_1, y_1)$$$ should be non-empty. This sequence of operations should transform the initial state of the table to the final one. We can show that a solution exists. If there is more than one solution, find any of them.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n, m \leq 300$$$) — the number of rows and columns of the table, respectively. The following $$$n$$$ lines describe the initial state of the table in the following format: each line contains $$$m$$$ non-empty strings consisting of zeros and ones. In the $$$i$$$-th of these lines, the $$$j$$$-th string is the string written at the cell $$$(i, j)$$$. The rows are enumerated from $$$1$$$ to $$$n$$$, the columns are numerated from $$$1$$$ to $$$m$$$. The following $$$n$$$ lines describe the final state of the table in the same format. Let's denote the total length of strings in the initial state as $$$s$$$. It is guaranteed that $$$s \leq 100\, 000$$$. It is also guaranteed that the numbers of zeros and ones coincide in the initial and final states.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_035.jsonl
|
349b29b035c022afb562388b821d7008
|
256 megabytes
|
["2 2\n00 10\n01 11\n10 01\n10 01", "2 3\n0 0 0\n011 1 0\n0 0 1\n011 0 0"]
|
PASSED
|
def fill(oper, curr, upper, second, n, m):
for i in range(n):
for j in range(m):
for s in reversed(curr[i][j]):
if s == '0':
if i == 0:
dest = (j + 1) % m
oper.append((0, j, 0, dest))
upper[dest] += 1
else:
oper.append((i, j, 0, j))
upper[j] += 1
else:
if i == 1:
dest = (j + 1) % m
oper.append((1, j, 1, dest))
second[dest] += 1
else:
oper.append((i, j, 1, j))
second[j] += 1
def mix(oper, start, finish, row):
less = []
greater = []
for ind in range(len(start)):
if start[ind] < finish[ind]:
less.append(ind)
else:
greater.append(ind)
l = 0
r = 0
while l != len(less):
if start[less[l]] < finish[less[l]]:
if start[greater[r]] > finish[greater[r]]:
oper.append((row, greater[r], row, less[l]))
start[less[l]] += 1
start[greater[r]] -= 1
else:
r += 1
else:
l += 1
def main(n, m, first, second):
x = first
y = [[list(reversed(st)) for st in second[i]] for i in range(n)]
upper1 = [0] * m
second1 = [0] * m
oper = []
fill(oper, x, upper1, second1, n, m)
upper2 = [0] * m
second2 = [0] * m
back = []
fill(back, y, upper2, second2, n, m)
# print(upper1, upper2, second1, second2, end='\n')
mix(oper, upper1, upper2, 0)
mix(oper, second1, second2, 1)
return str(len(oper) + len(back)) + '\n' + '\n'.join(' '.join(str(t + 1) for t in o) for o in oper) + '\n' + \
'\n'.join('{} {} {} {}'.format(o[2] + 1, o[3] + 1, o[0] + 1, o[1] + 1) for o in reversed(back))
if __name__ == '__main__':
n, m = map(int, input().split())
print(main(n, m, [input().split() for _ in range(n)], [input().split() for _ in range(n)]))
|
1539880500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2", "0", "797922655"]
|
907f7db88fb16178d6be57bea12f90a2
|
NoteIn the first example, this is the other possible case. In the second example, it's impossible to make a grid to satisfy such $$$r$$$, $$$c$$$ values.In the third example, make sure to print answer modulo $$$(10^9 + 7)$$$.
|
Suppose there is a $$$h \times w$$$ grid consisting of empty or full cells. Let's make some definitions: $$$r_{i}$$$ is the number of consecutive full cells connected to the left side in the $$$i$$$-th row ($$$1 \le i \le h$$$). In particular, $$$r_i=0$$$ if the leftmost cell of the $$$i$$$-th row is empty. $$$c_{j}$$$ is the number of consecutive full cells connected to the top end in the $$$j$$$-th column ($$$1 \le j \le w$$$). In particular, $$$c_j=0$$$ if the topmost cell of the $$$j$$$-th column is empty. In other words, the $$$i$$$-th row starts exactly with $$$r_i$$$ full cells. Similarly, the $$$j$$$-th column starts exactly with $$$c_j$$$ full cells. These are the $$$r$$$ and $$$c$$$ values of some $$$3 \times 4$$$ grid. Black cells are full and white cells are empty. You have values of $$$r$$$ and $$$c$$$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $$$r$$$ and $$$c$$$. Since the answer can be very large, find the answer modulo $$$1000000007\,(10^{9} + 7)$$$. In other words, find the remainder after division of the answer by $$$1000000007\,(10^{9} + 7)$$$.
|
Print the answer modulo $$$1000000007\,(10^{9} + 7)$$$.
|
The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \le h, w \le 10^{3}$$$) — the height and width of the grid. The second line contains $$$h$$$ integers $$$r_{1}, r_{2}, \ldots, r_{h}$$$ ($$$0 \le r_{i} \le w$$$) — the values of $$$r$$$. The third line contains $$$w$$$ integers $$$c_{1}, c_{2}, \ldots, c_{w}$$$ ($$$0 \le c_{j} \le h$$$) — the values of $$$c$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,400 |
train_002.jsonl
|
600fdd1ce561721193160d86be5d7f6d
|
256 megabytes
|
["3 4\n0 3 1\n0 2 3 0", "1 1\n0\n1", "19 16\n16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12\n6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4"]
|
PASSED
|
R = lambda: map(int, raw_input().split())
r, c = R()
ret = [[-1] * c for i in range(r)]
for i, x in zip(range(r), R()):
for j in range(x):
ret[i][j] = 1
if x != c:
ret[i][x] = 0
flag = 1
for i, x in zip(range(c), R()):
if flag:
for j in range(x):
if ret[j][i] == 0:
flag = 0
break
ret[j][i] = 1
if x != r:
if ret[x][i] == 1:
flag = 0
break
ret[x][i] = 0
if flag:
MOD = 1000000007
ans = 1
for i in range(r):
for j in range(c):
if ret[i][j] == -1:
ans <<= 1
if ans >= MOD:
ans -= MOD
print ans
else:
print 0
|
1569762300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4\n7\n11", "5\n4\n1\n5", "82\n125\n9\n191\n62\n63\n97"]
|
461378e9179c9de454674ea9dc49c56c
|
NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.
|
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.
|
Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.
|
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions. The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_096.jsonl
|
1340e6b65325cc0ce1f2806a74ebaf39
|
256 megabytes
|
["7 3\nabacaba\n1 3\n2 5\n1 7", "7 4\nabbabaa\n1 3\n5 7\n6 6\n2 4", "13 7\nsonoshikumiwo\n1 5\n2 10\n7 7\n1 13\n4 8\n2 5\n3 9"]
|
PASSED
|
n, t = map(int, input().split())
ui = input()
req = [0 for z in range(n + 1)]
for i, res in enumerate(ui):
req[i + 1] = req[i] + (ord(res) - 96)
for q in range(t):
l, r = map(int, input().split())
print(req[r] - req[l - 1])
|
1624183500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["4\n0\n3"]
|
e58fcbf5c49dc5666b1c65a0d5c76b6e
|
NoteIn the first test case, the original array is $$$[7, 6, 5, 4]$$$. In the second test case, the original array is $$$[4, 7, 6, 5]$$$.In the third test case, the original array is $$$[3, 1, 2]$$$.
|
This is the hard version of the problem. The difference in the constraints between both versions are colored below in red. You can make hacks only if all versions of the problem are solved.Marin and Gojou are playing hide-and-seek with an array.Gojou initially perform the following steps: First, Gojou chooses $$$2$$$ integers $$$l$$$ and $$$r$$$ such that $$$l \leq r$$$. Then, Gojou will make an array $$$a$$$ of length $$$r-l+1$$$ which is a permutation of the array $$$[l,l+1,\ldots,r]$$$. Finally, Gojou chooses a secret integer $$$x$$$ and sets $$$a_i$$$ to $$$a_i \oplus x$$$ for all $$$i$$$ (where $$$\oplus$$$ denotes the bitwise XOR operation). Marin is then given the values of $$$l,r$$$ and the final array $$$a$$$. She needs to find the secret integer $$$x$$$ to win. Can you help her?Note that there may be multiple possible $$$x$$$ that Gojou could have chosen. Marin can find any possible $$$x$$$ that could have resulted in the final value of $$$a$$$.
|
For each test case print an integer $$$x$$$. If there are multiple answers, print any.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. In the first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$\color{red}{\boldsymbol{0} \boldsymbol{\le} \boldsymbol{l}} \le r < 2^{17}$$$). The second line contains $$$r - l + 1$$$ space-seperated integers of $$$a_1,a_2,\ldots,a_{r-l+1}$$$ ($$$0 \le a_i < 2^{17}$$$). It is guaranteed that array $$$a$$$ is valid. It is guaranteed that the sum of $$$r - l + 1$$$ over all test cases does not exceed $$$2^{17}$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_095.jsonl
|
ac7d7fb931eab5a5eeeb50058d3a449b
|
256 megabytes
|
["3\n\n4 7\n\n3 2 1 0\n\n4 7\n\n4 7 6 5\n\n1 3\n\n0 2 1"]
|
PASSED
|
import sys
input = sys.stdin.readline
dd = [0] * (2 ** 17 + 1)
for _ in range(int(input())):
l, r = [int(xx) for xx in input().split()]
a = [int(xx) for xx in input().split()]
for i in range(r - l + 1):
dd[a[i]] = 1
if l % 2 == 0 and r % 2 == 1:
if r - l > 1000:
g = [0] * 17
for i in range(1, 17):
k = 0
for j in range(r - l + 1):
if a[j] % (2 ** (i + 1)) >= 2 ** i:
k += 1
l1 = 0
for j in range(l, r + 1):
if j % (2 ** (i + 1)) >= 2 ** i:
l1 += 1
if l1 != k:
g[i] = 1
ans = 0
for i in range(1, 17):
ans += g[i] * (2 ** i)
print(int(ans))
else:
for i in range(r - l + 1):
x = a[i] ^ l
for j in range(l, r + 1):
if not dd[j ^ x]:
break
else:
print(x)
break
else:
h = []
for i in range(r - l + 1):
if not dd[a[i] ^ 1]:
h.append(a[i])
for i in range(len(h)):
x = h[i] ^ l
for j in range(r - l + 1):
if a[j] ^ x < l or a[j] ^ x > r:
break
else:
print(x)
break
else:
for i in range(len(h)):
x = h[i] ^ r
for j in range(r - l + 1):
if a[j] ^ x < l or a[j] ^ x > r:
break
else:
print(x)
break
for i in range(r - l + 1):
dd[a[i]] = 0
|
1648391700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3 3 4 4 4 4 4 4 5 5 5 5 \n1 1"]
|
dc1dc5e5dd17d19760c772739ce244a7
|
NoteOne possible sequence of choices for the first testcase where Tina has $$$k=3$$$ buckets of paints is as follows.Tina paints the seats at positions $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ with pink paint. Rahul chooses the seat at $$$(3, 1)$$$ after which Tina chooses to sit at $$$(1, 3)$$$. Therefore, the distance between Tina and Rahul is $$$|3-1| + |1-3| = 4$$$, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For $$$k=0$$$ in the first test case, Rahul can decide to sit at $$$(2, 2)$$$ and Tina can decide to sit at $$$(4, 3)$$$ so the distance between them would be $$$|2 - 4| + |2 - 3| = 3$$$.Below are pictorial representations of the $$$k=3$$$ and $$$k=0$$$ cases for the first test case. A possible seating arrangement for $$$k=3$$$. A possible seating arrangement for $$$k=0$$$.
|
Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $$$n \times m$$$ grid. The seat in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r, c)$$$, and the distance between two seats $$$(a,b)$$$ and $$$(c,d)$$$ is $$$|a-c| + |b-d|$$$. As the class president, Tina has access to exactly $$$k$$$ buckets of pink paint. The following process occurs. First, Tina chooses exactly $$$k$$$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat. After Tina has painted $$$k$$$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink. After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for $$$k = 0, 1, \dots, n \cdot m - 1$$$, if Tina has $$$k$$$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!
|
For each test case, output $$$n \cdot m$$$ ordered integers — the distance between Rahul and Tina if both of them act optimally for every $$$k \in [0, n \cdot m - 1]$$$.
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \cdot m \leq 10^5$$$) — the number of rows and columns of seats in the classroom. The sum of $$$n \cdot m$$$ across all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300 |
train_109.jsonl
|
36b53e049ccb682c7eebf86cd2d41b1c
|
256 megabytes
|
["2\n\n4 3\n\n1 2"]
|
PASSED
|
def main():
import sys
readline=sys.stdin.readline
for _ in range(int(readline())):
n,m=map(int,readline().split())
ans=[]
for a in range(n):
for b in range(m):
ans.append(max(a+b,a+m-b-1,n-a+m-b-2,n-a-1+b))
print(' '.join(map(str,sorted(ans))))
main()
|
1642257300
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "V", "IV", "1111001", "A"]
|
c619d699e3e5fb42aea839ef6080c86c
|
NoteYou can find more information about roman numerals here: http://en.wikipedia.org/wiki/Roman_numerals
|
It's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.Each door has 4 parts. The first part is an integer number a. The second part is either an integer number b or some really odd sign which looks like R. The third one is an integer c and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.c is an integer written in base a, to open the door we should write it in base b. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!Here's an explanation of this really weird number system that even doesn't have zero:Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.: I=1 V=5 X=10 L=50 C=100 D=500 M=1000Symbols are iterated to produce multiples of the decimal (1, 10, 100, 1, 000) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I 1, II 2, III 3, V 5, VI 6, VII 7, etc., and the same for other bases: X 10, XX 20, XXX 30, L 50, LXXX 80; CC 200, DCC 700, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.Also in bases greater than 10 we use A for 10, B for 11, etc.Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.
|
Write a single line that contains integer c in base b. You must omit leading zeros.
|
The first line contains two integers a and b (2 ≤ a, b ≤ 25). Only b may be replaced by an R which indicates Roman numbering system. The next line contains a single non-negative integer c in base a which may contain leading zeros but its length doesn't exceed 103. It is guaranteed that if we have Roman numerals included the number would be less than or equal to 300010 and it won't be 0. In any other case the number won't be greater than 101510.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_049.jsonl
|
e595002367f398e053845df76c44662b
|
256 megabytes
|
["10 2\n1", "16 R\n5", "5 R\n4", "2 2\n1111001", "12 13\nA"]
|
PASSED
|
numbers = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15,'G':16,'H':17,'I':18,'J':19,'K':20,'L':21,'M':22,'N':23,'O':24,'P':25,'Q':26,'R':27,'S':28,'T':29,'U':30,'V':31,'W':32,'X':33,'Y':34,'Z':35}
characters = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F',16:'G',17:'H',18:'I',19:'J',20:'K',21:'L',22:'M',23:'N',24:'O',25:'P',26:'Q',27:'R',28:'S',29:'T',30:'U',31:'V',32:'W',33:'X',34:'Y',35:'Z'}
def ConvertToDecimal(number, base):
newnumber = 0
for digit in range(-1,(0-len(number))-1,-1):
if(numbers[number[digit]] >= int(base)):
return -1
newnumber += numbers[number[digit]]*(int(base)**(0-digit-1))
return newnumber
def ConvertToBase(number, base):
newnumber = ''
if(number == 0):
return '0'
while number > 0:
newnumber = characters[number%base] + newnumber
number = number//base
return newnumber
def ConvertToRoman(number):
newnumber = ''
for i in range(4,0,-1):
currentnumber = (number%(10**i) - number%(10**(i-1)))//(10**(i-1))
if(currentnumber > 0):
if(i==4):
newnumber += 'M'*currentnumber
elif(i==3):
if(currentnumber == 9):
newnumber += 'CM'
elif(currentnumber>=5):
newnumber += 'D' + 'C'*(currentnumber-5)
elif currentnumber == 4:
newnumber += 'CD'
else:
newnumber += 'C'*currentnumber
elif(i==2):
if(currentnumber == 9):
newnumber += 'XC'
elif(currentnumber>=5):
newnumber += 'L' + 'X'*(currentnumber-5)
elif currentnumber == 4:
newnumber += 'XL'
else:
newnumber += 'X'*currentnumber
elif(i==1):
if(currentnumber == 9):
newnumber += 'IX'
elif(currentnumber>=5):
newnumber += 'V' + 'I'*(currentnumber-5)
elif currentnumber == 4:
newnumber += 'IV'
else:
newnumber += 'I'*currentnumber
return newnumber
a,b = [x for x in input().split()]
c = input()
if b == 'R':
print(ConvertToRoman(ConvertToDecimal(c,int(a))))
else:
print(ConvertToBase(ConvertToDecimal(c,int(a)),int(b)))
|
1298390400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nYES\nYES\nNO"]
|
2515630678babfa39f606d535948abf7
|
NoteIn the first test case, you can remove all stones without using a superability: $$$[1, 2, 1] \rightarrow [1, 1, 0] \rightarrow [0, 0, 0]$$$.In the second test case, you can apply superability to the second and the third piles and then act like in the first testcase.In the third test case, you can apply superability to the fourth and the fifth piles, thus getting $$$a = [2, 2, 2, 3, 1]$$$.In the fourth test case, you can apply superability to the first and the second piles, thus getting $$$a = [1900, 2100, 1600, 3000, 1600]$$$.
|
During cleaning the coast, Alice found $$$n$$$ piles of stones. The $$$i$$$-th pile has $$$a_i$$$ stones.Piles $$$i$$$ and $$$i + 1$$$ are neighbouring for all $$$1 \leq i \leq n - 1$$$. If pile $$$i$$$ becomes empty, piles $$$i - 1$$$ and $$$i + 1$$$ doesn't become neighbouring.Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to do only the following operation: Select two neighboring piles and, if both of them are not empty, remove one stone from each of them. Alice understands that sometimes it's impossible to remove all stones with the given operation, so she allowed you to use the following superability: Before the start of cleaning, you can select two neighboring piles and swap them. Determine, if it is possible to remove all stones using the superability not more than once.
|
For each test case, print YES or NO — is it possible to remove all stones using the superability not more than once or not.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the number of stones in each pile. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_100.jsonl
|
51c1acc5694f3f39b47f04c3f0704ac3
|
256 megabytes
|
["5\n3\n1 2 1\n3\n1 1 2\n5\n2 2 2 1 3\n5\n2100 1900 1600 3000 1600\n2\n2443 2445"]
|
PASSED
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
A = list(map(int, input().split()))
L, R = [0] * (n + 1), [0] * (n + 1)
for i in range(n):
L[i + 1] = -1 if L[i] < 0 else A[i] - L[i]
for i in range(n - 1, -1, -1):
R[i] = -1 if R[i + 1] < 0 else A[i] - R[i + 1]
if L[-1] == 0:
print("YES")
continue
for i in range(n - 1):
left, right = L[i], R[i + 2]
if left < 0 or right < 0: continue
cur = A[i + 1] - left
if cur < 0: continue
cur = A[i] - cur
if cur < 0: continue
cur = right - cur
if not cur:
print("YES")
break
else:
print("NO")
|
1611066900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["d 2\ns 3\n! 5"]
|
5e34b8ed812d392799f45c3c3fa1c979
|
NoteIn the first example, the hidden node is node $$$5$$$. We first ask about the distance between node $$$x$$$ and node $$$2$$$. The answer is $$$3$$$, so node $$$x$$$ is either $$$4$$$ or $$$5$$$. We then ask about the second node in the path from node $$$3$$$ to node $$$x$$$. Note here that node $$$3$$$ is an ancestor of node $$$5$$$. We receive node $$$5$$$ as the answer. Finally, we report that the hidden node is node $$$5$$$.
|
This is an interactive problem.You're given a tree consisting of $$$n$$$ nodes, rooted at node $$$1$$$. A tree is a connected graph with no cycles.We chose a hidden node $$$x$$$. In order to find this node, you can ask queries of two types: d $$$u$$$ ($$$1 \le u \le n$$$). We will answer with the distance between nodes $$$u$$$ and $$$x$$$. The distance between two nodes is the number of edges in the shortest path between them. s $$$u$$$ ($$$1 \le u \le n$$$). We will answer with the second node on the path from $$$u$$$ to $$$x$$$. However, there's a plot twist. If $$$u$$$ is not an ancestor of $$$x$$$, you'll receive "Wrong answer" verdict! Node $$$a$$$ is called an ancestor of node $$$b$$$ if $$$a \ne b$$$ and the shortest path from node $$$1$$$ to node $$$b$$$ passes through node $$$a$$$. Note that in this problem a node is not an ancestor of itself.Can you find $$$x$$$ in no more than $$$36$$$ queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
|
To print the answer, print "! x" (without quotes).
|
The first line contains the integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_025.jsonl
|
36e9cfe7b32f4fd7e3d06d16f15264f6
|
256 megabytes
|
["5\n1 2\n1 3\n3 4\n3 5\n3\n5"]
|
PASSED
|
def sec(tup):
return -tup[1]
def do(graph,top,level):
if level==0:
print("!",top)
return None
curr=top
for i in range(level):
curr=graph[curr]
print("d",curr)
dist=int(input())
if dist==0:
print("!",curr)
return None
newt=top
for i in range(level-dist//2):
newt=graph[newt]
print("s",newt)
v=int(input())
newt=v
newl=dist//2-1
do(graph,newt,newl)
return None
def main():
n=int(input())
graph=[[] for i in range(n+1)]
for i in range(n-1):
u,v=map(int,input().split())
graph[u].append(v)
graph[v].append(u)
print("d",1)
d=int(input())
layers=[[1]]
layer=[1]
lays=[None]*(n+1)
lays[1]=0
for i in range(d):
newlayer=[]
for guy in layer:
for neigh in graph[guy]:
graph[neigh].remove(guy)
newlayer.append(neigh)
lays[neigh]=i+1
layers.append(newlayer)
layer=newlayer
des=[0]*(n+1)
for guy in layers[-1]:
des[guy]=1
for i in range(d):
for guy in layers[-i-2]:
des[guy]=sum(des[boi] for boi in graph[guy])
for guy in range(1,n+1):
for i in range(len(graph[guy])):
graph[guy][i]=(graph[guy][i],des[graph[guy][i]])
graph[guy].sort(key=sec)
best=[0]*(n+1)
for i in range(1,n+1):
if len(graph[i])>0:
best[i]=graph[i][0][0]
do(best,1,d)
main()
|
1559570700
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["No", "Yes", "No"]
|
8fd51c391728b433cc94923820e908ff
|
NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into "q", then second player is unable to move, so he loses.
|
Two people are playing a game with a string $$$s$$$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.
|
If the first player wins, print "Yes". If the second player wins, print "No".
|
The only line contains the string $$$s$$$, consisting of lowercase latin letters ($$$1 \leq |s| \leq 100\,000$$$), where $$$|s|$$$ means the length of a string $$$s$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_001.jsonl
|
0ac7e679160fa139a0478a0bbb566a16
|
256 megabytes
|
["abacaba", "iiq", "abba"]
|
PASSED
|
s = input()
n = len(s)
a = []
a.append(s[0])
ans = 0
for i in range(1, n):
if a:
cur = a.pop()
if cur == s[i]:
ans += 1
continue
else:
a.append(cur)
a.append(s[i])
else:
a.append(s[i])
if ans % 2:
print('Yes')
else:
print('No')
|
1548167700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["No", "Yes\n4 12 7 31 7 61"]
|
4033eee4e822b9df57e30297e339c17d
|
NoteIn the first example no permutation is valid.In the second example the given answer lead to the sequence $$$a_1 = 4$$$, $$$a_2 = 8$$$, $$$a_3 = 15$$$, $$$a_4 = 16$$$, $$$a_5 = 23$$$, $$$a_6 = 42$$$.
|
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence $$$a_1, \ldots, a_n$$$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $$$b_1, \ldots, b_n$$$ using the following rules: $$$b_1 = a_1$$$; $$$b_i = a_i \oplus a_{i - 1}$$$ for all $$$i$$$ from 2 to $$$n$$$, where $$$x \oplus y$$$ is the bitwise XOR of $$$x$$$ and $$$y$$$. It is easy to see that the original sequence can be obtained using the rule $$$a_i = b_1 \oplus \ldots \oplus b_i$$$.However, some time later Vitya discovered that the integers $$$b_i$$$ in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers $$$b_i$$$ so that the sequence $$$a_i = b_1 \oplus \ldots \oplus b_i$$$ is strictly increasing. Help him find such a permutation or determine that it is impossible.
|
If there are no valid permutations, print a single line containing "No". Otherwise in the first line print the word "Yes", and in the second line print integers $$$b'_1, \ldots, b'_n$$$ — a valid permutation of integers $$$b_i$$$. The unordered multisets $$$\{b_1, \ldots, b_n\}$$$ and $$$\{b'_1, \ldots, b'_n\}$$$ should be equal, i. e. for each integer $$$x$$$ the number of occurrences of $$$x$$$ in the first multiset should be equal to the number of occurrences of $$$x$$$ in the second multiset. Apart from this, the sequence $$$a_i = b'_1 \oplus \ldots \oplus b'_i$$$ should be strictly increasing. If there are multiple answers, print any of them.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$ ($$$1 \leq b_i < 2^{60}$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_060.jsonl
|
d3ccd7f0aa8552894cdc24383c30b5e6
|
256 megabytes
|
["3\n1 2 3", "6\n4 7 7 12 31 61"]
|
PASSED
|
import sys
def interleave(c, b, mask):
lb, ib, s = len(b), 0, False
if ib<lb:
yield b[ib]
ib, s = 1, True
for e in c:
yield e
s ^= (e&mask)>0
if not s and ib<lb:
yield b[ib]
ib, s = ib+1, True
if ib<lb: yield -1
def calprefix(b):
cur = 0
for e in b:
cur ^= e
yield cur
n = int(raw_input())
b = [int(t) for t in raw_input().split()]
c = []
for w in range(60,0,-1):
low, high = 1<<(w-1), (1<<w)-1
bx = filter(lambda x: low<=x and x<=high, b)
c = list(interleave(c, bx, low))
if len(c)>0 and c[-1]==-1:
print "No"
sys.exit(0)
print "Yes"
print " ".join(map(lambda x: str(x), c))
#ans = list(calprefix(c))
#print " ".join(map(lambda x: str(x), ans))
#c = 0
#for e in ans:
# print c^e
# c = e
|
1525007700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n5\n4"]
|
b89e9598adae3da19903cdbfd225dd3c
|
NoteIn the first test case we get either $$$a = [1, 2]$$$ or $$$a = [2, 1]$$$ after casting the spell for the first time, and it is impossible to cast it again.
|
— Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got $$$n$$$ piles of candies, the $$$i$$$-th pile initially contains $$$a_i$$$ candies. BThero can cast a copy-paste spell as follows: He chooses two piles $$$(i, j)$$$ such that $$$1 \le i, j \le n$$$ and $$$i \ne j$$$. All candies from pile $$$i$$$ are copied into pile $$$j$$$. Formally, the operation $$$a_j := a_j + a_i$$$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $$$k$$$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?
|
For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power.
|
The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case consists of two lines: the first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$, $$$2 \le k \le 10^4$$$); the second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le k$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$, and the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_006.jsonl
|
d7aab99a4852170a83d0ff0e7a84e745
|
256 megabytes
|
["3\n2 2\n1 1\n3 5\n1 2 3\n3 7\n3 2 2"]
|
PASSED
|
x1 = int(input())
for i in range(x1):
n,k = map(int,input().split())
l = list(map(int,input().split()))
c=0
d=min(l)
l.sort()
for i in range(1,n):
c+=(k-l[i])//d
print(c)
|
1601219100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
|
86bf9688b92ced5238009eefd051387d
| null |
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
|
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
|
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 109) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the numbers on Eugeny's cards.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_020.jsonl
|
50894e6c8f81b1921873a203326db8c7
|
256 megabytes
|
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
|
PASSED
|
#!/usr/bin/env python3
class CantException(Exception):
pass
def odd_v(value):
return 1 if value % 2 == 1 else -1
change_idx = 1
acceptable = {-1: set(), 1: set()}
def change(card_values, oddv, m):
global change_idx
if acceptable[oddv]:
res = acceptable[oddv].pop()
card_values.add(res)
return res
change_idx_start = change_idx
while change_idx in card_values or odd_v(change_idx) != oddv:
if change_idx not in card_values:
acceptable[odd_v(change_idx)].add(change_idx)
change_idx += 1
if change_idx > m:
change_idx = 1
if change_idx == change_idx_start:
raise CantException()
res = change_idx
card_values.add(res)
change_idx += 1
if change_idx > m:
change_idx = 1
return res
def solve():
n, m = map(int, input().split())
cards = list(map(int, input().split()))
odd_balance = 0
card_values = set()
indices_to_be_changed = set()
for i, c in enumerate(cards):
odd_balance += odd_v(c)
if c in card_values:
indices_to_be_changed.add(i)
card_values.add(c)
# print("indices to be changed: ", indices_to_be_changed)
change_count = len(indices_to_be_changed)
for i in indices_to_be_changed:
if odd_v(cards[i]) * odd_balance <= 0:
#print("Changing ", cards[i])
cards[i] = change(card_values, odd_v(cards[i]), m)
#print("Changed to ", cards[i])
else:
#print("For teh balance changing ", cards[i])
odd_balance -= 2 * odd_v(cards[i])
cards[i] = change(card_values, - odd_v(cards[i]), m)
#print("Changed to ", cards[i])
#print("current odd balance:", odd_balance)
for i in range(len(cards)):
if odd_balance == 0:
break
if odd_v(cards[i]) * odd_balance > 0:
# print("gonna change")
change_count += 1
odd_balance -= 2 * odd_v(cards[i])
cards[i] = change(card_values, -odd_v(cards[i]), m)
odd_balance = 0
for i, c in enumerate(cards):
odd_balance += odd_v(c)
if odd_balance != 0:
print(odd_balance)
print("WTFFFFF")
return change_count, cards
if __name__ == '__main__':
try:
change_cnt, cards = solve()
print(change_cnt)
print(" ".join(map(str, cards)))
except CantException:
print("-1")
|
1482057300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES", "NO\nNO"]
|
0369c070f4ac9aba4887bae32ad8b85b
|
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
|
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
|
For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_003.jsonl
|
4d469d39f9db33f22e52909f52b92a5a
|
256 megabytes
|
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
|
PASSED
|
import os
import sys
from io import BytesIO, IOBase
import math
def dfsVisited (G, node, nodeInfo, V, P):
V.add (node)
ans = 0
for v in G[node]:
if v not in V:
ans += dfsVisited (G, v, nodeInfo, V, P)
ans += P[node-1]
nodeInfo[node-1][0] = ans
return ans
def dfsCheckBecameHappy (G, node, nodeInfo, V):
V.add (node)
childUnhappy = 0
childHappy = 0
for v in G[node]:
if v not in V:
childHappy += nodeInfo[v-1][1]
if childHappy > nodeInfo[node-1][1]: return False
ans = True
for v in G[node]:
if v not in V:
ans = ans and dfsCheckBecameHappy (G, v, nodeInfo, V)
return ans
def main():
t = int(input())
for _ in range (t):
n,m = map(int, input().split())
P = list(map(int, input().split()))
H = list(map(int, input().split()))
root = 1
graph = dict()
nodeInfo = [[-1]*3 for i in range (n)] #visitedPeople, happy, unhappy
for i in range (1, n+1):
graph[i] = list()
for _ in range (n-1):
u,v = map(int, input().split())
graph[u].append (v)
graph[v].append (u)
visited = set()
_ = dfsVisited(graph, 1, nodeInfo, visited, P)
okay = True
for i in range (n):
happy = (nodeInfo[i][0]+H[i])/2
if math.floor(happy) != math.ceil(happy):
okay = not okay
break
unhappy = nodeInfo[i][0]-happy
if happy<0 or unhappy<0:
okay = not okay
break
nodeInfo[i][1] = int(happy)
nodeInfo[i][2] = int(unhappy)
if not okay:
print ("NO")
continue
visited = set()
if dfsCheckBecameHappy (graph, 1, nodeInfo, visited):
print ("YES")
else:
print ("NO")
# 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 = lambda s: self.buffer.write(s.encode()) if self.writable else None
def read(self):
if self.buffer.tell():
return self.buffer.read().decode("ascii")
return os.read(self._fd, os.fstat(self._fd).st_size).decode("ascii")
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().decode("ascii")
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
def print(*args, sep=" ", end="\n", file=sys.stdout, flush=False):
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(end)
if flush:
file.flush()
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
sys.setrecursionlimit(int(1e7))
if __name__ == "__main__":
main()
|
1596119700
|
[
"math",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
0,
1
] |
|
2 seconds
|
["1 2\n3 3", "2 3\n4 6", "1 1\n2 2", "2 7\n8 13"]
|
23261cfebebe782715646c38992c48a6
|
NoteIn the first example $$$s[1;2] = 12$$$ and $$$s[3;3] = 5$$$, $$$12+5=17$$$.In the second example $$$s[2;3] = 54$$$ and $$$s[4;6] = 471$$$, $$$54+471=525$$$.In the third example $$$s[1;1] = 2$$$ and $$$s[2;2] = 3$$$, $$$2+3=5$$$.In the fourth example $$$s[2;7] = 218633$$$ and $$$s[8;13] = 757639$$$, $$$218633+757639=976272$$$.
|
Let's call a positive integer good if there is no digit 0 in its decimal representation.For an array of a good numbers $$$a$$$, one found out that the sum of some two neighboring elements is equal to $$$x$$$ (i.e. $$$x = a_i + a_{i + 1}$$$ for some $$$i$$$). $$$x$$$ had turned out to be a good number as well.Then the elements of the array $$$a$$$ were written out one after another without separators into one string $$$s$$$. For example, if $$$a = [12, 5, 6, 133]$$$, then $$$s = 1256133$$$.You are given a string $$$s$$$ and a number $$$x$$$. Your task is to determine the positions in the string that correspond to the adjacent elements of the array that have sum $$$x$$$. If there are several possible answers, you can print any of them.
|
In the first line, print two integers $$$l_1$$$, $$$r_1$$$, meaning that the first term of the sum ($$$a_i$$$) is in the string $$$s$$$ from position $$$l_1$$$ to position $$$r_1$$$. In the second line, print two integers $$$l_2$$$, $$$r_2$$$, meaning that the second term of the sum ($$$a_{i + 1}$$$) is in the string $$$s$$$ from position $$$l_2$$$ to position $$$r_2$$$.
|
The first line contains the string $$$s$$$ ($$$2 \le |s| \le 5 \cdot 10^5$$$). The second line contains an integer $$$x$$$ ($$$2 \le x < 10^{200000}$$$). An additional constraint on the input: the answer always exists, i.e you can always select two adjacent substrings of the string $$$s$$$ so that if you convert these substrings to integers, their sum is equal to $$$x$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 3,200 |
train_090.jsonl
|
2453a85f89f18fa1a6f787779ff48d24
|
256 megabytes
|
["1256133\n17", "9544715561\n525", "239923\n5", "1218633757639\n976272"]
|
PASSED
|
import sys
s = sys.stdin.readline().strip()
x = sys.stdin.readline().strip()
ls, lx = len(s), len(x)
MOD = 2**31-1
h = [0] * (ls+1)
p = [1] * (ls+1)
def gh(start, end):
return (h[end+1] - h[start] * p[end-start+1]) % MOD
def gen_z(s, zx = None, x=None):
z = [0]*len(s)
l, r, start = 0, -1, 0
if not zx: zx = z; x =s; z[0] = len(s); start = 1
for i in range(start, len(s)):
if i <= r: z[i] = min(zx[i - l], r - i + 1);
while i + z[i] < len(s) and z[i] < len(x) and s[i + z[i]] == x[z[i]]: z[i]+=1;
if i + z[i] - 1 > r:
l = i;
r = i + z[i] - 1;
return z
zx = gen_z(x)
zs = gen_z(s, zx, x)
for idx, i in enumerate(s):
h[idx+1] = (h[idx] * 10 + ord(i) - 48) % MOD
p[idx+1] = p[idx]*10 % MOD
target = 0
for i in x: target = (target * 10 + ord(i) - 48) % MOD
def printresult(a, b, c):
sys.stdout.write("%d %d\n%d %d\n" % (a+1, b, b+1, c+1))
sys.exit()
if lx > 1:
for i in range(ls - lx - lx + 3):
if (gh(i, i+lx-2) + gh(i+lx-1, i+lx+lx-3)) % MOD == target: printresult(i, i+lx-1, i+lx+lx-3)
for i in range(ls - lx + 1):
j = lx - zs[i]
if j > 0:
if i+lx+j <= ls and (gh(i, i+lx-1) + gh(i+lx, i+lx+j-1)) % MOD == target: printresult(i, i+lx, i+lx+j-1)
if i-j >= 0 and (gh(i-j, i-1) + gh(i, i+lx-1)) % MOD == target: printresult(i-j, i, i+lx-1)
if j > 1:
if i+lx+j-1 <= ls and (gh(i, i+lx-1) + gh(i+lx, i+lx+j-2)) % MOD == target: printresult(i, i+lx, i+lx+j-2)
if i-j+1 >= 0 and (gh(i-j+1, i-1) + gh(i, i+lx-1)) % MOD == target: printresult(i-j+1, i, i+lx-1)
|
1633856700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
3 seconds
|
["7\n4\n1"]
|
6c1d534c1066997eb7e7963b4e783708
|
NoteIn the first test case, the array $$$a$$$ is not good, but if we take the subsequence $$$[a_1, a_2, a_3, a_4, a_5, a_6, a_8]$$$, then the square can be split as shown in the statement.In the second test case, we can take the subsequence consisting of the last four elements of $$$a$$$ and cut the square with a horizontal line through its center.
|
There is a $$$k \times k$$$ grid, where $$$k$$$ is even. The square in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r,c)$$$. Two squares $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are considered adjacent if $$$\lvert r_1 - r_2 \rvert + \lvert c_1 - c_2 \rvert = 1$$$.An array of adjacent pairs of squares is called strong if it is possible to cut the grid along grid lines into two connected, congruent pieces so that each pair is part of the same piece. Two pieces are congruent if one can be matched with the other by translation, rotation, and reflection, or a combination of these. The picture above represents the first test case. Arrows indicate pairs of squares, and the thick black line represents the cut. You are given an array $$$a$$$ of $$$n$$$ pairs of adjacent squares. Find the size of the largest strong subsequence of $$$a$$$. An array $$$p$$$ is a subsequence of an array $$$q$$$ if $$$p$$$ can be obtained from $$$q$$$ by deletion of several (possibly, zero or all) elements.
|
For each test case, output a single integer — the size of the largest strong subsequence of $$$a$$$.
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$; $$$2 \leq k \leq 500$$$, $$$k$$$ is even) — the length of $$$a$$$ and the size of the grid, respectively. Then $$$n$$$ lines follow. The $$$i$$$-th of these lines contains four space-separated integers $$$r_{i,1}$$$, $$$c_{i,1}$$$, $$$r_{i,2}$$$, and $$$c_{i,2}$$$ ($$$1 \leq r_{i,1}, c_{i,1}, r_{i,2}, c_{i,2} \leq k$$$) — the $$$i$$$-th element of $$$a$$$, represented by the row and column of the first square $$$(r_{i,1}, c_{i,1})$$$ and the row and column of the second square $$$(r_{i,2}, c_{i,2})$$$. These squares are adjacent. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$, and the sum of $$$k$$$ over all test cases does not exceed $$$500$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,700 |
train_109.jsonl
|
fbce098fcc71f106dfe8a865041df174
|
512 megabytes
|
["3\n\n8 4\n\n1 2 1 3\n\n2 2 2 3\n\n3 2 3 3\n\n4 2 4 3\n\n1 4 2 4\n\n2 1 3 1\n\n2 2 3 2\n\n4 1 4 2\n\n7 2\n\n1 1 1 2\n\n2 1 2 2\n\n1 1 1 2\n\n1 1 2 1\n\n1 2 2 2\n\n1 1 2 1\n\n1 2 2 2\n\n1 6\n\n3 3 3 4"]
|
PASSED
|
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from heapq import heappop, heappush
for _ in range(int(input())):
q, n = map(int, input().split())
graph = [[[] for j in range(n + 1)] for i in range(n + 1)]
for x in range(n + 1):
for y in range(n + 1):
if x - 1 >= 0: graph[x-1][y] += [[x, y, 0]]
if x + 1 < n: graph[x+1][y] += [[x, y, 0]]
if y - 1 >= 0: graph[x][y-1] += [[x, y, 0]]
if y + 1 < n: graph[x][y+1] += [[x, y, 0]]
def update(x1, y1, x2, y2):
for i in range(len(graph[x1][y1])):
if (graph[x1][y1][i][0], graph[x1][y1][i][1]) == (x2, y2):
graph[x1][y1][i][2] += 1
for i in range(len(graph[x2][y2])):
if (graph[x2][y2][i][0], graph[x2][y2][i][1]) == (x1, y1):
graph[x2][y2][i][2] += 1
for i in range(q):
x1, y1, x2, y2 = map(int, input().split())
if x1 == x2:
y1, y2 = min(y1, y2), max(y1, y2)
update(x1 - 1, y1, x1, y1)
update(n - (x1 - 1), n - y1, n - x1, n - y1)
else:
x1, x2 = min(x1, x2), max(x1, x2)
update(x1, y1 - 1, x1, y1)
update(n - x1, n - (y1 - 1), n - x1, n - y1)
dist = [[float("inf")] * (n + 1) for __ in range(n + 1)]
queue = []
heappush(queue, (0, n // 2, n // 2))
dist[n // 2][n // 2] = 0
while queue:
length, x, y = heappop(queue)
if x == 0 or y == 0:
print(q - length)
break
if dist[x][y] != length:
continue
for x2, y2, w in graph[x][y]:
if dist[x2][y2] > dist[x][y] + w:
dist[x2][y2] = dist[x][y] + w
heappush(queue, (dist[x2][y2], x2, y2))
|
1642257300
|
[
"geometry",
"graphs"
] |
[
0,
1,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1", "0"]
|
1b8596fcbaa42fa334b782b78ad1931b
|
NoteIn the first test case, Qingshan can only choose $$$x=3$$$ to win, so the answer is $$$1$$$.In the second test case, if Qingshan will choose $$$x=4$$$, Daniel can choose $$$y=1$$$. In the first turn (Qingshan's) Qingshan chooses $$$x'=3$$$ and changes $$$x$$$ to $$$3$$$. In the second turn (Daniel's) Daniel chooses $$$y'=2$$$ and changes $$$y$$$ to $$$2$$$. Qingshan can't choose $$$x'=2$$$ because $$$y=2$$$ at this time. Then Qingshan loses.
|
On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.A permutation $$$p$$$ is written from left to right on the paper. First Qingshan chooses an integer index $$$x$$$ ($$$1\le x\le n$$$) and tells it to Daniel. After that, Daniel chooses another integer index $$$y$$$ ($$$1\le y\le n$$$, $$$y \ne x$$$).The game progresses turn by turn and as usual, Qingshan moves first. The rules follow: If it is Qingshan's turn, Qingshan must change $$$x$$$ to such an index $$$x'$$$ that $$$1\le x'\le n$$$, $$$|x'-x|=1$$$, $$$x'\ne y$$$, and $$$p_{x'}<p_x$$$ at the same time. If it is Daniel's turn, Daniel must change $$$y$$$ to such an index $$$y'$$$ that $$$1\le y'\le n$$$, $$$|y'-y|=1$$$, $$$y'\ne x$$$, and $$$p_{y'}>p_y$$$ at the same time. The person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible $$$x$$$ to make Qingshan win in the case both players play optimally.
|
Print the number of possible values of $$$x$$$ that Qingshan can choose to make her win.
|
The first line contains a single integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$p_1,p_2,\dots,p_n$$$ ($$$1\le p_i\le n$$$) — the permutation.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_085.jsonl
|
bcbe05872ccfdfee5211bb0a249738a3
|
256 megabytes
|
["5\n1 2 5 4 3", "7\n1 2 4 6 5 3 7"]
|
PASSED
|
n = int(input())
a = [int(i) for i in input().split()]
r = []
cur = 0
i = 0
while n != i + 1:
while n != i + 1 and a[i] < a[i + 1]:
i += 1
cur += 1
r.append(cur + 1)
cur = 1
while n != i + 1 and a[i] > a[i + 1]:
i += 1
cur += 1
r.append(cur)
cur = 0
t = max(r)
if t % 2 == 0:
print(0)
exit()
ans = 0
fl = False
for i in range(0, len(r), 2):
if (r[i] == t and r[i + 1] == t) and not fl:
ans += 1
elif fl and r[i] == t or r[i+1] == t:
print(0)
exit()
if r[i] == t or r[i+1] == t:
fl = True
print(ans)
|
1615377900
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["2", "2"]
|
9ed2a081b65df66629fcf0d4fc0bb02c
|
NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").
|
A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).
|
Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.
|
The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,500 |
train_015.jsonl
|
4554a2bd185ee93367daa91e09f62ebb
|
256 megabytes
|
["bb??x???\naab", "ab?c\nacb"]
|
PASSED
|
s = raw_input()
p = raw_input()
from collections import Counter
dp = Counter(p)
def eqp(d):
need = 0
p = dp
for key in p:
if key not in d:
need += p[key]
continue
if d[key] > p[key]:
return False
if d[key] < p[key]:
need += p[key] - d[key]
continue
if "?" in d:
if need != d["?"]:
return False
else:
return True
else:
if need == 0:
return True
else:
return False
d = {}
count = 0
for i in xrange(len(s)):
if i >= len(p):
d[s[i-len(p)]] -= 1
if d[s[i-len(p)]] == 0:
del d[s[i-len(p)]]
if s[i] not in d:
d[s[i]] = 0
d[s[i]] += 1
if eqp(d):
count += 1
print count
|
1326899100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1230", "2750685", "2189"]
|
c943742fb0720af18058ff0da8a33974
|
NoteFor the first example the answer is just the sum of numbers from $$$l$$$ to $$$r$$$ which equals to $$$\frac{50 \cdot 51}{2} - \frac{9 \cdot 10}{2} = 1230$$$. This example also explained in the problem statement but for $$$k = 1$$$.For the second example the answer is just the sum of numbers from $$$l$$$ to $$$r$$$ which equals to $$$\frac{2345 \cdot 2346}{2} = 2750685$$$.For the third example the answer is $$$101 + 110 + 111 + 112 + 113 + 114 + 115 + 116 + 117 + 118 + 119 + 121 + 122 + 131 + 133 + 141 + 144 + 151 = 2189$$$.
|
You are given two integers $$$l$$$ and $$$r$$$ ($$$l \le r$$$). Your task is to calculate the sum of numbers from $$$l$$$ to $$$r$$$ (including $$$l$$$ and $$$r$$$) such that each number contains at most $$$k$$$ different digits, and print this sum modulo $$$998244353$$$.For example, if $$$k = 1$$$ then you have to calculate all numbers from $$$l$$$ to $$$r$$$ such that each number is formed using only one digit. For $$$l = 10, r = 50$$$ the answer is $$$11 + 22 + 33 + 44 = 110$$$.
|
Print one integer — the sum of numbers from $$$l$$$ to $$$r$$$ such that each number contains at most $$$k$$$ different digits, modulo $$$998244353$$$.
|
The only line of the input contains three integers $$$l$$$, $$$r$$$ and $$$k$$$ ($$$1 \le l \le r < 10^{18}, 1 \le k \le 10$$$) — the borders of the segment and the maximum number of different digits.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_033.jsonl
|
de930c6302e4fe4819684b472e8876c6
|
256 megabytes
|
["10 50 2", "1 2345 10", "101 154 2"]
|
PASSED
|
MOD = 998244353
def pop_count(x) :
ans = 0
while (x > 0) :
ans = ans + x % 2
x = x // 2
return ans
def check(x, k) :
mask = 0
nx = int(x)
while (nx > 0) :
mask = mask | (1 << (nx % 10))
nx = nx // 10
if (pop_count(mask) <= k) :
return x
return 0
pop = []
p10 = []
f = [[0 for j in range(1 << 10)] for i in range(20)]
w = [[0 for j in range(1 << 10)] for i in range(20)]
def prepare() :
p10.append(1)
for i in range(20) :
p10.append(p10[i] * 10 % MOD)
for i in range(1 << 10) :
pop.append(pop_count(i))
w[0][0] = 1
for i in range(1, 20) :
for j in range(1 << 10) :
for use in range(10) :
w[i][j | (1 << use)] = (w[i][j | (1 << use)] + w[i - 1][j]) % MOD
f[i][j | (1 << use)] = (f[i][j | (1 << use)] + w[i - 1][j] * use * p10[i - 1] + f[i - 1][j]) % MOD
def solve(x, k) :
sx = [int(d) for d in str(x)]
n = len(sx)
ans = 0
for i in range(1, n) :
for use in range(1, 10) :
for mask in range(1 << 10) :
if (pop[(1 << use) | mask] <= k) :
ans = (ans + f[i - 1][mask] + use * w[i - 1][mask] % MOD * p10[i - 1]) % MOD
cmask = 0
csum = 0
for i in range(n) :
cdig = sx[i]
for use in range(cdig) :
if (i == 0 and use == 0) :
continue
nmask = cmask | (1 << use)
for mask in range(1 << 10) :
if (pop[nmask | mask] <= k) :
ans = (ans + f[n - i - 1][mask] + (csum * 10 + use) * w[n - i - 1][mask] % MOD * p10[n - i - 1]) % MOD
cmask |= 1 << cdig
csum = (10 * csum + cdig) % MOD
return ans
prepare()
l, r, k = map(int, input().split())
ans = (check(r, k) + solve(r, k) - solve(l, k) + MOD) % MOD
print(ans)
|
1540478100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nYES\nNO\nYES"]
|
cbd91ac0fc9e4ca01996791e4c94bd6e
|
NoteIn the first test case, $$$s[2\ldots 4] = $$$ "010". In this case $$$s_1s_3s_5$$$ ("001000") and $$$s_2s_3s_6$$$ ("001000") are good suitable subsequences, while $$$s_2s_3s_4$$$ ("001000") is not good. $$$s[1\ldots 3] = $$$ "001". No suitable good subsequence exists. $$$s[3\ldots 5] = $$$ "100". Here $$$s_3s_5s_6$$$ ("001000") is a suitable good subsequence.
|
Hr0d1y has $$$q$$$ queries on a binary string $$$s$$$ of length $$$n$$$. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. For each query, he has to determine whether there exists a good subsequence in $$$s$$$ that is equal to the substring $$$s[l_i\ldots r_i]$$$. A substring $$$s[i\ldots j]$$$ of a string $$$s$$$ is the string formed by characters $$$s_i s_{i+1} \ldots s_j$$$. String $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $$$\ge 2$$$. For example, if $$$s$$$ is "1100110", then the subsequences $$$s_1s_2s_4$$$ ("1100110") and $$$s_1s_5s_7$$$ ("1100110") are good, while $$$s_1s_2s_3$$$ ("1100110") is not good. Can you help Hr0d1y answer each query?
|
For each test case, output $$$q$$$ lines. The $$$i$$$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $$$s[l_i...r_i]$$$, and "NO" otherwise. You may print each letter in any case (upper or lower).
|
The first line of the input contains a single integer $$$t$$$ ($$$1\leq t \leq 100$$$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $$$n$$$ ($$$2 \leq n \leq 100$$$) and $$$q$$$ ($$$1\leq q \leq 100$$$) — the length of the string and the number of queries. The second line contains the string $$$s$$$. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| null |
train_000.jsonl
|
7ba1d2c9acbb3e1bbad4c98bdcb8cc79
|
256 megabytes
|
["2\n6 3\n001000\n2 4\n1 3\n3 5\n4 2\n1111\n1 4\n2 3"]
|
PASSED
|
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from collections import Counter
from math import sqrt, pi, ceil, log, inf, gcd, floor
def main():
for _ in range(int(input())):
n, q = map(int, input().split())
a = input().strip()
for i in range(q):
l, r = map(int, input().split())
k = 0
s = a[l - 1:r]
y = []
for j in range(n):
if s[k] == a[j]:
y.append(j)
k += 1
if k == len(s):
break
if len(y) != len(s):
print("NO")
else:
f = 1
for j in range(len(y) - 1):
if y[j] + 1 != y[j + 1]:
f = 0
break
if f == 0:
print("YES")
else:
if a[y[-1] + 1:].count(s[-1]) >= 1:
print("YES")
else:
print("NO")
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
|
1605969300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1\n4"]
|
6a333044e2ed8f9f4fa44bc16b994418
|
NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.
|
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit. For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.
|
For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_010.jsonl
|
4c96ca28274b9c6a937cefa475333b14
|
256 megabytes
|
["2\n1 2 2 2\n1 1 2 2"]
|
PASSED
|
import math
o=int(input())
for i in range(o):
s=input()
l=s.split()
f1=math.fabs(int(l[0])-int(l[2]))
f2=math.fabs(int(l[1])-int(l[3]))
if int(l[0])!=int(l[2]) and int(l[1])!=int(l[3]):
print(int(2+f1+f2))
else:
print(int(f1+f2))
|
1602939900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["GBGBG", "BBGBGBB", "NO"]
|
2a14f4a526ad2237b897102bfa298003
| null |
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.
|
If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.
|
The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_010.jsonl
|
c99b6d0f4746fae34551c1971ee7a02f
|
256 megabytes
|
["5 1 3 2", "7 2 2 5", "4 3 4 0"]
|
PASSED
|
n, k, a, b = [int(x) for x in input().split()]
s = "NO"
if (int(n / (k+1)) <= min(a, b)):
s = ""
actual = (a >= b)
while(a != b):
v = int(n / (k+1))
if (actual):
m = max(min(k, a - v), 1)
s += "G" * m
a -= m
else:
m = max(min(k, b - v), 1)
s += "B" * m
b -= m
n -= m
actual = not actual
if actual:
s += "GB" * a
else:
s += "BG" * a
print(s)
|
1482057300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nYES\nNO\nYES\nNO"]
|
65a64ea63153fec4d660bad1287169d3
|
NoteIn the first case, you don't need to modify $$$s$$$, since the given $$$s$$$ will bring you to Planetforces.In the second case, you can delete orders $$$s_2$$$, $$$s_3$$$, $$$s_4$$$, $$$s_6$$$, $$$s_7$$$ and $$$s_8$$$, so $$$s$$$ becomes equal to "UR".In the third test case, you have to delete order $$$s_9$$$, otherwise, you won't finish in the position of Planetforces.
|
You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces. Space can be represented as the $$$XY$$$ plane. You are starting at point $$$(0, 0)$$$, and Planetforces is located in point $$$(p_x, p_y)$$$.The piloting system of your spaceship follows its list of orders which can be represented as a string $$$s$$$. The system reads $$$s$$$ from left to right. Suppose you are at point $$$(x, y)$$$ and current order is $$$s_i$$$: if $$$s_i = \text{U}$$$, you move to $$$(x, y + 1)$$$; if $$$s_i = \text{D}$$$, you move to $$$(x, y - 1)$$$; if $$$s_i = \text{R}$$$, you move to $$$(x + 1, y)$$$; if $$$s_i = \text{L}$$$, you move to $$$(x - 1, y)$$$. Since string $$$s$$$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from $$$s$$$ but you can't change their positions.Can you delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces after the system processes all orders?
|
For each test case, print "YES" if you can delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$p_x$$$ and $$$p_y$$$ ($$$-10^5 \le p_x, p_y \le 10^5$$$; $$$(p_x, p_y) \neq (0, 0)$$$) — the coordinates of Planetforces $$$(p_x, p_y)$$$. The second line contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$: $$$|s|$$$ is the length of string $$$s$$$) — the list of orders. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_107.jsonl
|
54344f85c3e889c48a513d917305cd39
|
256 megabytes
|
["6\n10 5\nRRRRRRRRRRUUUUU\n1 1\nUDDDRLLL\n-3 -5\nLDLDLDDDR\n1 2\nLLLLUU\n3 -2\nRDULRLLDR\n-1 6\nRUDURUUUUR"]
|
PASSED
|
t = int(input())
for i in range(1,t+1):
x,y = input().split()
x, y = int(x), int(y)
s = input()
d = ""
if x > 0:
d += x * "R"
if x < 0:
d += abs(x) * "L"
if y > 0:
d += y * "U"
if y < 0:
d += abs(y) * "D"
for i in range(0,len(d)):
if (d[i] in s) == False:
print("NO")
break
else:
s = s[0:s.index(d[i])] + s[s.index(d[i]) + 1:len(s)]
if len(d) - 1 == i:
print("YES")
|
1612535700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4.5 seconds
|
["1", "2", "0"]
|
ba82353e9bc1ee36ed068547d2f4043d
| null |
You are given a tree consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is equal to $$$a_i$$$.Let's denote the function $$$g(x, y)$$$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $$$x$$$ to vertex $$$y$$$ (including these two vertices). Also let's denote $$$dist(x, y)$$$ as the number of vertices on the simple path between vertices $$$x$$$ and $$$y$$$, including the endpoints. $$$dist(x, x) = 1$$$ for every vertex $$$x$$$.Your task is calculate the maximum value of $$$dist(x, y)$$$ among such pairs of vertices that $$$g(x, y) > 1$$$.
|
If there is no pair of vertices $$$x, y$$$ such that $$$g(x, y) > 1$$$, print $$$0$$$. Otherwise print the maximum value of $$$dist(x, y)$$$ among such pairs.
|
The first line contains one integer $$$n$$$ — the number of vertices $$$(1 \le n \le 2 \cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 2 \cdot 10^5)$$$ — the numbers written on vertices. Then $$$n - 1$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ $$$(1 \le x, y \le n, x \ne y)$$$ denoting an edge connecting vertex $$$x$$$ with vertex $$$y$$$. It is guaranteed that these edges form a tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_076.jsonl
|
725234a665a10e2222c41abd77423eb0
|
256 megabytes
|
["3\n2 3 4\n1 2\n2 3", "3\n2 3 4\n1 3\n2 3", "3\n1 1 1\n1 2\n2 3"]
|
PASSED
|
from sys import stdin, stdout
from math import *
from heapq import *
from collections import *
dv=list(range(200002))
for i in range(2,200002):
if ((i*i)>=200002):
break
if (dv[i]==i):
j=i
while ((i*j)<200002):
dv[i*j]=i
j=j+1
def loPr(x):
global dv
if (x<=1):
return []
ret=[]
while(x>1):
d=dv[x]
ret.append(d)
while(x%d==0):
x=trunc(x/d)
return ret
def main():
global dv
n=int(stdin.readline())
a=[0]+[int(x) for x in stdin.readline().split()]
e=[]
for _ in range(n+2):
e.append([])
for _ in range(n-1):
u,v=[int(x) for x in stdin.readline().split()]
e[u].append(v)
e[v].append(u)
pre=[0]*(n+2)
q=[1]
d=[False]*(n+2)
d[1]=True
pre[1]=1
i=0
while(i<len(q)):
u=q[i]
for v in e[u]:
if (d[v]==False):
d[v]=True
pre[v]=u
q.append(v)
i=i+1
f=[dict()]
for _ in range(n+2):
f.append(dict())
b=[[]]
for i in range(1,n+1):
b.append(loPr(a[i]))
for p in b[i]:
f[i][p]=[1]
q.reverse()
res=0
for u in q:
nxt=pre[u]
#print (str(u)+": f=" +str(f[u])+ " b=" +str(b[u]))
for p in b[u]:
fp=f[u].get(p,[1])
fp.sort()
res=max(res,fp[-1])
if (len(fp)>=2):
res=max(res,fp[-1]+fp[-2]-1)
fnxt=f[nxt].get(p,None)
if (fnxt!=None):
fnxt.append(max(1,fp[-1])+1)
stdout.write(str(res))
return 0
if __name__ == "__main__":
main()
|
1547217300
|
[
"number theory",
"trees"
] |
[
0,
0,
0,
0,
1,
0,
0,
1
] |
|
1 second
|
["YES", "NO"]
|
aeda11f32911d256fb6263635b738e99
|
NoteThe first sample: Those near pairs of blue and orange points actually coincide. First, manipulate the first engine: use the second operation with $$$\theta = \pi$$$ (to rotate all power sources $$$180$$$ degrees).The power sources in the first engine become $$$(0, 0)$$$, $$$(0, -2)$$$, and $$$(-2, 0)$$$. Second, manipulate the second engine: use the first operation with $$$a = b = -2$$$.The power sources in the second engine become $$$(-2, 0)$$$, $$$(0, 0)$$$, $$$(0, -2)$$$, and $$$(-1, -1)$$$. You can examine that destroying any point, the power field formed by the two engines are always the solid triangle $$$(0, 0)$$$, $$$(-2, 0)$$$, $$$(0, -2)$$$.In the second sample, no matter how you manipulate the engines, there always exists a power source in the second engine that power field will shrink if you destroy it.
|
After the war, the supersonic rocket became the most common public transportation.Each supersonic rocket consists of two "engines". Each engine is a set of "power sources". The first engine has $$$n$$$ power sources, and the second one has $$$m$$$ power sources. A power source can be described as a point $$$(x_i, y_i)$$$ on a 2-D plane. All points in each engine are different.You can manipulate each engine separately. There are two operations that you can do with each engine. You can do each operation as many times as you want. For every power source as a whole in that engine: $$$(x_i, y_i)$$$ becomes $$$(x_i+a, y_i+b)$$$, $$$a$$$ and $$$b$$$ can be any real numbers. In other words, all power sources will be shifted. For every power source as a whole in that engine: $$$(x_i, y_i)$$$ becomes $$$(x_i \cos \theta - y_i \sin \theta, x_i \sin \theta + y_i \cos \theta)$$$, $$$\theta$$$ can be any real number. In other words, all power sources will be rotated.The engines work as follows: after the two engines are powered, their power sources are being combined (here power sources of different engines may coincide). If two power sources $$$A(x_a, y_a)$$$ and $$$B(x_b, y_b)$$$ exist, then for all real number $$$k$$$ that $$$0 \lt k \lt 1$$$, a new power source will be created $$$C_k(kx_a+(1-k)x_b,ky_a+(1-k)y_b)$$$. Then, this procedure will be repeated again with all new and old power sources. After that, the "power field" from all power sources will be generated (can be considered as an infinite set of all power sources occurred).A supersonic rocket is "safe" if and only if after you manipulate the engines, destroying any power source and then power the engine, the power field generated won't be changed (comparing to the situation where no power source erased). Two power fields are considered the same if and only if any power source in one field belongs to the other one as well.Given a supersonic rocket, check whether it is safe or not.
|
Print "YES" if the supersonic rocket is safe, otherwise "NO". You can print each letter in an arbitrary case (upper or lower).
|
The first line contains two integers $$$n$$$, $$$m$$$ ($$$3 \le n, m \le 10^5$$$) — the number of power sources in each engine. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0\leq x_i, y_i\leq 10^8$$$) — the coordinates of the $$$i$$$-th power source in the first engine. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0\leq x_i, y_i\leq 10^8$$$) — the coordinates of the $$$i$$$-th power source in the second engine. It is guaranteed that there are no two or more power sources that are located in the same point in each engine.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_053.jsonl
|
41a57db03a5726e49a482d24032adbfa
|
256 megabytes
|
["3 4\n0 0\n0 2\n2 0\n0 2\n2 2\n2 0\n1 1", "3 4\n0 0\n0 2\n2 0\n0 2\n2 2\n2 0\n0 0"]
|
PASSED
|
import sys
# > 0 anti-clock, < 0 clockwise, == 0 same line
def orientation(p1, p2, p3):
return (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0])
def dot(p1, p2, p3, p4):
return (p2[0]-p1[0])*(p4[0]-p3[0]) + (p2[1]-p1[1])*(p4[1]-p3[1])
def theta(p1, p2):
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
if abs(dx) < 0.1 and abs(dy) < 0.1:
t = 0
else:
t = dy/(abs(dx) + abs(dy))
if abs(t) < 0.1 ** 10:
t = 0
if dx < 0:
t = 2 - t
elif dy < 0:
t = 4 + t
return t*90
def dist_sq(p1, p2):
return (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1])
def chull(points):
# let 0 element to be smallest, reorder elements
pi = [x for x in range(len(points))]
min_y = points[0][1]
min_x = points[0][0]
min_ind = 0
for i in range(len(points)):
if points[i][1] < min_y or points[i][1] == min_y and points[i][0] < min_x:
min_y = points[i][1]
min_x = points[i][0]
min_ind = i
pi[0] = min_ind
pi[min_ind] = 0
th = [theta(points[pi[0]], points[x]) for x in range(len(points))]
pi.sort(key=lambda x: th[x])
# process equals
unique = [pi[0], pi[1]]
for i in range(2, len(pi)):
if th[pi[i]] != th[unique[-1]]:
unique.append(pi[i])
else:
if dist_sq(points[pi[0]], points[unique[-1]]) < dist_sq(points[pi[0]], points[pi[i]]):
unique[-1] = pi[i] # put max
pi = unique
stack = []
for i in range(min(len(pi), 3)):
stack.append(points[pi[i]])
if len(stack) < 3:
return stack
for i in range(3, len(pi)):
while len(stack) >= 2:
o = orientation(stack[-2], stack[-1], points[pi[i]])
if o > 0:
stack.append(points[pi[i]])
break
elif o < 0:
stack.pop()
else: # ==
if dist_sq(stack[-2], stack[-1]) < dist_sq(stack[-2], points[pi[i]]):
stack.pop()
else:
break # skip i-th point
return stack
def z_func(s):
slen, l, r = len(s), 0, 0
z = [0]*slen
z[0] = slen
for i in range(1, slen):
if i <= r: z[i] = min(r-i+1, z[i-l])
while i+z[i] < slen and s[z[i]] == s[i+z[i]]: z[i] += 1
if i+z[i]-1 > r: l, r = i, i+z[i]-1
return z
n,m = map(int, sys.stdin.readline().strip().split())
a = []
for _ in range(n):
x,y = map(int, sys.stdin.readline().strip().split())
a.append((x, y))
b = []
for _ in range(m):
x, y = map(int, sys.stdin.readline().strip().split())
b.append((x, y))
ah = chull(a)
bh = chull(b)
if len(ah) == len(bh):
if len(ah) == 2:
if dist_sq(ah[0], ah[1]) == dist_sq(bh[0], bh[1]):
print('YES')
else:
print('NO')
else:
da = []
for i in range(len(ah)):
dot_a = dot(ah[i-2], ah[i-1], ah[i-1], ah[i])
da.append((dist_sq(ah[i], ah[i-1]), dot_a))
db = []
for i in range(len(bh)):
dot_b = dot(bh[i - 2], bh[i - 1], bh[i - 1], bh[i])
db.append((dist_sq(bh[i], bh[i-1]), dot_b))
l = r = 0
daab = []
daab.extend(db)
daab.append(-1)
daab.extend(da)
daab.extend(da)
zab = z_func(daab)
found = False
for i in range(len(db)+1, len(daab)-len(db)+1):
if zab[i] == len(db):
found = True
break
if found:
print('YES')
else:
print('NO')
else:
print('NO')
|
1533737100
|
[
"geometry",
"strings"
] |
[
0,
1,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2", "-1"]
|
24a43df3e6d2af348692cdfbeb8a195c
|
NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.
|
Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
|
If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).
|
The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,500 |
train_012.jsonl
|
e13831f19029c448f77cda19924761d9
|
256 megabytes
|
["5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5", "7 4\n2 1\n3 6\n5 1\n1 7"]
|
PASSED
|
n,m=map(int,raw_input().split())
graph=[[False for i in xrange(n+1)]for j in xrange(n+1)]
graph2=[[] for i in xrange(n+1)]
for i in xrange(m):
u,v=map(int,raw_input().split())
graph[u][v]=graph[v][u]=True
graph2[u].append(v)
graph2[v].append(u)
ans=1e999
for u in xrange(1,n+1):
for v in graph2[u]:
for k in graph2[v]:
if graph[u][k]:
ans=min(ans,len(graph2[u])+len(graph2[v])+len(graph2[k])-6)
if ans==1e999:ans=-1
print ans
|
1440865800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["AGACGTCT", "AGCT", "===", "==="]
|
d6423f380e6ba711d175d91e73f97b47
|
NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.
|
The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.
|
If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).
|
The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_033.jsonl
|
29a584a597e5dad49537e256e6f4353d
|
256 megabytes
|
["8\nAG?C??CT", "4\nAGCT", "6\n????G?", "4\nAA??"]
|
PASSED
|
n=input("")
Gene= list(input(""))
l= len(Gene)/4
for i in range(len(Gene)):
if Gene[i]=='?':
if Gene.count("A")!=l:
Gene[i]="A"
elif Gene.count("C")!=l:
Gene[i]="C"
elif Gene.count("G")!=l:
Gene[i]="G"
elif Gene.count("T")!=l:
Gene[i]="T"
if Gene.count("A")==Gene.count("G") and Gene.count("A")==Gene.count("T") and Gene.count("A")==Gene.count("C") and Gene.count("G")==Gene.count("T") and Gene.count("G")==Gene.count("C") and Gene.count("T")==Gene.count("C"):
for i in Gene:
print(i,end="")
else:
print("===")
|
1482113100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["0.57142857142857139685", "-1"]
|
2df45858a638a90d30315844df6d1084
|
NoteHere is a picture of the first samplePoints A, B, C, D - start mice positions, segments are their paths.Then, at first time when all mice will be in rectangle it will be looks like this:Here is a picture of the second samplePoints A, D, B will never enter rectangle.
|
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1, y1) and (x2, y2).Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix, viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.
|
In the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
|
The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of computer mice on the desk. The second line contains four integers x1, y1, x2 and y2 (0 ≤ x1 ≤ x2 ≤ 100 000), (0 ≤ y1 ≤ y2 ≤ 100 000) — the coordinates of the opposite corners of the mousetrap. The next n lines contain the information about mice. The i-th of these lines contains four integers rix, riy, vix and viy, (0 ≤ rix, riy ≤ 100 000, - 100 000 ≤ vix, viy ≤ 100 000), where (rix, riy) is the initial position of the mouse, and (vix, viy) is its speed.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_020.jsonl
|
80f745db8f080782def902190e43c603
|
256 megabytes
|
["4\n7 7 9 8\n3 5 7 5\n7 5 2 4\n3 3 7 8\n6 6 3 2", "4\n7 7 9 8\n0 3 -5 4\n5 0 5 4\n9 9 -1 -6\n10 5 -7 -10"]
|
PASSED
|
rd = lambda: map(int, input().split())
n = int(input())
x1, y1, x2, y2 = rd()
l = []
r = []
m = []
for i in range(n):
t = []
rx, ry, vx, vy = rd()
m.append([rx, ry, vx, vy])
if x1 <= rx <= x2 and y1 <= ry <= y2:
t.append(0)
if vx == 0 and vy == 0:
t.append(0x3f3f3f3f3f3f3f3f)
if vx:
t1 = (x1 - rx) / vx
if t1 >= 0:
if y1 <= ry + t1 * vy <= y2:
t.append(t1)
t1 = (x2 - rx) / vx
if t1 >= 0:
if y1 <= ry + t1 * vy <= y2:
t.append(t1)
if vy:
t1 = (y1 - ry) / vy
if t1 >= 0:
if x1 <= rx + t1 * vx <= x2:
t.append(t1)
t1 = (y2 - ry) / vy
if t1 >= 0:
if x1 <= rx + t1 * vx <= x2:
t.append(t1)
if len(t) < 2:
print(-1)
exit()
t.sort()
l.append(t[0])
r.append(t[-1])
l.sort()
r.sort()
if l[-1] > r[0]:
print(-1)
else:
p = (l[-1] + r[0]) / 2
if not all(x1 < rx + p * vx < x2 and y1 < ry + p * vy < y2 for rx, ry, vx, vy in m):
print(-1)
else:
print(l[-1])
|
1492965900
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4 1 5\n1 2 2\n1000000000 1 1\n6 6 10"]
|
a07c199ca02f0abaab6c73efdb2a5b2d
|
NoteFor the first test case, the best choice is $$$a=4$$$, $$$l=1$$$, $$$r=5$$$, and the game would go as follows. Marian starts with one dollar. After the first round, he ends up with $$$2$$$ dollars because the numbers coincide with the chosen one. After the second round, he ends up with $$$4$$$ dollars because the numbers coincide again. After the third round, he ends up with $$$2$$$ dollars because he guesses $$$4$$$ even though $$$3$$$ is the correct choice. After the fourth round, he ends up with $$$4$$$ dollars again. In the final round, he ends up $$$8$$$ dollars because he again guessed correctly. There are many possible answers for the second test case, but it can be proven that Marian will not end up with more than $$$2$$$ dollars, so any choice with $$$l = r$$$ with the appropriate $$$a$$$ is acceptable.
|
Marian is at a casino. The game at the casino works like this.Before each round, the player selects a number between $$$1$$$ and $$$10^9$$$. After that, a dice with $$$10^9$$$ faces is rolled so that a random number between $$$1$$$ and $$$10^9$$$ appears. If the player guesses the number correctly their total money is doubled, else their total money is halved. Marian predicted the future and knows all the numbers $$$x_1, x_2, \dots, x_n$$$ that the dice will show in the next $$$n$$$ rounds. He will pick three integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$l \leq r$$$). He will play $$$r-l+1$$$ rounds (rounds between $$$l$$$ and $$$r$$$ inclusive). In each of these rounds, he will guess the same number $$$a$$$. At the start (before the round $$$l$$$) he has $$$1$$$ dollar.Marian asks you to determine the integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$1 \leq a \leq 10^9$$$, $$$1 \leq l \leq r \leq n$$$) such that he makes the most money at the end.Note that during halving and multiplying there is no rounding and there are no precision errors. So, for example during a game, Marian could have money equal to $$$\dfrac{1}{1024}$$$, $$$\dfrac{1}{128}$$$, $$$\dfrac{1}{2}$$$, $$$1$$$, $$$2$$$, $$$4$$$, etc. (any value of $$$2^t$$$, where $$$t$$$ is an integer of any sign).
|
For each test case, output three integers $$$a$$$, $$$l$$$, and $$$r$$$ such that Marian makes the most amount of money gambling with his strategy. If there are multiple answers, you may output any of them.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2\cdot 10^5$$$) — the number of rounds. The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^9$$$), where $$$x_i$$$ is the number that will fall on the dice in the $$$i$$$-th round. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_096.jsonl
|
cefedd04c6e37082f0e70005a9833e24
|
256 megabytes
|
["4\n\n5\n\n4 4 3 4 4\n\n5\n\n11 1 11 1 11\n\n1\n\n1000000000\n\n10\n\n8 8 8 9 9 6 6 9 6 6"]
|
PASSED
|
#!/usr/bin/env python3
import sys
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline # to read input quickly
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
m9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
# d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = sys.maxsize
e18 = 10**18 + 10
# if testing locally, print to terminal with a different color
CHECK_OFFLINE_TEST = True
# CHECK_OFFLINE_TEST = False # uncomment this on Codechef
if CHECK_OFFLINE_TEST:
import getpass
OFFLINE_TEST = getpass.getuser() == "htong"
def log(*args):
if CHECK_OFFLINE_TEST and OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def read_strings(rows):
return [input().strip() for _ in range(rows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def solve_(arr):
# your solution here
g = defaultdict(list)
for i,x in enumerate(arr):
g[str(x)].append(i)
maxres = 0
ares = arr[0]
lres = 0
rres = 0
# log(g)
for element in g:
# brr = [ for i,x in enumerate(brr)]
# log(element, brr)
minprev = 10**10
left = 0
for i,x in enumerate(g[element]):
val,right = (2*i-x,x)
if val - minprev > maxres:
maxres = val - minprev
ares = element
lres = left
rres = right
if val < minprev:
minprev = val
left = right
log(maxres)
return ares, lres+1, rres+1
# for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
for case_num in range(int(input())):
# read line as an integer
k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# arr = input().split()
# read one line and parse each word as an integer
# a,b,c = list(map(int,input().split()))
arr = list(map(int,input().split()))
# arr = minus_one(arr)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
# mrr = read_matrix(k) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
res = solve(arr) # include input here
# print length if applicable
# print(len(res))
# parse result
res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
# res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
|
1655217300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2", "1"]
|
cf1eb164c4c970fd398ef9e98b4c07b1
|
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
|
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
|
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
|
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
|
standard output
|
standard input
|
Python 2
|
Python
| 900 |
train_003.jsonl
|
98236d01d326228228aca13f322600c9
|
256 megabytes
|
["5\na aa aaa ab abb", "3\namer arem mrea"]
|
PASSED
|
n = int(raw_input().strip())
x = raw_input().split(' ')
res = len(set([''.join(sorted(set(i))) for i in x]))
print res
|
1525183500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["391 0\n0 6 1 3 5\n0"]
|
f18a5fa0b2e7e96cb5994b7b2dbe0189
|
NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$.
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following: Set $$$d$$$ to be the maximum value of your array. For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!
|
For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.
|
Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) – the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ – the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_020.jsonl
|
218b099d0e20e60926872927b7b7159a
|
256 megabytes
|
["3\n2 1\n-199 192\n5 19\n5 -1 4 2 0\n1 2\n69"]
|
PASSED
|
t=int(input())
for i in range(0,t):
n,k=map(int,input().split())
ls=list(map(int,input().rstrip().split()))
if(k%2==1):
maxx=ls[0]
for l in range(0,n):
if ls[l]>maxx:
maxx=ls[l]
for l in range(0,n):
ls[l]=maxx-ls[l]
else:
j=0
while(j<=1):
maxx=ls[0]
for l in range(0,n):
if ls[l]>maxx:
maxx=ls[l]
for l in range(0,n):
ls[l]=maxx-ls[l]
j=j+1
for j in ls:
print(j,end=" ")
print(" ")
|
1597588500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["19.0000000000", "-1"]
|
8eda3e355d2823b0c8f92e1628dc1b69
| null |
Vasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with n trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect.There is a huge enemy laser far away from Vasya. The laser charges for a seconds, and then shoots continuously for b seconds. Then, it charges for a seconds again. Then it shoots continuously for b seconds again and so on. Vasya knows numbers a and b. He also knows that while the laser is shooting, Vasya must be in the trench, but while the laser is charging, Vasya can safely move around the field. The main thing is to have time to hide in the trench before the shot. If Vasya reaches the trench exactly at the moment when the laser starts shooting, we believe that Vasya managed to hide. Coincidentally, the length of any trench in meters numerically does not exceed b.Initially, Vasya is at point A. He needs to get to point B. Vasya moves at speed 1 meter per second in either direction. You can get in or out of the trench at any its point. Getting in or out of the trench takes no time. It is also possible to move in the trench, without leaving it.What is the minimum time Vasya needs to get from point A to point B, if at the initial time the laser has just started charging? If Vasya cannot get from point A to point B, print -1. If Vasya reaches point B at the moment when the laser begins to shoot, it is believed that Vasya managed to reach point B.
|
If Vasya can get from point A to point B, print the minimum time he will need for it. Otherwise, print number -1. The answer will be considered correct if the absolute or relative error does not exceed 10 - 4
|
The first line contains two space-separated integers: a and b (1 ≤ a, b ≤ 1000), — the duration of charging and the duration of shooting, in seconds. The second line contains four space-separated integers: Ax, Ay, Bx, By ( - 104 ≤ Ax, Ay, Bx, By ≤ 104) — the coordinates of points А and B. It is guaranteed that points A and B do not belong to any trench. The third line contains a single integer: n (1 ≤ n ≤ 1000), — the number of trenches. Each of the following n lines contains four space-separated integers: x1, y1, x2, y2 ( - 104 ≤ xi, yi ≤ 104) — the coordinates of ends of the corresponding trench. All coordinates are given in meters. It is guaranteed that for any trench either x1 = x2, or y1 = y2. No two trenches intersect. The length of any trench in meters doesn't exceed b numerically.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_061.jsonl
|
3352b1902067fa6b8c0010b33c65bc73
|
256 megabytes
|
["2 4\n0 5 6 5\n3\n0 0 0 4\n1 1 4 1\n6 0 6 4", "5 10\n0 0 10 10\n1\n5 0 5 9"]
|
PASSED
|
import math
R = lambda: map(int, raw_input().split())
a, b = R()
Ax, Ay, Bx, By = R()
n = R()[0]
x1, y1, x2, y2 = [Ax],[Ay],[Ax],[Ay]
for i in range(n):
_t1, _t2, _t3, _t4 = R()
if (_t1 > _t3): _t1, _t3 = _t3, _t1
if (_t2 > _t4):_t2, _t4 = _t4, _t2
x1.append(_t1)
y1.append(_t2)
x2.append(_t3)
y2.append(_t4)
x1.append(Bx)
y1.append(By)
x2.append(Bx)
y2.append(By)
kc = lambda x1, y1, x2, y2: (x1 - x2)**2 + (y1-y2)**2
kc2 = lambda x, y: x*x + y*y
def can_go2(i, j):
d = min(kc(x1[i],y1[i], x1[j], y1[j]), kc(x1[i],y1[i], x2[j], y2[j]), kc(x1[i],y1[i], x1[j], y2[j]), kc(x1[i],y1[i], x2[j], y1[j]),
kc(x1[i],y2[i], x1[j], y1[j]), kc(x1[i],y2[i], x2[j], y2[j]), kc(x1[i],y2[i], x1[j], y2[j]), kc(x1[i],y2[i], x2[j], y1[j]),
kc(x2[i],y1[i], x1[j], y1[j]), kc(x2[i],y1[i], x2[j], y2[j]), kc(x2[i],y1[i], x1[j], y2[j]), kc(x2[i],y1[i], x2[j], y1[j]),
kc(x2[i],y2[i], x1[j], y1[j]), kc(x2[i],y2[i], x2[j], y2[j]), kc(x2[i],y2[i], x1[j], y2[j]), kc(x2[i],y2[i], x2[j], y1[j]))
if (x1[i]-x1[j]) * (x2[j]-x1[i]) >= 0 or (x2[i] - x1[j]) * (x2[j] - x2[i]) >=0:
d = min(d, math.fabs(y1[i] - y2[j]), math.fabs(y1[i] - y1[j]), math.fabs(y2[i] - y1[j]), math.fabs(y2[i] - y2[j]))
if (y1[i]-y1[j]) * (y2[j]-y1[i]) >= 0 or (y2[i] - y1[j]) * (y2[j] - y2[i]) >=0:
d = min(d, math.fabs(x1[i] - x2[j]), math.fabs(x1[i] - x1[j]), math.fabs(x2[i] - x1[j]), math.fabs(x2[i] - x2[j]))
if d <= a ** 2: return d
else: return 0
def can_go(i, j):
d = kc2(max(0, max(x1[i],x1[j]) - min(x2[i], x2[j])), max(0, max(y1[i], y1[j]) - min(y2[i], y2[j])))
if d <= a ** 2: return d
else: return 0
dres = [-1 for i in range(0, n+2)]
dres[0] = 0
q = [0]
first, last = 0, 0
while first <= last:
i = q[first]
#print "BFS from %d" % i
first += 1
for j in range(1, n+1):
if dres[j] == -1:
if can_go(i, j) > 0:
#print "---Visit %d" % j
last += 1
q.append(j)
dres[j] = dres[i] + 1
res = 1000000000.0
if can_go(0, n + 1) > 0: res = math.sqrt(kc(Ax, Ay, Bx, By))
for i in range(1, n + 1):
if dres[i] > 0:
tmp = can_go(i, n + 1)
if tmp > 0: res = min(res, dres[i] * (a + b) + math.sqrt(tmp))
if res == 1000000000.0: print "-1"
else: print "%.10f" % res
|
1335280200
|
[
"geometry",
"graphs"
] |
[
0,
1,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n6\n1"]
|
e5244179b8ef807b1c6abfe113bd4f3b
|
NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.
|
You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.
|
For each test case print one integer — the number of good subarrays of the array $$$a$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_025.jsonl
|
587654258f0454e11c17216cc06713cb
|
256 megabytes
|
["3\n3\n120\n5\n11011\n6\n600005"]
|
PASSED
|
from sys import stdin,stdout
for _ in range(int(stdin.readline())):
n=int(stdin.readline())
# a=list(map(int,stdin.readline().split()))
a=[int(ch)-1 for ch in input()]
s=ans=0;d={0:1}
for v in a:
s+=v
ans+=d.get(s,0)
d[s]=d.get(s,0)+1
print(ans)
|
1597415700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n23\n19\n6\n26"]
|
4841cbc3d3ef29929690b78e30fbf22e
|
NoteFor the first test case, Atilla needs to know only the character $$$\texttt{a}$$$, so the alphabet of size $$$1$$$ which only contains $$$\texttt{a}$$$ is enough.For the second test case, Atilla needs to know the characters $$$\texttt{d}$$$, $$$\texttt{o}$$$, $$$\texttt{w}$$$, $$$\texttt{n}$$$. The smallest alphabet size that contains all of them is $$$23$$$ (such alphabet can be represented as the string $$$\texttt{abcdefghijklmnopqrstuvw}$$$).
|
In order to write a string, Atilla needs to first learn all letters that are contained in the string.Atilla needs to write a message which can be represented as a string $$$s$$$. He asks you what is the minimum alphabet size required so that one can write this message.The alphabet of size $$$x$$$ ($$$1 \leq x \leq 26$$$) contains only the first $$$x$$$ Latin letters. For example an alphabet of size $$$4$$$ contains only the characters $$$\texttt{a}$$$, $$$\texttt{b}$$$, $$$\texttt{c}$$$ and $$$\texttt{d}$$$.
|
For each test case, output a single integer — the minimum alphabet size required to so that Atilla can write his message $$$s$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters.
|
standard output
|
standard input
|
Python 2
|
Python
| 800 |
train_101.jsonl
|
3eb0e5971c25df234b921d942fc87dfa
|
256 megabytes
|
["5\n\n1\n\na\n\n4\n\ndown\n\n10\n\ncodeforces\n\n3\n\nbcf\n\n5\n\nzzzzz"]
|
PASSED
|
import sys
raw_input = iter(sys.stdin.read().splitlines()).next
def solution():
n = int(raw_input())
s = raw_input()
return ord(max(s))-ord('a')+1
for case in xrange(int(raw_input())):
print '%s' % solution()
|
1669041300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["3", "1", "1"]
|
1254d7ee968ed89a229e02ccefaf5994
|
NoteFor example $$$1$$$, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than $$$3$$$ operations, and as such the answer is $$$3$$$. Here is the puzzle from the first example. For example $$$2$$$, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is $$$1$$$. Here is the puzzle from the second example. For example $$$3$$$, by disturbing the cell on the top row and rightmost column, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than $$$1$$$ operation, and as such the answer is $$$1$$$. Here is the puzzle from the third example.
|
This is the hard version of the problem. The difference between the versions is the constraints on $$$a_i$$$. You can make hacks only if all versions of the problem are solved.Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with $$$n$$$ rows and $$$m$$$ columns of cells, some empty and some filled with blocks of sand, and $$$m$$$ non-negative integers $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). In this version of the problem, $$$a_i$$$ will always be not greater than the number of blocks of sand in column $$$i$$$.When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell $$$(i,j)$$$ will pass through all cells below and including the cell $$$(i,j)$$$ within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell $$$(i,j)$$$ are defined as $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$, and $$$(i,j+1)$$$ (if they are within the grid). Note that the newly falling blocks can disturb other blocks.In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least $$$a_i$$$ blocks of sand counted in the $$$i$$$-th sand counter for each column from $$$1$$$ to $$$m$$$.You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.
|
Print one non-negative integer, the minimum amount of operations needed to solve the puzzle.
|
The first line consists of two space-separated positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$). Each of the next $$$n$$$ lines contains $$$m$$$ characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand. The final line contains $$$m$$$ non-negative integers $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, $$$a_i$$$ will always be not greater than the number of blocks of sand in column $$$i$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 3,000 |
train_091.jsonl
|
564b5149bfdefab0343980c38cb23bd6
|
512 megabytes
|
["5 7\n#....#.\n.#.#...\n#....#.\n#....##\n#.#....\n4 1 1 1 0 3 1", "3 3\n#.#\n#..\n##.\n3 1 1", "7 5\n.#..#\n#....\n..##.\n..##.\n..###\n..#..\n#.##.\n0 0 2 4 2"]
|
PASSED
|
import itertools
import math
from math import inf
def readline():
return map(int, input().split())
def blocks(bits):
start = None
for (i, bit) in enumerate(itertools.chain(bits, [False])):
if bit and start is None:
start = i
if not bit and start is not None:
yield (start, i)
start = None
def test_blocks():
assert list(blocks([0, 0, 0])) == []
assert list(blocks([0, 1, 1])) == [(1, 3)]
assert list(blocks([1, 1])) == [(0, 2)]
assert list(blocks([0, 1, 1, 0, 0, 1, 1, 0])) == [(1, 3), (5, 7)]
def cut(iterable):
for (a, b, __) in iterable:
yield (a, b)
def magic_blocks(blocks, prev_blocks, annotate_w=False):
if annotate_w:
blocks = ((a, b, b-a) for (a, b) in blocks)
glue = itertools.chain(prev_blocks, [(inf, inf)])
gb, ge = -inf, -inf
ma, mb, weight = None, None, 0
for (a, b, w) in itertools.chain(blocks, [(inf, inf, inf)]):
if ma is None:
ma, mb, weight = a, b, w
continue
while ge <= a and ge < inf:
gb, ge = next(glue)
if gb < mb:
mb = b
weight += w
else:
# assert math.isfinite(weight)
yield ma, mb, weight
ma, mb, weight = a, b, w
def test_magic_blocks():
blocks = ((0, 2), (4, 7), (10, 15))
def tcut(mb):
return tuple(cut(mb))
assert tcut(magic_blocks(blocks, [])) == blocks
assert tcut(magic_blocks(blocks, [(2, 4)])) == blocks
assert tcut(magic_blocks(blocks, [(1, 4)])) == blocks
assert tcut(magic_blocks(blocks, [(1, 5)])) == ((0, 7), (10, 15))
assert tcut(magic_blocks(blocks, [(1, 10)])) == ((0, 7), (10, 15))
assert tcut(magic_blocks(blocks, [(1, 11)])) == ((0, 15),)
assert tcut(magic_blocks(blocks, [(1, 2), (3, 4), (7, 10)])) == blocks
assert tcut(magic_blocks(blocks, [(1, 2), (3, 4), (6, 100)])) == ((0, 2), (4, 15))
assert tcut(magic_blocks(blocks, [(7, 100), (101, 104)])) == blocks
assert tcut(magic_blocks((), [(7, 100), (101, 104)])) == ()
unset = object()
def debug(*args):
import sys
print(*args, file=sys.stderr)
def solve_1(seq, a):
ans = 0
t = False
for (is_sand, ai) in zip(seq, a):
if not is_sand:
t = False
if ai:
assert is_sand
if not t:
ans += 1
t = True
print(ans)
def main():
n, m = readline()
s = [
[ch == '#' for ch in input()]
for __ in range(n)
]
# assert all(len(row) == m for row in s)
a = list(readline())
ans = 0
if n == 1:
solve_1(s[0], a)
return
m_blocks = [()]
for i in range(m):
sb = (blocks(row[i] for row in reversed(s)))
m_blocks.append(tuple(magic_blocks(sb, cut(m_blocks[-1]), annotate_w=True)))
m_blocks.pop(0)
m_blocks.append(())
for i in range(m, 0, -1):
m_blocks[i-1] = tuple(magic_blocks(m_blocks[i-1], cut(m_blocks[i])))
c = None
f = -1
for i in range(m):
sand = a[i]
next_c = unset
next_f = -1
top = -1
for (from_, to, weight) in m_blocks[i]:
top = to - 1
if from_ <= f:
next_f = top
sand -= weight
if sand > 0:
continue
if c is not None and c > top:
continue
if next_c is unset:
next_c = from_
assert sand <= 0
if next_c is not unset and (c is not None or a[i] and next_c > f):
if c is None:
ans += 1
c = next_c
f = top
else:
c = None
f = next_f
# debug('cf', c, f)
print(ans)
if __name__ == '__main__':
main()
|
1623598500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["Yes\n1\n1 4", "No", "Yes\n4\n1 2\n1 3\n1 4\n1 5"]
|
0a476638c2122bfb236b53742cf8a89d
|
NoteThe tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree.The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
|
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
|
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
|
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_031.jsonl
|
50c70d8441dd5ff28a892026a9aa91bb
|
256 megabytes
|
["4\n1 2\n2 3\n3 4", "6\n1 2\n2 3\n3 4\n2 5\n3 6", "5\n1 2\n1 3\n1 4\n1 5"]
|
PASSED
|
n = int(input())
deg = [0]*100005
leaves = []
for i in range(1,n):
a,b = map(int, input().split())
deg[a]+=1
deg[b]+=1
cnt = 0
mxdeg = 0
root = 0
for j in range(1,n+1):
if deg[j]>mxdeg:
mxdeg = deg[j]
root = j
if deg[j] == 1:
leaves.append(j)
if deg[j] > 2:
cnt+=1
if cnt>1:
print("No")
exit()
print("Yes")
m = 0
for it in leaves:
if it != root:
m+=1
print(m)
for it2 in leaves:
if it2 != root:
print(root,it2)
|
1527432600
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1\nAE", "-1", "2\nAAE"]
|
94e58f3f7aa4d860b95d34c7c9f89058
|
NoteFor the first test, the statement $$$\forall x_1, \exists x_2, x_1<x_2$$$ is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.For the third test, the statement $$$\forall x_1, \forall x_2, \exists x_3, (x_1<x_3)\land (x_2<x_3)$$$ is true: We can set $$$x_3=\max\{x_1,x_2\}+1$$$.
|
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($$$\forall$$$) and existential ($$$\exists$$$). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: $$$\forall x,x<100$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is less than $$$100$$$. This statement is false. $$$\forall x,x>x-1$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is greater than $$$x-1$$$. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: $$$\exists x,x<100$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is less than $$$100$$$. This statement is true. $$$\exists x,x>x-1$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is greater than $$$x-1$$$. This statement is true. Moreover, these quantifiers can be nested. For example: $$$\forall x,\exists y,x<y$$$ is read as: for all real numbers $$$x$$$, there exists a real number $$$y$$$ such that $$$x$$$ is less than $$$y$$$. This statement is true since for every $$$x$$$, there exists $$$y=x+1$$$. $$$\exists y,\forall x,x<y$$$ is read as: there exists a real number $$$y$$$ such that for all real numbers $$$x$$$, $$$x$$$ is less than $$$y$$$. This statement is false because it claims that there is a maximum real number: a number $$$y$$$ larger than every $$$x$$$. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are $$$n$$$ variables $$$x_1,x_2,\ldots,x_n$$$, and you are given some formula of the form $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), $$$$$$where $$$\land$$$ denotes logical AND. That is, $$$f(x_1,\ldots, x_n)$$$ is true if every inequality $$$x_{j_i}<x_{k_i}$$$ holds. Otherwise, if at least one inequality does not hold, then $$$f(x_1,\ldots,x_n)$$$ is false.Your task is to assign quantifiers $$$Q_1,\ldots,Q_n$$$ to either universal ($$$\forall$$$) or existential ($$$\exists$$$) so that the statement $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if $$$f(x_1,x_2):=(x_1<x_2)$$$ then you are not allowed to make $$$x_2$$$ appear first and use the statement $$$\forall x_2,\exists x_1, x_1<x_2$$$. If you assign $$$Q_1=\exists$$$ and $$$Q_2=\forall$$$, it will only be interpreted as $$$\exists x_1,\forall x_2,x_1<x_2$$$.
|
If there is no assignment of quantifiers for which the statement is true, output a single integer $$$-1$$$. Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers. On the next line, output a string of length $$$n$$$, where the $$$i$$$-th character is "A" if $$$Q_i$$$ should be a universal quantifier ($$$\forall$$$), or "E" if $$$Q_i$$$ should be an existential quantifier ($$$\exists$$$). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$) — the number of variables and the number of inequalities in the formula, respectively. The next $$$m$$$ lines describe the formula. The $$$i$$$-th of these lines contains two integers $$$j_i$$$,$$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,600 |
train_004.jsonl
|
67c0321099415a106a7927e599fd0948
|
256 megabytes
|
["2 1\n1 2", "4 3\n1 2\n2 3\n3 1", "3 2\n1 3\n2 3"]
|
PASSED
|
import sys
range = xrange
input = raw_input
def toposort(graph):
res = []; found = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# Check for cycle
for node in res:
if any(found[nei] for nei in graph[node]):
return None
found[node] = 0
return res[::-1]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
coupl1 = [[] for _ in range(n)]
coupl2 = [[] for _ in range(n)]
for _ in range(m):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl1[u].append(v)
coupl2[v].append(u)
order = toposort(coupl1)
if order is None:
print -1
sys.exit()
seen1 = list(range(n))
seen2 = list(range(n))
for node in order:
for nei in coupl1[node]:
seen1[nei] = min(seen1[node], seen1[nei])
for node in reversed(order):
for nei in coupl2[node]:
seen2[nei] = min(seen2[node], seen2[nei])
seen = [+(seen1[node] == seen2[node] == node) for node in range(n)]
print sum(seen)
print ''.join('A' if c else 'E' for c in seen)
|
1588775700
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\n0 0\n1 0\n0 1\n2 0\n1 -1\n-1 1\n0 2", "NO", "YES\n3 3\n4 3\n5 3\n6 3"]
|
1ee7ec135d957db2fca0aa591fc44b16
|
NoteIn the first sample one of the possible positions of tree is:
|
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value.
|
If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them.
|
The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree. Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_069.jsonl
|
52d546f4ca5d5d47a31d2168aeb37c12
|
256 megabytes
|
["7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7", "6\n1 2\n2 3\n2 4\n2 5\n2 6", "4\n1 2\n2 3\n3 4"]
|
PASSED
|
#https://codeforces.com/problemset/problem/761/E
def solve():
def push(u, v, g):
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
n = int(input())
g = {}
for _ in range(n-1):
u, v = map(int, input().split())
push(u, v, g)
for u in g:
if len(g[u]) > 4:
return 'NO', None
d = {}
build(1, 0, 0, 0, 31, -1, d, g)
s = ''
for u in range(1, n+1):
x, y = d[u]
s += str(x) + ' ' + str(y)
s += '\n'
return 'YES', s
def cal_pos(dir_, cur_x, cur_y, cur_base):
if dir_ == 0:
return cur_x, cur_y + (1<<cur_base)
elif dir_ == 1:
return cur_x + (1<<cur_base), cur_y
elif dir_ == 2:
return cur_x, cur_y - (1<<cur_base)
else:
return cur_x - (1<<cur_base), cur_y
def build(u, p, cur_x, cur_y, cur_base, pre_dir, d, g):
d[u] = [cur_x, cur_y]
type_ = [0,1,2,3]
if pre_dir in type_:
type_.remove(pre_dir)
if u in g:
for v in g[u]:
if v != p:
dir_ = type_.pop()
next_x, next_y = cal_pos(dir_, cur_x, cur_y, cur_base)
build(v, u, next_x, next_y, cur_base-1, (dir_ - 2)%4, d, g)
ans ,s = solve()
if ans == 'NO':
print(ans)
else:
print(ans)
print(s)
|
1485873300
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["1 4 2 3 5 6 \n1 2 3 4 \n-1\n5 6 3 4 1 2 \n-1\n1 8 6 7 2 4 3 5"]
|
c2db558ecf921161ab4da003bd393ec7
|
NoteThe first test case is parsed in the problem statement.
|
A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.For a permutation $$$p$$$ of even length $$$n$$$ you can make an array $$$b$$$ of length $$$\frac{n}{2}$$$ such that: $$$b_i = \max(p_{2i - 1}, p_{2i})$$$ for $$$1 \le i \le \frac{n}{2}$$$ For example, if $$$p$$$ = [$$$2, 4, 3, 1, 5, 6$$$], then: $$$b_1 = \max(p_1, p_2) = \max(2, 4) = 4$$$ $$$b_2 = \max(p_3, p_4) = \max(3,1)=3$$$ $$$b_3 = \max(p_5, p_6) = \max(5,6) = 6$$$ As a result, we made $$$b$$$ = $$$[4, 3, 6]$$$.For a given array $$$b$$$, find the lexicographically minimal permutation $$$p$$$ such that you can make the given array $$$b$$$ from it.If $$$b$$$ = [$$$4,3,6$$$], then the lexicographically minimal permutation from which it can be made is $$$p$$$ = [$$$1,4,2,3,5,6$$$], since: $$$b_1 = \max(p_1, p_2) = \max(1, 4) = 4$$$ $$$b_2 = \max(p_3, p_4) = \max(2, 3) = 3$$$ $$$b_3 = \max(p_5, p_6) = \max(5, 6) = 6$$$ A permutation $$$x_1, x_2, \dots, x_n$$$ is lexicographically smaller than a permutation $$$y_1, y_2 \dots, y_n$$$ if and only if there exists such $$$i$$$ ($$$1 \le i \le n$$$) that $$$x_1=y_1, x_2=y_2, \dots, x_{i-1}=y_{i-1}$$$ and $$$x_i<y_i$$$.
|
For each test case, print on a separate line: lexicographically minimal permutation $$$p$$$ such that you can make an array $$$b$$$ from it; or a number -1 if the permutation you are looking for does not exist.
|
The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$\frac{n}{2}$$$ integers $$$b_i$$$ ($$$1 \le b_i \le n$$$) — elements of array $$$b$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_085.jsonl
|
d29358a55d6d4b859d3c787bbdcd35fd
|
256 megabytes
|
["6\n\n6\n\n4 3 6\n\n4\n\n2 4\n\n8\n\n8 7 2 3\n\n6\n\n6 4 2\n\n4\n\n4 4\n\n8\n\n8 7 4 5"]
|
PASSED
|
import collections
import math
import bisect
import sys
import heapq
import itertools
#import functools
def solve():
n = int(input())
arr = [int(i) for i in sys.stdin.readline().split()]
dic = {}
for i, num in enumerate(arr):
dic[num] = i
if len(dic) != n // 2 or n not in dic:
print(-1)
return
output = [-1] * n
for num in dic:
output[dic[num] * 2 + 1] = num
h = []
for num in range(n, 0, -1):
if num in dic:
heapq.heappush(h, -dic[num] * 2)
elif not h:
print(-1)
return
else:
output[-heapq.heappop(h)] = num
print(' '.join(map(str, output)))
t = int(input())
for _ in range(t):
solve()
|
1668782100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["Utkarsh\nAshish\nUtkarsh\nUtkarsh\nAshish"]
|
d4d41e75c68ce5e94c92e1b9876891bf
|
NoteIn the first test case, one possible sequence of moves can be$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.Ashish has no moves left, so Utkarsh wins.
|
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at $$$(0,0)$$$. In one move a player must increase either the $$$x$$$ coordinate or the $$$y$$$ coordinate of the token by exactly $$$k$$$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $$$d$$$ from $$$(0,0)$$$.In other words, if after a move the coordinates of the token are $$$(p,q)$$$, then $$$p^2 + q^2 \leq d^2$$$ must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.
|
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes).
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The only line of each test case contains two space separated integers $$$d$$$ ($$$1 \leq d \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq d$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| null |
train_021.jsonl
|
1c221cb4e56c5aaad964ef9a7a5cd759
|
256 megabytes
|
["5\n2 1\n5 2\n10 3\n25 4\n15441 33"]
|
PASSED
|
t = int(input())
for i in range(t):
n,k=map(int,input().split())
x = int((n / k)/2**0.5)
a = (x+1)**2 + (x)**2
b = (n/k)**2
if a >b:
print('Utkarsh')
else:
print('Ashish')
|
1605969300
|
[
"geometry",
"math",
"games"
] |
[
1,
1,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["YES\n2\n1 4\n4\n5 3 2 1\n5\n4 1 2 3 5", "NO\n2"]
|
8c06963c45469f638a1c7c4769295be9
|
NoteHere is what the queries look like for the first test case (red corresponds to the 1st query, blue 2nd query, and green 3rd query): Notice that every edge in the graph is part of either $$$0$$$ or $$$2$$$ colored query edges.The graph in the second test case looks like this: There does not exist an assignment of paths that will force all edges to have even weights with the given queries. One must add at least $$$2$$$ new queries to obtain a set of queries that can satisfy the condition.
|
She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of $$$n$$$ nodes with $$$m$$$ edges. You also have $$$q$$$ queries. Each query consists of two nodes $$$a$$$ and $$$b$$$.Initially, all edges in the graph have a weight of $$$0$$$. For each query, you must choose a simple path starting from $$$a$$$ and ending at $$$b$$$. Then you add $$$1$$$ to every edge along this path. Determine if it's possible, after processing all $$$q$$$ queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed $$$10^{18}$$$ under the given constraints.A simple path is defined as any path that does not visit a node more than once.An edge is said to have an even weight if its value is divisible by $$$2$$$.
|
If it is possible to force all edge weights to be even, print "YES" on the first line, followed by $$$2q$$$ lines indicating the choice of path for each query in the same order the queries are given. For each query, the first line should contain a single integer $$$x$$$: the number of nodes in the chosen path. The next line should then contain $$$x$$$ spaced separated integers $$$p_i$$$ indicating the path you take ($$$p_1 = a, p_x = b$$$ and all numbers should fall between $$$1$$$ and $$$n$$$). This path cannot contain duplicate nodes and must be a valid simple path in the graph. If it is impossible to force all edge weights to be even, print "NO" on the first line and the minimum number of added queries on the second line.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$, $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2}, 3 \cdot 10^5\right)}$$$). Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x, y \leq n$$$, $$$x\neq y$$$) indicating an undirected edge between node $$$x$$$ and $$$y$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 3 \cdot 10^5$$$). Each of the next $$$q$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq n, a \neq b$$$), the description of each query. It is guaranteed that $$$nq \leq 3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_087.jsonl
|
fb387101b53d97c89a12905bb41874ad
|
512 megabytes
|
["6 7\n2 1\n2 3\n3 5\n1 4\n6 1\n5 6\n4 5\n3\n1 4\n5 1\n4 5", "5 7\n4 3\n4 5\n2 1\n1 4\n1 3\n3 5\n3 2\n4\n4 2\n3 5\n5 1\n4 5"]
|
PASSED
|
import sys
input=sys.stdin.readline
def unionfind(u):
v=u
while u!=parent[u]:
u=parent[u]
while v!=u:
w=parent[v]
parent[v]=u
v=parent[w]
return u
def path(u,v):
s=[u]
pre=[-1]*(n+1)
pre[u]=u
while s:
x=s.pop()
for y in g[x]:
if pre[y]>=0:
continue
pre[y]=x
s.append(y)
ans=[v]
while ans[-1]!=u:
ans.append(pre[ans[-1]])
return ans[::-1]
n,m=map(int,input().split())#30w 30w
g=[[] for i in range(n+1)]
parent=[i for i in range(n+1)]
for i in range(m):
u, v = map(int, input().split())
root1,root2=unionfind(u),unionfind(v)
if root1==root2:
continue
parent[max(root1,root2)]=min(root1,root2)
g[u].append(v)
g[v].append(u)
l=len(g)
q=int(input())#n*q 30w
query=[]
d={}
for i in range(q):
a,b=map(int,input().split())
query.append([a,b])
if a in d:
del d[a]
else:
d[a]=1
if b in d:
del d[b]
else:
d[b]=1
if len(d)>0:
print("NO")
print(len(d)//2)
else:
print("YES")
for i in range(q):
ans=path(query[i][0],query[i][1])
print(len(ans))
print(" ".join(map(str,ans)))
|
1634468700
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["aa", "abca"]
|
c01fc2cb6efc7eef290be12015f8d920
|
NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".
|
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".
|
Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.
|
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_020.jsonl
|
4d11c7f5103873c1181250dba643b83f
|
256 megabytes
|
["3\naaa", "5\nabcda"]
|
PASSED
|
n = int(input())
s = input()
min = n - 1
for i in range(n - 1):
if s[i] > s[i + 1]:
min = i
break
print(s[:min] + s[min + 1:])
|
1542033300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2 4 1 2 \n1 3"]
|
3342e71884677534b7a126f89d441585
|
NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.
|
You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.
|
For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.
|
The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_084.jsonl
|
26fc8dcabda715685cbd10dd07636f9c
|
256 megabytes
|
["2\n4\n4 2 1 2\n2\n3 1"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
res=[]
a = list(map(int,input().split()))
a.sort()
last=0
first = 0
minn=1e9
first,last = 0,0
for i in range(1,n):
if a[i]==a[i-1]:
first,last = a[i],a[i]
ind=i
ind2=i-1
break
if minn>(a[i]-a[i-1]):
minn = a[i]-a[i-1]
first = a[i-1]
last = a[i]
ind=i
ind2=i-1
res.append(first)
for i in range(ind+1,n):
res.append(a[i])
for i in range(ind2):
res.append(a[i])
res.append(last)
print(*res)
|
1624026900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0\n1\n3\n3"]
|
4f8eac547bbd469a69de2f4aae4a87f0
|
NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,1$$$.
|
Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?
|
For each test case, print one integer — the minimal value of the maximum value in the sequence.
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — 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 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 900 |
train_095.jsonl
|
ccee34b56e6d91baebf9d6c0a2d73673
|
256 megabytes
|
["4\n2\n1 2\n3\n1 1 3\n4\n3 11 3 7\n5\n11 7 15 3 7"]
|
PASSED
|
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
x=a[0]
for i in range(1,n):
x=a[i]&x
if x==0:
break
print(x)
|
1629038100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n3\n2\n3\n4"]
|
38afe98586a3b8d6061fe7e3e8fc4d02
|
NoteIn the first test case $$$x = 1$$$, so you need only one jump: the $$$1$$$-st jump from $$$0$$$ to $$$0 + 1 = 1$$$.In the second test case $$$x = 2$$$. You need at least three jumps: the $$$1$$$-st jump from $$$0$$$ to $$$0 + 1 = 1$$$; the $$$2$$$-nd jump from $$$1$$$ to $$$1 + 2 = 3$$$; the $$$3$$$-rd jump from $$$3$$$ to $$$3 - 1 = 2$$$; Two jumps are not enough because these are the only possible variants: the $$$1$$$-st jump as $$$-1$$$ and the $$$2$$$-nd one as $$$-1$$$ — you'll reach $$$0 -1 -1 =-2$$$; the $$$1$$$-st jump as $$$-1$$$ and the $$$2$$$-nd one as $$$+2$$$ — you'll reach $$$0 -1 +2 = 1$$$; the $$$1$$$-st jump as $$$+1$$$ and the $$$2$$$-nd one as $$$-1$$$ — you'll reach $$$0 +1 -1 = 0$$$; the $$$1$$$-st jump as $$$+1$$$ and the $$$2$$$-nd one as $$$+2$$$ — you'll reach $$$0 +1 +2 = 3$$$; In the third test case, you need two jumps: the $$$1$$$-st one as $$$+1$$$ and the $$$2$$$-nd one as $$$+2$$$, so $$$0 + 1 + 2 = 3$$$.In the fourth test case, you need three jumps: the $$$1$$$-st one as $$$-1$$$, the $$$2$$$-nd one as $$$+2$$$ and the $$$3$$$-rd one as $$$+3$$$, so $$$0 - 1 + 2 + 3 = 4$$$.
|
You are standing on the $$$\mathit{OX}$$$-axis at point $$$0$$$ and you want to move to an integer point $$$x > 0$$$.You can make several jumps. Suppose you're currently at point $$$y$$$ ($$$y$$$ may be negative) and jump for the $$$k$$$-th time. You can: either jump to the point $$$y + k$$$ or jump to the point $$$y - 1$$$. What is the minimum number of jumps you need to reach the point $$$x$$$?
|
For each test case, print the single integer — the minimum number of jumps to reach $$$x$$$. It can be proved that we can reach any integer point $$$x$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains the single integer $$$x$$$ ($$$1 \le x \le 10^6$$$) — the destination point.
|
standard output
|
standard input
|
PyPy 3
|
Python
| null |
train_017.jsonl
|
deed7bf9d36bb86d56a139a6f422d7f7
|
256 megabytes
|
["5\n1\n2\n3\n4\n5"]
|
PASSED
|
t=int(input())
for i in range(t):
n=int(input())
u=1
while((u*(u+1)/2)<n):
u += 1
a=u*(u+1)/2
c=a-n
for j in range(1,u+1):
if(c==j+1):
c = c-j-1
print(int(u+c))
|
1606746900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["3", "2", "1"]
|
10f2f1df27cf61f11afb074dab01ebec
|
NoteThere are three good substrings in the first sample test: «aab», «ab» and «b».In the second test only substrings «e» and «t» are good.
|
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
|
Print a single integer — the number of good substrings of string s.
|
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 200. The input limits for scoring 70 points are (subproblems G1+G2): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 50000.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_050.jsonl
|
9e646f3585e336052db5afa339565ff5
|
256 megabytes
|
["aaab\n2\naa 0 0\naab 1 1", "ltntlnen\n3\nn 0 0\nttlneenl 1 4\nlelllt 1 1", "a\n0"]
|
PASSED
|
def count(p, s):
start = 0
c = 0
while True:
try:
pos = s.index(p, start)
c += 1
start = pos + 1
except ValueError:
return c
s = input()
n = int(input())
pravs = []
for i in range(n):
p, l, r = input().split()
l = int(l); r = int(r)
pravs.append((p, l, r))
var = set()
for l in range(len(s)):
for r in range(l+1, len(s)+1):
pods = s[l:r]
for prav in pravs:
if not prav[1] <= count(pods, prav[0]) <= prav[2]:
break
else:
var.add(pods)
print(len(var))
|
1371042000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["32\n8646\n604"]
|
d3c3bc95605010040e2018e465eb9fab
|
NoteIn the first test case $$$99 + 32 = 131$$$ is a palindrome. Note that another answer is $$$12$$$, because $$$99 + 12 = 111$$$ is also a palindrome.In the second test case $$$1023 + 8646 = 9669$$$.In the third test case $$$385 + 604 = 989$$$.
|
During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $$$121, 66, 98989$$$ are palindromes, and $$$103, 239, 1241$$$ are not palindromes.Alina understands that a valid number always exist. Help her find one!
|
For each of $$$t$$$ test cases print an answer — a positive $$$n$$$-digit integer without leading zeros, such that the sum of the input integer and this number is a palindrome. We can show that at least one number satisfying the constraints exists. If there are multiple solutions, you can output any of them.
|
The first line of input data contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the number that is written on the ground. The second line of contains the positive $$$n$$$-digit integer without leading zeroes — the number itself. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100\,000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,100 |
train_094.jsonl
|
24297919af6e3029c3955b14692ec317
|
256 megabytes
|
["3\n2\n99\n4\n1023\n3\n385"]
|
PASSED
|
# Import helpful pages
from multiprocessing.dummy import current_process
import queue
from sys import stdin, stdout
from collections import defaultdict
import copy
import math
import itertools
import heapq
import bisect
from turtle import back
# Helper methods for execution
def get_int_dd():
def def_value():
return 0
return defaultdict(def_value)
def get_counts(li):
dd = get_int_dd()
for i in li:
dd[i] += 1
return dd
def get_li_dd():
def def_value():
return []
return defaultdict(def_value)
def get_index_map(li, w_offset=False):
dd = get_li_dd()
for i,n in enumerate(li):
dd[n].append(i + (1 if w_offset else 0))
return dd
def to_int_list(str):
str.strip()
return [int(i) for i in str.split()]
def to_char_list(str):
str.strip()
return [str[i] for i in range(len(str))]
# INPUT METHODS
def read_line():
return stdin.readline().strip()
def read_int():
return int(read_line())
def read_ints():
return [int(i) for i in read_line().split()]
def read_str_list(read_n=True):
n = read_int()
return [read_line() for i in range(n)]
# OUTPUT METHODS
def write_out(value):
stdout.write(str(value))
def write_line(value):
stdout.write(str(value) + '\n')
COMMENTS_ON = True
def comment(value):
if COMMENTS_ON:
stdout.write(str(value) + '\n')
def execute_on_input(calc_ans, read_case=read_line, t=None, write_output=write_line):
if not t:
t = read_int()
for eval in [calc_ans(read_case()) for input in range(t)]:
write_output(eval)
def qA():
def read():
return read_int(), read_int()
def calc(input):
n, a = input
a_str = str(a)
if int(a_str[0]) != 9:
palin = int(''.join(['9' for i in range(n)]))
return palin - a
min_b = 10 ** (n - 1)
closest_palin = 10 * min_b + 1
if closest_palin < min_b + a:
increase_pre = min_b + a - closest_palin
incr_len = len(str(increase_pre))
other_i = n - incr_len
increase = 10 ** incr_len + 10 ** other_i
closest_palin += increase
b = closest_palin - a
b_str = str(b)
if len(b_str) != n:
return len(b_str), b
return b
# Execute on each input line.
execute_on_input(calc, read_case=read)
def qTemplate():
def read():
n = read_int()
line = read_line()
return (n, line)
def calc(input):
return input
# Execute on each input line.
execute_on_input(calc, read_case=read)
# Call the methods
if __name__ == "__main__":
qA()
|
1655629500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["Iwantorderpizza", "sampleaseinout"]
|
586341bdd33b1dc3ab8e7f9865b5f6f6
| null |
Amugae has a sentence consisting of $$$n$$$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
|
In the only line output the compressed word after the merging process ends as described in the problem.
|
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of the words in Amugae's sentence. The second line contains $$$n$$$ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed $$$10^6$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000 |
train_001.jsonl
|
b902082ef641b4164a498953a9a0d707
|
256 megabytes
|
["5\nI want to order pizza", "5\nsample please ease in out"]
|
PASSED
|
def kmp(s):
i,j = -1,0
fail = [0]*len(s)
while j < len(s):
if i == -1 or s[j] == s[i]:
fail[j] = i
j += 1
i += 1
else:
i = -1 if i == 0 else fail[i-1]+1
return fail[-1]+1
n = input()
words = raw_input().split(" ")
out = words[0]
for word in words[1:]:
com = min(len(word),len(out))
l = kmp(word+"_"+out[-com:])
out += word[l:]
print out
|
1565526900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["62\n112\n107\n-1", "26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]
|
67dd049fafc464fed87fbd23f0ccc8ab
|
NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
|
Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$ — its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
|
Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$) — the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$) — the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_098.jsonl
|
f550dd6d6a089108f2b1ab9130f6de7f
|
256 megabytes
|
["3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1"]
|
PASSED
|
import sys
input = sys.stdin.readline
n=int(input())
ans=0
l=[]
for _ in range(n):
a,b=map(int,input().split())
ans+=a
l.append(b-a)
l.sort(reverse=True)
idx=10**10
for i in range(n):
if l[i]<0:
idx=i
break
rui=[0]
for i in range(n):
rui.append(rui[-1]+l[i])
def extgcd(a, b):
if b:
d, y, x = extgcd(b, a % b)
y -= (a // b)*x
return d, x, y
return a, 1, 0
import math
m=int(input())
#print(l)
#print(rui)
#print(ans,idx)
for _ in range(m):
x,y=map(int,input().split())
g=math.gcd(x,y)
if n%g>0:
print(-1)
continue
g,a,b=extgcd(x,y)
a*=(n//g)
b*=(n//g)
idx2=idx
#print(a,b,idx)
if b<idx2//y:
tmp=(idx2//y-b)//(x//g)
b+=(tmp*(x//g))
else:
tmp=(b-idx2//y)//(x//g)
b-=(tmp*(x//g))
if b<0:
tmp=b//(x//g)
b+=tmp*(x//g)
if b*y>n:
tmp=(b*y-n)//(y*(x//g))
b-=tmp*(x//g)
ma=-10**20
for i in range(-2,3):
tmpb=b+i*(x//g)
if 0<=tmpb*y<=n:
ma=max(ma,rui[tmpb*y])
if ma==-10**20:
print(-1)
else:
print(ans+ma)
|
1662647700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["0\n0\n1"]
|
644ef17fe304b090e0cf33a84ddc546a
|
NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations: with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$, with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$, with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$. The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.
|
There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?
|
For each test case, output a single integer — the minimum possible ugliness of the buildings.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_100.jsonl
|
45465e3519b41f75e5aa47cc1abbd9e0
|
256 megabytes
|
["3\n3\n10 10 10\n4\n3 2 1 2\n5\n1 2 3 1 5"]
|
PASSED
|
t=int(input())
if t>=1 and t<=10000:
for j in range(t):
b= int(input())
a=input().split()
sum=0
for i in range(len(a)):
sum=sum +int(a[i])
if sum%b==0:
print(0)
else:
print(1)
|
1640356500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["First", "First", "Draw", "First", "Second"]
|
6f52388b652a900e63ec39406225392c
| null |
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
|
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
|
The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word. It is guaranteed that both words consist of 2·n characters "0" and "1".
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_033.jsonl
|
0de64ede6037fed936e2d94b590a3df3
|
256 megabytes
|
["2\n0111\n0001", "3\n110110\n001001", "3\n111000\n000111", "4\n01010110\n00101101", "4\n01100000\n10010011"]
|
PASSED
|
from sys import stdin
def readLine():
return stdin.readline();
def main():
while True:
n = int(readLine());
a = readLine();
b = readLine();
both = 0;
onlyA = 0; onlyB = 0;
for i in range(2*n):
if a[i] == '1' and b[i] == '1':
both += 1;
elif a[i] == '1':
onlyA += 1;
elif b[i] == '1':
onlyB += 1;
A = 0; B = 0;
for i in range(n):
if both:
A += 1;
both -= 1;
elif onlyA:
A += 1;
onlyA -= 1;
elif onlyB:
onlyB -= 1;
if both:
B += 1;
both -= 1;
elif onlyB:
B += 1;
onlyB -= 1;
elif onlyA:
onlyA -= 1;
if A > B:
print( "First" );
elif A < B:
print( "Second" );
else:
print( "Draw" );
break;
main();
|
1366644900
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["NO\nYES\nYES\nYES\nNO"]
|
3ec1b7027f487181dbdfb12f295f11ae
| null |
Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if: $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$; $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$; $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$; $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.
|
For each test case, output on a separate line: "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 900 |
train_086.jsonl
|
46b3d5d55dfd9c2705827cff9285abea
|
256 megabytes
|
["5\n1\n4041\n4042\n8081\n8079"]
|
PASSED
|
import math
def get():
return list(map(int, input().split()))
def intput():
return int(input())
def rec(w,memo):
if(w in memo):
return memo[w]
if (w==0):
return True
if (w<0):
return False
memo[w]=rec(w - 2021, memo) | rec(w - 2020, memo)
return memo[w]
def main():
for _ in range(intput()):
s=intput()
f=s%2020 *2021
q=(s-f)/2020
if (s!=1910):
if( (int(q)*2020 +f ==s or (int(q)+1)*2020 +f ==s) and q>=0):
print("YES")
else:
print("NO")
else:
print("YES")
main()
|
1611586800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["142857", "Impossible", "102564"]
|
86dc5cb9e667fc2ae4d988613feddcb6
|
NoteSample 1: 142857·5 = 714285.Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
|
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
|
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
|
The single line contains integers p, x (1 ≤ p ≤ 106, 1 ≤ x ≤ 9).
|
standard output
|
standard input
|
Python 3
|
Python
| null |
train_070.jsonl
|
94f99c26af7d19738cc24a431e5c839a
|
256 megabytes
|
["6 5", "1 2", "6 4"]
|
PASSED
|
p, k = map(int, input().split())
u = 10 * k - 1
v = pow(10, p - 1, u) - k
for y in range(k, 10):
if (y * v) % u == 0:
q = d = 9 * y
while q % u: q = 10 * q + d
q = str(q // u)
print(q * (p // len(q)))
break
else: print('Impossible')
|
1392910200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["7", "100"]
|
6bb2793e275426eb076972fab69d0eba
| null |
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≤ i, j ≤ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
|
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
|
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_004.jsonl
|
fc92b516d112816ef177feeed05e3455
|
256 megabytes
|
["great10", "aaaaaaaaaa"]
|
PASSED
|
def f(x=input()):
d = dict()
for i in x:
if i in d: d[i]+=1
else: d[i] = 1
return sum([j*j for _,j in d.items()])
print(f())
|
1292862000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["4\n1\n2\n2\n1\n8\n1\n2\n2"]
|
15823d23340c845e0c257974390cb69f
|
NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
|
While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
|
For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) — the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) — the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) — the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_100.jsonl
|
f0c033a7d2f640720635c40df4676d30
|
256 megabytes
|
["9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0"]
|
PASSED
|
import sys
input = sys.stdin.readline
def pow(x, a, mod):
if a == 0:
return 1
if a == 1:
return x % mod
if a % 2:
return (x * pow(x * x, a // 2, mod)) % mod
else:
return (pow(x * x, a // 2, mod)) % mod
def sol(n, a, b, d):
vis = [False] * n
aind = [0] * n
for i in range(n):
aind[a[i]] = i
res = 0
for i in range(n):
if vis[a[i]]: continue
if a[i] == b[i]: continue
count = 0
vis[a[i]] = True
curr = i
count += d[curr]
while not vis[b[curr]]:
vis[b[curr]] = True
curr = aind[b[curr]]
count += d[curr]
if not count:
res += 1
return pow(2, res, (10 ** 9 +7))
t = int(input())
for case in range(t):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
d = list(map(int,input().split()))
a = [i-1 for i in a]
b = [i-1 for i in b]
print(sol(n, a, b, d))
|
1651847700
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["9", "12"]
|
2596db1dfc124ea9e14c3f13c389c8d2
|
NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3·3 = 9.
|
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.
|
Print the maximum possible value of the hedgehog's beauty.
|
First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively. Then follow m lines, each containing two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_027.jsonl
|
ffe546a4b2f133c3b4a40d24d29ef7b2
|
256 megabytes
|
["8 6\n4 5\n3 5\n2 5\n1 2\n2 8\n6 7", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
|
PASSED
|
R = lambda : map(int, input().split())
n,m=R()
adj=[[] for _ in range(n)]
from collections import defaultdict
d=defaultdict(int)
for i in range(m):
u,v=R()
if (u>v):
u,v=v,u
adj[u-1].append(v-1)
d[u-1]+=1
d[v-1]+=1
h=defaultdict(int)
for i in range(n):
h[i]=max(h[i],1)
for v in adj[i]:
h[v]=max(h[v],h[i]+1)
mx = 0
for i in range(n):
mx = max(mx,h[i]*d[i])
print(mx)
|
1452261900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
4 seconds
|
["1\n1", "3\n1 3 4", "4\n1 4 5 6", "7\n1 2 4 5 6 7 9"]
|
81f7807397635c9ce01f9100e68cb420
| null |
Let's call a set of positive integers $$$a_1, a_2, \dots, a_k$$$ quadratic if the product of the factorials of its elements is a square of an integer, i. e. $$$\prod\limits_{i=1}^{k} a_i! = m^2$$$, for some integer $$$m$$$.You are given a positive integer $$$n$$$.Your task is to find a quadratic subset of a set $$$1, 2, \dots, n$$$ of maximum size. If there are multiple answers, print any of them.
|
In the first line, print a single integer — the size of the maximum subset. In the second line, print the subset itself in an arbitrary order.
|
A single line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,900 |
train_085.jsonl
|
174b1d60eff3d63cd65d55d4091e1504
|
256 megabytes
|
["1", "4", "7", "9"]
|
PASSED
|
def is_square(n):
return int(n ** 0.5) ** 2 == n
def solve(n):
if n <= 3:
return range(2, n+1)
k = n >> 1
if n % 4 == 0:
return [k]
if n % 4 == 1:
return [k, n]
if n % 4 == 2:
if is_square(n + 2):
return [k + 1]
if is_square(2 * k * (k - 1)):
return [k - 2]
return [2, k]
if n % 4 == 3:
if is_square(n + 1):
return [k + 1, n]
if is_square(2 * k * (k - 1)):
return [k - 2, n]
if is_square(n * (k - 1)):
return [k - 2, n - 2]
return [2, k, n]
N = int(input())
ans = solve(N)
output = [x for x in range(1, N+1) if x not in ans]
print(len(output))
print(" ".join(map(str, output)))
|
1640615700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["2\n1 3 4", "-1", "4\n1 3 2 3 4"]
|
c23efec5ead55d9adee703c3ff535b94
| null |
In Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there are k such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: ai, ci, bi. Vasya wants to get from the city 1 to the city n and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes.
|
If there are no path from 1 to n print -1. Otherwise on the first line print the number of roads d along the shortest path from the city 1 to the city n. On the second line print d + 1 numbers — any of the possible shortest paths for Vasya. The path should start in the city 1 and end in the city n.
|
The first line contains three integers n, m, k (2 ≤ n ≤ 3000, 1 ≤ m ≤ 20000, 0 ≤ k ≤ 105) which are the number of cities, the number of roads and the number of the forbidden triplets correspondingly. Then follow m lines each containing two integers xi, yi (1 ≤ xi, yi ≤ n) which are the road descriptions. The road is described by the numbers of the cities it joins. No road joins a city with itself, there cannot be more than one road between a pair of cities. Then follow k lines each containing three integers ai, bi, ci (1 ≤ ai, bi, ci ≤ n) which are the forbidden triplets. Each ordered triplet is listed mo more than one time. All three cities in each triplet are distinct. City n can be unreachable from city 1 by roads.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_039.jsonl
|
b497e10aee4e64e951c3c9b6d0571ea7
|
256 megabytes
|
["4 4 1\n1 2\n2 3\n3 4\n1 3\n1 4 3", "3 1 0\n1 2", "4 4 2\n1 2\n2 3\n3 4\n1 3\n1 2 3\n1 3 4"]
|
PASSED
|
if __name__ =='__main__':
n, m, k = map(int, input().split())
graph = [[] for i in range(n + 2)]
for i in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
graph[n].append(n+1)
processed =[[-1 for i in range(n+2)] for j in range(n+2)]
forbid = set(a + (b+c*n)*n for (a,b,c) in (map(int, input().split()) for i in range(k)))
bfsqueue =[(0,1)]
processed[0][1] = 0
while bfsqueue and processed[n][n+1] == -1:
u,v = bfsqueue.pop(0)
for key in graph[v]:
if processed[v][key] != -1 or (u+ (v+key*n)*n in forbid):
continue
processed[v][key] = u
if key == n+1:
break
bfsqueue.append((v,key))
if processed[n][n+1] != -1:
i, j = n,n+1
ans = []
while i:
ans.append(i)
i,j = processed[i][j],i
print(len(ans) - 1)
print(' '.join(map(str,reversed(ans))))
else:
print(-1)
|
1297440000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES", "NO", "YES"]
|
c4b7265ff4332225c0d5617c3233a910
| null |
One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.
|
If the given state is reachable in the described game, output YES, otherwise NO.
|
The first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_034.jsonl
|
cc056a88cd96d0b8039a6bc699aa93e6
|
256 megabytes
|
["5\n5 4 3 2 1\n1 1 1 1 1", "7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1", "7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1"]
|
PASSED
|
n = int(input())
data = list(map(int, input().split()))
spans = list(map(int, input().split()))
connect = [[False for c in range(n)] for r in range(n)]
for p, span in enumerate(spans):
for r in [p-span, p+span]:
if r >= 0 and r < n:
connect[p][r] = connect[r][p] = True
def visit(data, connect, seen, group, i):
if not seen[i]:
seen[i] = True
group.append((i, data[i]))
for j in range(n):
if connect[i][j]:
visit(data, connect, seen, group, j)
seen = [False for i in range(n)]
for i in range(n):
group = []
visit(data, connect, seen, group, i)
group.sort()
#print()
#print(group)
values = sorted([value for (index, value) in group])
#print(values)
for i, value in enumerate(values):
data[group[i][0]] = value
#print(data)
if data == list(range(1, n+1)):
print('YES')
else:
print('NO')
|
1284735600
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
4 seconds
|
["OR 1 2\n\nOR 2 3\n\nXOR 2 4\n\n! 0 0 2 3"]
|
0ce667283c449582aa79c64927a4b781
|
NoteThe array $$$a$$$ in the example is $$$[0, 0, 2, 3]$$$.
|
The only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array $$$a$$$ of $$$n$$$ integers which he wants Ashish to guess. Note that $$$n$$$ is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND $$$i$$$ $$$j$$$: ask for the bitwise AND of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ OR $$$i$$$ $$$j$$$: ask for the bitwise OR of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ XOR $$$i$$$ $$$j$$$: ask for the bitwise XOR of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range $$$[0, n-1]$$$ (inclusive) and Ashish can ask no more than $$$n+1$$$ queries.
| null |
The first line of input contains one integer $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — the length of the array. It is guaranteed that $$$n$$$ is a power of two.
|
standard output
|
standard input
|
Python 3
|
Python
| null |
train_027.jsonl
|
5ce5536001501032bbd9e6c2a1e938eb
|
256 megabytes
|
["4\n\n0\n\n2\n\n3"]
|
PASSED
|
n = int(input())
a = [0]
know = 0
pos = [0]*n
pos[0] = 1
for i in range(2, n+1):
print("XOR", 1, i)
x = int(input())
a.append(x)
if pos[x] > 0 and know == 0:
know = 1
print("OR", pos[x], i)
a[0] = int(input())^x
pos[x] = i
if know == 0:
print("OR", 1, pos[1])
x = int(input()) # x = a[0] | (a[0] ^ 1)
print("OR", 1, pos[2])
y = int(input()) # y = a[0] | (a[0] ^ 2)
a[0] = (x & (n-2)) | (y & (n-3))
for i in range(1, n):
a[i] ^= a[0]
print('!', *a)
|
1605969300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["11111", "1111110", "0"]
|
7f855479e9df3405bb29f2a0cb1cb3b3
|
NoteIn the first example, you can choose the substrings 11010 and 101. $$$f(s_1) = 26$$$, $$$f(s_2) = 5$$$, their bitwise OR is $$$31$$$, and the binary representation of $$$31$$$ is 11111.In the second example, you can choose the substrings 1110010 and 11100.
|
You are given a string $$$s$$$ consisting of $$$n$$$ characters. Each character of $$$s$$$ is either 0 or 1.A substring of $$$s$$$ is a contiguous subsequence of its characters.You have to choose two substrings of $$$s$$$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows: let $$$s_1$$$ be the first substring, $$$s_2$$$ be the second chosen substring, and $$$f(s_i)$$$ be the integer such that $$$s_i$$$ is its binary representation (for example, if $$$s_i$$$ is 11010, $$$f(s_i) = 26$$$); the value is the bitwise OR of $$$f(s_1)$$$ and $$$f(s_2)$$$. Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.
|
Print the maximum possible value you can get in binary representation without leading zeroes.
|
The first line contains one integer $$$n$$$ — the number of characters in $$$s$$$. The second line contains $$$s$$$ itself, consisting of exactly $$$n$$$ characters 0 and/or 1. All non-example tests in this problem are generated randomly: every character of $$$s$$$ is chosen independently of other characters; for each character, the probability of it being 1 is exactly $$$\frac{1}{2}$$$. This problem has exactly $$$40$$$ tests. Tests from $$$1$$$ to $$$3$$$ are the examples; tests from $$$4$$$ to $$$40$$$ are generated randomly. In tests from $$$4$$$ to $$$10$$$, $$$n = 5$$$; in tests from $$$11$$$ to $$$20$$$, $$$n = 1000$$$; in tests from $$$21$$$ to $$$40$$$, $$$n = 10^6$$$. Hacks are forbidden in this problem.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_088.jsonl
|
68c59b97cfa6f2b5b06a497f09bfadb1
|
512 megabytes
|
["5\n11010", "7\n1110010", "4\n0000"]
|
PASSED
|
n = int(input())
s = input()
s = list(s)
i = 0
while s[i] == '0':
i += 1
if i == n:
break
if i == n:
print(0)
else:
s = s[i:]
n = len(s)
ans = [i for i in s]
i = 0
o = 0
while s[i] == '1':
o += 1
i += 1
if o == 0:
print('0')
else:
ones = [j for j in range(1, o+1)]
while i < n and len(ones) > 0:
if s[i] == '0':
tmp = []
for j in ones:
if s[i - j] == '1':
tmp.append(j)
if len(tmp) > 0:
ans[i] = '1'
ones = tmp
i += 1
anss = ''
for i in ans:
anss += i
print(anss)
|
1666017300
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds
|
["3\n0\n1\n-1"]
|
389be6455476db86a8a5d9d5343ee35a
|
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
|
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
|
Print $$$T$$$ integers — one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
|
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_004.jsonl
|
8dca9099c4c5940f13721bd53c96f999
|
256 megabytes
|
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
|
PASSED
|
for i in range(int(input())):
n,x = map(int,input().split())
s=input()
count0=0
l=[]
for j in range(n):
if s[j]=="0":
count0+=1
l.append(count0)
else:
count0-=1
l.append(count0)
a=s.count("0")
b=len(s)-a
k=a-b
if a==b and x==0:
print(-1)
elif a==b and x in l:
print(-1)
elif a==b and x not in l:
print(0)
else:
flag=0
for j in l:
c=(x-j)/k
if c==(int(c)) and c>=0:
flag+=1
if x==0:
print(flag+1)
else:
print(flag)
|
1580308500
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds
|
["0\n1\n1\n2\n1\n-1"]
|
7ad14848b3b9f075477fbf0c5f648c77
|
NoteFor the $$$1$$$-st test case, since $$$s$$$ and $$$t$$$ are equal, you don't need to apply any operation.For the $$$2$$$-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.For the $$$3$$$-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.For the $$$4$$$-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length $$$2$$$ beginning at the second character to convert it to cba.For the $$$5$$$-th test case, you only need to apply one operation on the entire string abab to convert it to baba.For the $$$6$$$-th test case, it is not possible to convert string $$$s$$$ to $$$t$$$.
|
You are given two strings $$$s$$$ and $$$t$$$, each of length $$$n$$$ and consisting of lowercase Latin alphabets. You want to make $$$s$$$ equal to $$$t$$$. You can perform the following operation on $$$s$$$ any number of times to achieve it — Choose any substring of $$$s$$$ and rotate it clockwise once, that is, if the selected substring is $$$s[l,l+1...r]$$$, then it becomes $$$s[r,l,l + 1 ... r - 1]$$$. All the remaining characters of $$$s$$$ stay in their position. For example, on rotating the substring $$$[2,4]$$$ , string "abcde" becomes "adbce". 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.Find the minimum number of operations required to convert $$$s$$$ to $$$t$$$, or determine that it's impossible.
|
For each test case, output the minimum number of operations to convert $$$s$$$ to $$$t$$$. If it is not possible to convert $$$s$$$ to $$$t$$$, output $$$-1$$$ instead.
|
The first line of the input contains a single integer $$$t$$$ $$$(1\leq t \leq 2000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\leq n \leq 2000)$$$ — the length of the strings. The second and the third lines contain strings $$$s$$$ and $$$t$$$ respectively. The sum of $$$n$$$ over all the test cases does not exceed $$$2000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,600 |
train_050.jsonl
|
7eca10c9f82a669d27abaa16b70ddb7e
|
256 megabytes
|
["6\n1\na\na\n2\nab\nba\n3\nabc\ncab\n3\nabc\ncba\n4\nabab\nbaba\n4\nabcc\naabc"]
|
PASSED
|
def num(c):
return ord(c) - 97
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
s1 = input().strip()
s2 = input().strip()
char1 = [0] * 26
char2 = [0] * 26
for c in s1:
char1[num(c)] += 1
for c in s2:
char2[num(c)] += 1
if char1 != char2:
print(-1)
continue
dp = [[(False, 0, 0) for j in range(n+1)] for i in range(n + 1)]
dp[0][0] = [True, 0,[0]*26]
def upd(a, b, val, sett):
if not dp[a][b][0] or val > dp[a][b][1]:
dp[a][b] = (True, val, sett)
for i in range(n):
for j in range(n):
valid, val, tab = dp[i][j]
if not valid:
continue
top = s1[i]
bot = s2[j]
if top == bot:
#upd(i+1, j+1, val + 1, tab)
if not dp[i + 1][j + 1][0] or val + 1 > dp[i + 1][j + 1][1]:
dp[i + 1][j + 1] = [True, val + 1, tab]
if tab[num(top)] > 0:
sett = tab[:]
sett[num(top)] -= 1
#upd(i+1, j, val, sett)
if not dp[i + 1][j][0] or val > dp[i + 1][j][1]:
dp[i + 1][j] = [True, val, sett]
sett = tab[:]
sett[num(bot)] += 1
#upd(i, j + 1, val, sett)
if not dp[i][j + 1][0] or val > dp[i][j + 1][1]:
dp[i][j + 1] = [True, val, sett]
del dp[i][j][2]
poss = [dp[i][n][1] for i in range(n + 1)]
print(n - max(poss))
|
1590935700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["3 5\n2 4"]
|
259e39c9e63e43678e596c0d8c66937c
|
NoteThe first query is $$$P=17$$$. $$$a=3$$$ and $$$b=5$$$ are valid bases in this case, because $$$17 \bmod 3 = 17 \bmod 5 = 2$$$. There are other pairs which work as well.In the second query, with $$$P=5$$$, the only solution is $$$a=2$$$ and $$$b=4$$$.
|
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is $$$P$$$. Gregor wants to find two bases of $$$P$$$. Formally, Gregor is looking for two integers $$$a$$$ and $$$b$$$ which satisfy both of the following properties. $$$P \bmod a = P \bmod b$$$, where $$$x \bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$, and $$$2 \le a < b \le P$$$. Help Gregor find two bases of his favorite prime number!
|
Your output should consist of $$$t$$$ lines. Each line should consist of two integers $$$a$$$ and $$$b$$$ ($$$2 \le a < b \le P$$$). If there are multiple possible solutions, print any.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each subsequent line contains the integer $$$P$$$ ($$$5 \le P \le {10}^9$$$), with $$$P$$$ guaranteed to be prime.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_086.jsonl
|
1bbc496283cb11c6da06a3c1b29f1900
|
256 megabytes
|
["2\n17\n5"]
|
PASSED
|
for _ in range(int(input())):
print(2,int(input())-1,sep=" ")
|
1627828500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["3"]
|
e1ebaf64b129edb8089f9e2f89a0e1e1
|
NoteLet's have a look at the example. Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
|
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≤ i < p) are friends. Help the Beaver find the maximum number of acquaintances he can invite.
|
Output a single number — the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.
|
The first line of input contains an integer n — the number of the Beaver's acquaintances. The second line contains an integer k — the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi — indices of people who form the i-th pair of friends. The next line contains an integer m — the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2 ≤ n ≤ 14 The input limitations for getting 100 points are: 2 ≤ n ≤ 2000
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_030.jsonl
|
c2811e69a9d6318588311d70488e632b
|
256 megabytes
|
["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"]
|
PASSED
|
# maa chudaaye duniya
n = int(input())
parents = [i for i in range(n+1)]
ranks = [1 for i in range(n+1)]
def find(x):
if parents[x] != x:
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
xs = find(x)
ys = find(y)
if xs == ys:
return
if ranks[xs] > ranks[ys]:
parents[ys] = xs
elif ranks[ys] > ranks[xs]:
parents[xs] = ys
else:
parents[ys] = xs
ranks[xs] += 1
for _ in range(int(input())):
u, v = map(int, input().split())
union(u, v)
# print(parents)
rejects = set([])
for _ in range(int(input())):
p, q = map(int, input().split())
ps = find(p)
qs = find(q)
if ps == qs:
rejects.add(ps)
ps = {}
for i in range(1, n+1):
p = find(i)
if p not in rejects:
if p in ps:
ps[p] += 1
else:
ps[p] = 1
# print(ps)
ans = 0
for i in ps:
ans = max(ans, ps[i])
print(ans)
|
1335016800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "4"]
|
0aed14262c135d1624df9814078031ae
|
NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.
|
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
|
Print a single integer number, the maximum number of letters that Nastya can remove.
|
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_003.jsonl
|
fe64d9b8710f1fcb265559c438395a59
|
512 megabytes
|
["ababcba\nabb\n5 3 4 1 7 6 2", "bbbabb\nbb\n1 6 3 4 2 5"]
|
PASSED
|
a=input()
b=input()
c=[i-1 for i in list(map(int,input().split()))]
l=0
r=len(a)
while r-l>1 :
m=l+(r-l)//2#two pointer
d=list(a)
j=0
for o in range(m):#first half delete value replace with ""
d[c[o]]=""
for i in range(int(len(a))):
if(d[i]==b[j]):
j+=1
if(j==len(b)):
l=m
break
if(j!=len(b)):r=m
print(l)
|
1488096300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["ababababa", "catcat"]
|
34dd4c8400ff7a67f9feb1487f2669a6
| null |
You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.
|
Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.
|
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 50$$$) — the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_008.jsonl
|
18597ff58ce327c82f61600bc4f9226d
|
256 megabytes
|
["3 4\naba", "3 2\ncat"]
|
PASSED
|
# -*- coding: utf-8 -*-
import sys
from itertools import accumulate
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
N, K = MAP()
T = input()
if set(T) == 1:
ans = T + T[0] * (K-1)
print(ans)
exit()
i = N - 1
while T[:i] != T[N-i:]:
i -= 1
same = T[:i]
diff = T[i:]
ans = same + diff * K
print(ans)
|
1535122200
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\nNO\nYES"]
|
5afb904f611d963ed3e302faefef3305
|
NoteIn the first query of the third type $$$k = 3$$$, we can, for example, choose a sequence $$$[1, 2, 3]$$$, since $$$1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3$$$ and $$$3 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 1$$$.In the second query of the third type $$$k = 2$$$, and we can't find sequence $$$p_1, p_2$$$ such that arcs $$$(p_1, p_2)$$$ and $$$(p_2, p_1)$$$ have the same characters.In the third query of the third type, we can, for example, choose a sequence $$$[1, 2, 3, 2, 1]$$$, where $$$1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 \xrightarrow{\text{d}} 2 \xrightarrow{\text{c}} 1$$$.
|
You are given a directed graph consisting of $$$n$$$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.You should process $$$m$$$ queries with it. Each query is one of three types: "$$$+$$$ $$$u$$$ $$$v$$$ $$$c$$$" — add arc from $$$u$$$ to $$$v$$$ with label $$$c$$$. It's guaranteed that there is no arc $$$(u, v)$$$ in the graph at this moment; "$$$-$$$ $$$u$$$ $$$v$$$" — erase arc from $$$u$$$ to $$$v$$$. It's guaranteed that the graph contains arc $$$(u, v)$$$ at this moment; "$$$?$$$ $$$k$$$" — find the sequence of $$$k$$$ vertices $$$v_1, v_2, \dots, v_k$$$ such that there exist both routes $$$v_1 \to v_2 \to \dots \to v_k$$$ and $$$v_k \to v_{k - 1} \to \dots \to v_1$$$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.
|
For each query of the third type, print YES if there exist the sequence $$$v_1, v_2, \dots, v_k$$$ described above, or NO otherwise.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the graph and the number of queries. The next $$$m$$$ lines contain queries — one per line. Each query is one of three types: "$$$+$$$ $$$u$$$ $$$v$$$ $$$c$$$" ($$$1 \le u, v \le n$$$; $$$u \neq v$$$; $$$c$$$ is a lowercase Latin letter); "$$$-$$$ $$$u$$$ $$$v$$$" ($$$1 \le u, v \le n$$$; $$$u \neq v$$$); "$$$?$$$ $$$k$$$" ($$$2 \le k \le 10^5$$$). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,400 |
train_094.jsonl
|
504e29b459e6cdcae98ee1b8e3613d53
|
256 megabytes
|
["3 11\n+ 1 2 a\n+ 2 3 b\n+ 3 2 a\n+ 2 1 b\n? 3\n? 2\n- 2 1\n- 3 2\n+ 2 1 c\n+ 3 2 d\n? 5"]
|
PASSED
|
import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate
import math
import sys
# sys.setrecursionlimit(10 ** 6)
# Fast IO Region
BUFSIZE = 8192
#
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# sys.setrecursionlimit(800)
ii = lambda: int(input())
mii = lambda: map(int, input().split())
lmii = lambda: list(map(int, input().split()))
i2c = lambda n: chr(ord('a') + n)
c2i = lambda c: ord(c) - ord('a')
# mod = 998244353
mod = 10 ** 9 + 7
def solve():
n, m = mii()
magic = 2184732
d = {}
bs = 0
bss = 0
for i in range(m):
ope = input().split()
if len(ope) == 4:
ch, u, v, c = ope
u = int(u) + magic
v = int(v) + magic
d[(u, v)] = c
if (v, u) in d and d[(v, u)] != '#':
bs += 1
if d[(v, u)] == c:
bss += 1
elif len(ope) == 3:
ch, u, v = ope
u = int(u) + magic
v = int(v) + magic
if (v, u) in d and d[(v, u)] != '#':
bs -= 1
if d[(v, u)] == d[(u, v)]:
bss -= 1
d[(u, v)] = '#'
else:
_, k = ope
k = int(k)
if k & 1:
if bs > 0:
print('YES')
else:
print('NO')
else:
if bss > 0:
print('YES')
else:
print('NO')
for _ in range(1):
solve()
|
1614696300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["11", "11010"]
|
133eaf241bb1557ba9a3f59c733d34bf
|
NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.
|
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
|
In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.
|
The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,100 |
train_009.jsonl
|
ff02f8a871c066fb6ad910a6c744cabe
|
256 megabytes
|
["101", "110010"]
|
PASSED
|
a = list(raw_input())
idx = -1
for i in range(len(a)):
if a[i] == '0':
a.pop(i)
idx = i
print ''.join(a)
break
if idx == -1:
print ''.join(a[:-1])
|
1356190200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["Yes\nNo\nNo\nYes"]
|
a97e70ad20a337d12dcf79089c16c9f0
|
NoteIn the first test case, we can simply swap $$$31$$$ and $$$14$$$ ($$$31 + 14 = 45$$$ which is odd) and obtain the non-decreasing array $$$[1,6,14,31]$$$.In the second test case, the only way we could sort the array is by swapping $$$4$$$ and $$$2$$$, but this is impossible, since their sum $$$4 + 2 = 6$$$ is even.In the third test case, there is no way to make the array non-decreasing.In the fourth test case, the array is already non-decreasing.
|
You are given an array $$$a_1, a_2, \dots, a_n$$$. You can perform operations on the array. In each operation you can choose an integer $$$i$$$ ($$$1 \le i < n$$$), and swap elements $$$a_i$$$ and $$$a_{i+1}$$$ of the array, if $$$a_i + a_{i+1}$$$ is odd.Determine whether it can be sorted in non-decreasing order using this operation any number of times.
|
For each test case, print "Yes" or "No" depending on whether you can or can not sort the given array. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. 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,100 |
train_106.jsonl
|
a78555172afa167b42e6b761027146a4
|
256 megabytes
|
["4\n\n4\n\n1 6 31 14\n\n2\n\n4 2\n\n5\n\n2 9 6 7 10\n\n3\n\n6 6 6"]
|
PASSED
|
# cook your dish here
# cook your dish here
#!/usr/bin/env python
from cmath import inf
import os
from math import ceil, factorial, floor, log, sqrt
import re
import sys
from collections import Counter, defaultdict
from itertools import permutations
from io import BytesIO, IOBase
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def highestPowerOf2(n):
return (n & (~(n - 1)))
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a,b):
return (a / gcd(a,b))* b
def is_sorted(n, arr):
for j in range(n-1):
if arr[j]>arr[j+1]:
return False
return True
# Returns XNOR of num1 and num2
def prime_factor(n):
ans = []
if n%2==0:
ans.append(2)
while n%2==0:
n = n//2
for j in range(3, round(n**0.5) + 1, 2):
if n%j==0:
ans.append(j)
while n%j==0:
n = n//j
if n!=1:
ans.append(n)
return ans
def isPowerofTwo(n):
if (n == 0):
return 0
if ((n & (~(n - 1))) == n):
return 1
return 0
def sum_root(n):
a = 1
b = 1
c = -2*n
d = b**2 - 4*a*c
root = (-b + int(d**0.5))/2
return round(root)
def factors(n):
i = 1
cnt = 0
while i <= sqrt(n):
if (n % i == 0) :
# If divisors are equal, print only one
if (n / i == i) :
cnt += 1
else :
# Otherwise print both
cnt += 2
i = i + 1
return cnt
def prime(n):
if n%2==0 and n>2:
return False
for j in range(3, int(sqrt(n)) + 1, 2):
if n%j==0:
return False
return True
def is_palindrome(s, n):
for j in range(n//2):
if s[j] != s[n-j-1]:
return False
return True
prod = 1
memo = {}
def solve(x):
global memo
if x in memo:
return memo[x]
else:
if x>4:
memo[x] = (solve(x//2)*solve(ceil(x/2)))%998244353
else:
memo[x] = x
return memo[x]
class Graph:
def __init__(self, V):
# No. of vertices
self.V = V
# Pointer to an array containing
# adjacency lists
self.adj = [[] for i in range(self.V)]
# Function to return the number of
# connected components in an undirected graph
def NumberOfconnectedComponents(self):
# Mark all the vertices as not visited
visited = [False for i in range(self.V)]
# To store the number of connected
# components
count = 0
for v in range(self.V):
if (visited[v] == False):
self.DFSUtil(v, visited)
count += 1
return count
def DFSUtil(self, v, visited):
# Mark the current node as visited
visited[v] = True
# Recur for all the vertices
# adjacent to this vertex
for i in self.adj[v]:
if (not visited[i]):
self.DFSUtil(i, visited)
# Add an undirected edge
def addEdge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
def main():
for i in range(int(input())):
n = int(input())
arr = [int(x) for x in input().split()]
odd = []
even = []
for j in range(n):
if arr[j]%2!=0:
odd.append(arr[j])
else:
even.append(arr[j])
if odd == list(sorted(odd)) and even == list(sorted(even)):
print("YES")
else:
print("NO")
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
1644849300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "6", "6", "11"]
|
40002052843ca0357dbd3158b16d59f4
|
NoteConsidering the first $$$24$$$ nodes of the system, the node network will look as follows (the nodes $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ are drawn bold):For the first example, Ivy will place the emotion samples at the node $$$1$$$. From here: The distance from Vanessa's first fragment to the node $$$1$$$ is $$$1$$$. The distance from Vanessa's second fragment to the node $$$1$$$ is $$$0$$$. The distance from Vanessa's third fragment to the node $$$1$$$ is $$$4$$$. The total length is $$$5$$$.For the second example, the assembly node will be $$$6$$$. From here: The distance from Vanessa's first fragment to the node $$$6$$$ is $$$0$$$. The distance from Vanessa's second fragment to the node $$$6$$$ is $$$2$$$. The distance from Vanessa's third fragment to the node $$$6$$$ is $$$2$$$. The distance from Vanessa's fourth fragment to the node $$$6$$$ is again $$$2$$$. The total path length is $$$6$$$.
|
Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($$$1, 2, 3, \ldots$$$). The node with a number $$$x$$$ ($$$x > 1$$$), is directly connected with a node with number $$$\frac{x}{f(x)}$$$, with $$$f(x)$$$ being the lowest prime divisor of $$$x$$$.Vanessa's mind is divided into $$$n$$$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $$$i$$$-th fragment is now located at the node with a number $$$k_i!$$$ (a factorial of $$$k_i$$$).To maximize the chance of successful awakening, Ivy decides to place the samples in a node $$$P$$$, so that the total length of paths from each fragment to $$$P$$$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $$$P$$$ needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $$$P$$$.
|
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $$$P$$$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $$$P$$$ needs to be counted multiple times as well.
|
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — number of fragments of Vanessa's mind. The second line contains $$$n$$$ integers: $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), denoting the nodes where fragments of Vanessa's mind are located: the $$$i$$$-th fragment is at the node with a number $$$k_i!$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_043.jsonl
|
79d3d1fb0ab362b14234d83001540a9b
|
512 megabytes
|
["3\n2 1 4", "4\n3 1 4 4", "4\n3 1 4 1", "5\n3 1 4 1 5"]
|
PASSED
|
from sys import stdin, stdout
prime = list()
factor = list()
count = list()
dist = list()
N = 0
def find_prime():
global prime
for i in range(2, 5010):
is_prime = True
for j in prime:
if i % j == 0:
is_prime = False
break
if is_prime is True:
prime.append(i)
def calculate_factor(max):
global prime
global factor
global dist
factor = [[0 for x in range(len(prime))] for y in range(5010)]
dist = [0] * (max+1)
d = 0
for i in range(1, max+1):
temp = i
factor[i] = list(factor[i-1])
for j,x in enumerate(prime):
while temp % x == 0:
factor[i][j] +=1
temp = temp / x
d += 1
if temp == 1:
dist[i] = d
break
def dynamic_count():
global count
for i in range (1,len(count)):
count[i] += count[i-1]
def moving(i, left, right, d, current_factor):
global count
global prime
global factor
global N
while (factor[left][i] == factor[right][i]):
d += ((2 * (count[right] - count[left-1])) - N) * (factor[right][i] - current_factor[i])
current_factor[i] = factor[right][i]
i -= 1
if i < 0:
return d
d += ((2 * (count[right] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
current_factor[i] = factor[left][i]
temp_left = right
while temp_left >= left:
if (factor[temp_left-1][i] != factor[right][i] or temp_left == left ) and count[right] - count[temp_left-1] > int(N/2):
if (temp_left > left):
d += ((2 * (count[temp_left-1] - count[left-1]))) * (factor[left][i] - current_factor[i])
return moving(i, temp_left, right, d, current_factor)
elif factor[temp_left-1][i] != factor[right][i]:
i -= 1
right = temp_left - 1
if i < 0:
return d
temp_left -= 1
return d
def unanem():
global prime
global count
global N
if count[1] > int(N/2):
return 0
current_factor = [0] * 5010
if count[5000] - count[4998] > int(N/2):
return moving(len(prime)-3, 4999, 5000, 0, current_factor)
for i,x in enumerate(prime):
counter = 0
if i == 0:
counter = count[1]
else:
counter = count[prime[i] - 1] - count[prime[i-1] - 1]
if counter>int(N/2):
return moving (i, prime[i-1], prime[i] - 1, 0 , current_factor)
return 0
def main():
global prime
global factor
global count
global N
global debugs
N = int(stdin.readline())
num_list = list(map(int, stdin.readline().split()))
max = 0
for i in num_list:
if max < i:
max = i
count = [0] * (5010)
for i in num_list:
count[i] += 1
find_prime()
calculate_factor(max)
dynamic_count()
d = unanem()
overall_dist = 0
for i,c in enumerate(count):
if i == max + 1:
break
if i == 0:
continue
overall_dist += (count[i] - count[i-1])*dist[i]
print(overall_dist - d)
main()
|
1579440900
|
[
"number theory",
"math",
"trees",
"graphs"
] |
[
0,
0,
1,
1,
1,
0,
0,
1
] |
|
1 second
|
["? 2 3 4\n? 1 3 4\n? 1 2 4\n? 1 2 3\n! 3"]
|
712bef1b0f737cb9c2b35a96498d50bc
|
NoteIn the example, $$$n = 4$$$, $$$k = 3$$$, $$$m = 3$$$, $$$a = [2, 0, 1, 9]$$$.
|
This problem is interactive.We have hidden an array $$$a$$$ of $$$n$$$ pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of $$$k$$$ different elements of the array, it will return the position and value of the $$$m$$$-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember $$$k$$$, but don't remember $$$m$$$. Your task is to find $$$m$$$ using queries to this device. You can ask not more than $$$n$$$ queries.Note that the array $$$a$$$ and number $$$m$$$ are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array $$$a$$$. You just have to guess $$$m$$$.
| null |
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le k < n \le 500$$$) — the length of the array and the number of the elements in the query. It is guaranteed that number $$$m$$$ satisfies $$$1\le m \le k$$$, elements $$$a_1, a_2, \dots, a_n$$$ of the array satisfy $$$0\le a_i \le 10^9$$$, and all of them are different.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_006.jsonl
|
18d1f2aa8e6deaa9456d0003de0cfe7c
|
256 megabytes
|
["4 3\n4 9\n4 9\n4 9\n1 2"]
|
PASSED
|
import sys
n, k = map(int, input().split())
k1 = 0
k2 = 0
b1 = 0
b2 = 0
for i in range(k + 1):
print('?', end=' ')
for j in range(k + 1):
if i != j:
print(j + 1, end=' ')
sys.stdout.flush()
a, x = map(int, input().split())
if i == 0:
b1 = x
if x == b1:
k1 += 1
else:
b2 = x
k2 += 1
if b1 > b2:
print('!', k1)
else:
print('!', k2)
sys.stdout.flush()
|
1577628300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0\n1\n3\n1"]
|
7226a7d2700ee52f52d417f404c42ab7
|
NoteIn the first test case, we have $$$s=0$$$ so all numbers are equal to $$$0$$$ and there isn't any number equal to $$$49$$$.In the second test case, we have $$$s=1$$$. There are two possible sequences: $$$[0, 1]$$$ or $$$[1, 0]$$$. In both cases, the number $$$1$$$ appears just once. In the third test case, we have $$$s=12$$$, which is the maximum possible value of $$$s$$$ for this case. Thus, the number $$$4$$$ appears $$$3$$$ times in the sequence.
|
Luis has a sequence of $$$n+1$$$ integers $$$a_1, a_2, \ldots, a_{n+1}$$$. For each $$$i = 1, 2, \ldots, n+1$$$ it is guaranteed that $$$0\leq a_i < n$$$, or $$$a_i=n^2$$$. He has calculated the sum of all the elements of the sequence, and called this value $$$s$$$. Luis has lost his sequence, but he remembers the values of $$$n$$$ and $$$s$$$. Can you find the number of elements in the sequence that are equal to $$$n^2$$$?We can show that the answer is unique under the given constraints.
|
For each test case, print one integer — the number of elements in the sequence which are equal to $$$n^2$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n< 10^6$$$, $$$0\le s \le 10^{18}$$$). It is guaranteed that the value of $$$s$$$ is a valid sum for some sequence satisfying the above constraints.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_110.jsonl
|
ddf7915b016cb6be917db4bc7de960b2
|
256 megabytes
|
["4\n\n7 0\n\n1 1\n\n2 12\n\n3 12"]
|
PASSED
|
t=int(input())
for i in range(t):
x=input()
a=x.split()
print(int(a[1])//(int(a[0]))**2)
|
1646408100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n1 4 5", "8\n1 5 4 8 10 6 3 7"]
|
0dd041c0665d3ec4c46c2c791c17192d
|
NoteThe first example case achieves a strength of 1/2. No other subset is strictly better.The second example case achieves a strength of 1. Note that the subset doesn't necessarily have to be connected.
|
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are k cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses.After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible. More formally, they would like to capture a non-empty set of cities S with no fortresses of Life Fibers. The strength of a city is defined as (number of neighbors of x in S) / (total number of neighbors of x). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in S.Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.
|
The first line should contain an integer r, denoting the size of an optimum set (1 ≤ r ≤ n - k). The second line should contain r integers, denoting the cities in the set. Cities may follow in an arbitrary order. This line should not contain any of the cities with fortresses. If there are multiple possible answers, print any of them.
|
The first line of input contains three integers n, m, k (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000, 1 ≤ k ≤ n - 1). The second line of input contains k integers, representing the cities with fortresses. These cities will all be distinct. The next m lines contain the roads. The i-th of these lines will have 2 integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Every city will have at least one road adjacent to it. There is no more than one road between each pair of the cities.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_052.jsonl
|
8817438774cfd979a67caada560555f8
|
256 megabytes
|
["9 8 4\n3 9 6 8\n1 2\n1 3\n1 4\n1 5\n2 6\n2 7\n2 8\n2 9", "10 8 2\n2 9\n1 3\n2 9\n4 5\n5 6\n6 7\n7 8\n8 10\n10 4"]
|
PASSED
|
import heapq
def read_data():
'''
n: number of cities
m: number of roads
k: initial numuber of fortresses of Life Fibers
Es: list of edges
fs: fs[i] = True -> city i is under control of Life Fibers
gs: gs[i] number of edges connected to city i
hs: hs[i] number of adjacent cities under control of Life Fibers
'''
n, m, k = map(int, input().split())
Es = [[] for i in range(n)]
fs = [False] * n
gs = [0.0] * n
hs = [0.0] * n
fortresses = list(map(int, input().split()))
for f in fortresses:
fs[f-1] = True
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
Es[a].append(b)
Es[b].append(a)
gs[a] += 1
gs[b] += 1
hs[a] += fs[b]
hs[b] += fs[a]
return n, m, k, fs, gs, hs, Es
def solve(n, m, k, fs, gs, hs, Es):
hq = [(-h/g, i) for i, (g, h) in enumerate(zip(gs, hs))]
hq.sort()
f_diff = set()
while hq:
p, i = heapq.heappop(hq)
if fs[i] or i in f_diff:
continue
update_fs(fs, f_diff)
f_diff = set()
dfs(p, i, hq, f_diff, fs, gs, hs, Es)
return [i + 1 for i, f in enumerate(fs) if not f]
def update_fs(fs, f_diff):
for f in f_diff:
fs[f] = True
def dfs(p, i, hq, f_diff, fs, gs, hs, Es):
fifo = [i]
f_diff.add(i)
while fifo:
i = fifo.pop(-1)
for j in Es[i]:
if fs[j] or j in f_diff:
continue
hs[j] += 1
pj = -hs[j]/gs[j]
if pj > p:
heapq.heappush(hq, (pj, j))
else:
fifo.append(j)
f_diff.add(j)
if __name__ == '__main__':
n, m, k, fs, gs, hs, Es = read_data()
beaches = solve(n, m, k, fs, gs, hs, Es)
print(len(beaches))
print(*beaches)
|
1435163400
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["YES\n1 3 5\nNO\nNO"]
|
7f5269f3357827b9d8682d70befd3de1
| null |
You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You want to split it into exactly $$$k$$$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $$$n$$$ elements of the array $$$a$$$ must belong to exactly one of the $$$k$$$ subsegments.Let's see some examples of dividing the array of length $$$5$$$ into $$$3$$$ subsegments (not necessarily with odd sums): $$$[1, 2, 3, 4, 5]$$$ is the initial array, then all possible ways to divide it into $$$3$$$ non-empty non-intersecting subsegments are described below: $$$[1], [2], [3, 4, 5]$$$; $$$[1], [2, 3], [4, 5]$$$; $$$[1], [2, 3, 4], [5]$$$; $$$[1, 2], [3], [4, 5]$$$; $$$[1, 2], [3, 4], [5]$$$; $$$[1, 2, 3], [4], [5]$$$. Of course, it can be impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.You have to answer $$$q$$$ independent queries.
|
For each query, print the answer to it. If it is impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as $$$k$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_k$$$ such that $$$1 \le r_1 < r_2 < \dots < r_k = n$$$, where $$$r_j$$$ is the right border of the $$$j$$$-th segment (the index of the last element that belongs to the $$$j$$$-th segment), so the array is divided into subsegments $$$[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]$$$. Note that $$$r_k$$$ is always $$$n$$$ but you should print it anyway.
|
The first line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,200 |
train_007.jsonl
|
8c040a7744f61d6ad7a8755fac6e80f0
|
256 megabytes
|
["3\n5 3\n7 18 3 14 1\n5 4\n1 2 3 4 5\n6 2\n1 2 8 4 10 2"]
|
PASSED
|
from sys import stdin,stdout
t=int(stdin.readline())
for _ in range(t):
n,k=map(int,stdin.readline().split())
l=list(map(int,stdin.readline().strip().split()))
count=0
i,m=0,0
ans=[]
while i<n:
if l[i]%2==1:
ans.append(i+1)
i+=1
if len(ans)>=k and (len(ans)-k)%2==0:
ans=ans[:k]
ans[len(ans)-1]=n
print('YES')
print(*ans)
else:
print('NO')
|
1563978900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["2\n4\n830690567"]
|
0b3f93005a639a9a51279fae65c15301
|
NoteFor $$$n = 2$$$, both permutations $$$[1, 2]$$$, and $$$[2, 1]$$$ are almost perfect.For $$$n = 3$$$, there are only $$$6$$$ permutations. Having a look at all of them gives us: $$$[1, 2, 3]$$$ is an almost perfect permutation. $$$[1, 3, 2]$$$ is an almost perfect permutation. $$$[2, 1, 3]$$$ is an almost perfect permutation. $$$[2, 3, 1]$$$ is NOT an almost perfect permutation ($$$\lvert p_2 - p^{-1}_2 \rvert = \lvert 3 - 1 \rvert = 2$$$). $$$[3, 1, 2]$$$ is NOT an almost perfect permutation ($$$\lvert p_2 - p^{-1}_2 \rvert = \lvert 1 - 3 \rvert = 2$$$). $$$[3, 2, 1]$$$ is an almost perfect permutation. So we get $$$4$$$ almost perfect permutations.
|
A permutation $$$p$$$ of length $$$n$$$ is called almost perfect if for all integer $$$1 \leq i \leq n$$$, it holds that $$$\lvert p_i - p^{-1}_i \rvert \le 1$$$, where $$$p^{-1}$$$ is the inverse permutation of $$$p$$$ (i.e. $$$p^{-1}_{k_1} = k_2$$$ if and only if $$$p_{k_2} = k_1$$$).Count the number of almost perfect permutations of length $$$n$$$ modulo $$$998244353$$$.
|
For each test case, output a single integer — the number of almost perfect permutations of length $$$n$$$ modulo $$$998244353$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of each test case follows. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$) — the length of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,400 |
train_106.jsonl
|
53ea8df8ffb5e9f51cdc8c8ef7db7ad8
|
256 megabytes
|
["3\n\n2\n\n3\n\n50"]
|
PASSED
|
mod = 998244353
def main():
import sys
input = sys.stdin.readline
# comb init
nmax = 3 * 10 ** 5 + 10 # change here
fac = [0] * nmax
finv = [0] * nmax
inv = [0] * nmax
fac[0] = 1
fac[1] = 1
finv[0] = 1
finv[1] = 1
inv[1] = 1
for i in range(2, nmax):
fac[i] = fac[i - 1] * i % mod
inv[i] = mod - inv[mod % i] * (mod // i) % mod
finv[i] = finv[i - 1] * inv[i] % mod
def comb(n, r):
if n < r:
return 0
else:
return (fac[n] * ((finv[r] * finv[n - r]) % mod)) % mod
F = [1, 1]
for i in range(2, 3 * 10 ** 5 + 1):
F.append((F[-1] + (i - 1) * F[-2]) % mod)
for _ in range(int(input())):
N = int(input())
ans = 0
tmp = 1
pow2 = 1
for k in range(N+1):
if N - 4 * k < 0:
break
ans = (ans + ((comb(N - 2 * k, 2 * k) * F[N - 4 * k]) % mod * (tmp * pow2) % mod) % mod) % mod
tmp = (tmp * (2 * k + 1)) % mod
pow2 = (pow2 * 2) % mod
print(ans)
if __name__ == '__main__':
main()
|
1662474900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3\n6\n1\n1"]
|
d107db1395ded62904d0adff164e5c1e
|
NoteIn the first test case we can divide the elements as follows: $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$. $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$. $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element.
|
You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.
|
For each test case print 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$$$, $$$m$$$ $$$(1 \le n \le 10^5, 1 \le m \le 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_087.jsonl
|
ba3005307e031255389f78c6f868f846
|
256 megabytes
|
["4\n6 4\n2 2 8 6 9 4\n10 8\n1 1 1 5 2 4 4 8 6 7\n1 1\n666\n2 2\n2 4"]
|
PASSED
|
t = int(input())
for p in range(t):
l = list(map(int, input().rstrip().split()))
n = l[0]
m = l[1]
res = []
l1 = list(map(int, input().rstrip().split()))
mydict = {}
count = 0
for a in range(m):
mydict[a] = 0
for i in l1:
mydict[i % m] += 1
for j in range(m):
if mydict[j] == 0:
continue
if j == 0:
count += 1
elif mydict[m - j] != 0:
if mydict[m - j] == mydict[j]:
count += 1
elif abs(mydict[j] - mydict[m - j]) >= 1:
count += abs(mydict[j] - mydict[m - j])
else:
count += 1
mydict[j] = 0
mydict[m - j] = 0
else:
count += mydict[j]
mydict[j] = 0
print(count)
|
1615991700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["202\n13\n19"]
|
fe9279aa95148f0887cc7eeb89afbac6
|
NoteIn the first test case, to reach $$$(2, 2)$$$ you need to make at least one turn, so your path will consist of exactly $$$2$$$ segments: one horizontal of length $$$2$$$ and one vertical of length $$$2$$$. The cost of the path will be equal to $$$2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$$$.In the second test case, one of the optimal paths consists of $$$3$$$ segments: the first segment of length $$$1$$$, the second segment of length $$$3$$$ and the third segment of length $$$2$$$.The cost of the path is $$$1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$$$.In the third test case, one of the optimal paths consists of $$$4$$$ segments: the first segment of length $$$1$$$, the second one — $$$1$$$, the third one — $$$4$$$, the fourth one — $$$4$$$. The cost of the path is $$$1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$$$.
|
Let's say you are standing on the $$$XY$$$-plane at point $$$(0, 0)$$$ and you want to reach point $$$(n, n)$$$.You can move only in two directions: to the right, i. e. horizontally and in the direction that increase your $$$x$$$ coordinate, or up, i. e. vertically and in the direction that increase your $$$y$$$ coordinate. In other words, your path will have the following structure: initially, you choose to go to the right or up; then you go some positive integer distance in the chosen direction (distances can be chosen independently); after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than $$$n - 1$$$ direction changes.As a result, your path will be a polygonal chain from $$$(0, 0)$$$ to $$$(n, n)$$$, consisting of at most $$$n$$$ line segments where each segment has positive integer length and vertical and horizontal segments alternate.Not all paths are equal. You have $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the cost of the $$$i$$$-th segment.Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $$$k$$$ segments ($$$k \le n$$$), then the cost of the path is equal to $$$\sum\limits_{i=1}^{k}{c_i \cdot length_i}$$$ (segments are numbered from $$$1$$$ to $$$k$$$ in the order they are in the path).Find the path of the minimum cost and print its cost.
|
For each test case, print the minimum possible cost of the path from $$$(0, 0)$$$ to $$$(n, n)$$$ consisting of at most $$$n$$$ alternating segments.
|
The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — the costs of each segment. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,500 |
train_104.jsonl
|
0c0aaa7349c8d7260c199b8c4ecbbeb0
|
256 megabytes
|
["3\n2\n13 88\n3\n2 3 1\n5\n4 3 2 1 4"]
|
PASSED
|
import random
from datetime import datetime
import math
now = datetime.now()
cazuri=int(input())
for tt in range(cazuri):
#n,c=map(int,input().split())
n=int(input())
#stringul=input()
bloc=list(map(int,input().split()))
pare=[]
impare=[]
suma_pare=0
suma_impare=0
cate_pare=1
cate_impare=1
suma_totala=0
suma_pare=bloc[0]
suma_impare=bloc[1]
min_pare=bloc[0]
min_impare=bloc[1]
val_pare=bloc[0]*n
val_impare=bloc[1]*n
val_total=val_pare+val_impare
# print("val total=",val_total)
if n==2:
print(val_total)
else:
for i in range(2,n):
if i%2==0:
cate_pare+=1
suma_pare+=bloc[i]
if bloc[i]<min_pare:
min_pare=bloc[i]
val_pare=min_pare*(n+1-cate_pare)+suma_pare-min_pare
val_total=min(val_total,val_pare+val_impare)
else:
cate_impare+=1
suma_impare+=bloc[i]
if bloc[i]<min_impare:
min_impare=bloc[i]
val_impare=min_impare*(n+1-cate_impare)+suma_impare-min_impare
# print("val impare=",val_impare,val_pare)
val_total=min(val_total,val_impare+val_pare)
print(val_total)
|
1616079000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 7\n3 9\n5 10"]
|
a9cd97046e27d799c894d8514e90a377
| null |
You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.
|
Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_006.jsonl
|
a18b61278f52aa0381e702af35798055
|
256 megabytes
|
["3\n1 10\n3 14\n1 10"]
|
PASSED
|
t=int(input())
for _ in range(t):
l,r=map(int,input().split())
print(l,l*2)
|
1546007700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
|
159365b2f037647fbaa656905e6f5252
|
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
|
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
|
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
|
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_036.jsonl
|
eafee7208e6d2f9ec2cacfff6cfbab04
|
256 megabytes
|
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
|
PASSED
|
def binSearch(arr, el):
if len(arr) == 0: return -1
l, p = 0, len(arr)-1
while l != p:
s = (l+p) // 2
if arr[s] < el:
l = s + 1
else:
p = s
return l if arr[l] == el else -1
n = int(input())
a = [int(i) for i in input().split()]
s = sorted(a)
subsList = []
visited = [False for i in range(n)]
for i in range(n):
ind = i
newSub = False
while not visited[ind]:
if not newSub:
subsList.append([])
newSub = True
visited[ind] = True
subsList[-1].append(str(ind+1))
ind = binSearch(s, a[ind])
out = str(len(subsList)) + "\n"
for lineNr in range(len(subsList)-1):
out += str(len(subsList[lineNr])) + " "
out += " ".join(subsList[lineNr]) + "\n"
out += str(len(subsList[-1])) + " "
out += " ".join(subsList[-1])
print(out)
|
1503592500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2 3 4\n1 3\n-1\n1 2 2 5 5"]
|
91d510b68f04971b871718460663ca3b
| null |
You are asked to build an array $$$a$$$, consisting of $$$n$$$ integers, each element should be from $$$1$$$ to $$$k$$$.The array should be non-decreasing ($$$a_i \le a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$). You are also given additional constraints on it. Each constraint is of one of three following types: $$$1~i~x$$$: $$$a_i$$$ should not be equal to $$$x$$$; $$$2~i~j~x$$$: $$$a_i + a_j$$$ should be less than or equal to $$$x$$$; $$$3~i~j~x$$$: $$$a_i + a_j$$$ should be greater than or equal to $$$x$$$. Build any non-decreasing array that satisfies all constraints or report that no such array exists.
|
For each testcase, determine if there exists a non-decreasing array that satisfies all conditions. If there is no such array, then print -1. Otherwise, print any valid array — $$$n$$$ integers from $$$1$$$ to $$$k$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^4$$$; $$$0 \le m \le 2 \cdot 10^4$$$; $$$2 \le k \le 10$$$). The $$$i$$$-th of the next $$$m$$$ lines contains a description of a constraint. Each constraint is of one of three following types: $$$1~i~x$$$ ($$$1 \le i \le n$$$; $$$1 \le x \le k$$$): $$$a_i$$$ should not be equal to $$$x$$$; $$$2~i~j~x$$$ ($$$1 \le i < j \le n$$$; $$$2 \le x \le 2 \cdot k$$$): $$$a_i + a_j$$$ should be less than or equal to $$$x$$$; $$$3~i~j~x$$$ ($$$1 \le i < j \le n$$$; $$$2 \le x \le 2 \cdot k$$$): $$$a_i + a_j$$$ should be greater than or equal to $$$x$$$. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^4$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^4$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,800 |
train_083.jsonl
|
a7700d58ffbd8fbbf545a770cbb2fdb8
|
512 megabytes
|
["4\n\n4 0 4\n\n2 2 3\n\n3 1 2 3\n\n1 2 2\n\n3 3 2\n\n1 1 1\n\n2 2 3 2\n\n3 2 3 2\n\n5 5 5\n\n3 2 5 7\n\n2 4 5 10\n\n3 4 5 6\n\n3 3 4 7\n\n2 1 5 7"]
|
PASSED
|
import sys
input = sys.stdin.readline
# TwoSat code from PyRival: https://github.com/cheran-senthil/PyRival/blob/9947ae98b7884614d98a5860764e85798c0cddfa/pyrival/data_structures/TwoSat.py
def find_SCC(graph):
SCC, S, P = [], [], []
depth = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
d = depth[~node] - 1
if P[-1] > d:
SCC.append(S[d:])
del S[d:], P[-1]
for node in SCC[-1]:
depth[node] = -1
elif depth[node] > 0:
while P[-1] > depth[node]:
P.pop()
elif depth[node] == 0:
S.append(node)
P.append(len(S))
depth[node] = len(S)
stack.append(~node)
stack += graph[node]
return SCC[::-1]
class TwoSat:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(2 * n)]
def _imply(self, x, y):
self.graph[x].append(y if y >= 0 else 2 * self.n + y)
def either(self, x, y):
"""either x or y must be True"""
self._imply(~x, y)
self._imply(~y, x)
def set(self, x):
"""x must be True"""
self._imply(~x, x)
def implies(self, x, y):
self.either(~x, y)
def solve(self):
SCC = find_SCC(self.graph)
order = [0] * (2 * self.n)
for i, comp in enumerate(SCC):
for x in comp:
order[x] = i
for i in range(self.n):
if order[i] == order[~i]:
return False, None
return True, [+(order[i] > order[~i]) for i in range(self.n)]
class Helper:
def __init__(self, i: int): self.i = i
def __ge__(self, x: int): return self.i * (K+1) + x - 1
def __lt__(self, x: int): return ~(self >= x)
def __gt__(self, x: int): return self >= x + 1
def __le__(self, x: int): return self < x + 1
out = []
for _ in range(int(input())):
N, M, K = map(int, input().split())
A = [Helper(i) for i in range(N)]
ts = TwoSat(N*(K+1))
for i in range(N):
ts.set(A[i] >= 1)
ts.set(A[i] <= K)
for k in range(1, K):
ts.implies(A[i] < k, A[i] < k+1)
if i < N-1:
for k in range(1, K+1):
ts.implies(A[i] >= k, A[i+1] >= k)
for _ in range(M):
type, *args = map(int, input().split())
if type == 1:
i, x = args; i -= 1
ts.either(A[i] < x, A[i] > x)
else:
i, j, x = args
i -= 1; j -= 1
if type == 2:
for y in range(1, K+1):
if 1 <= x - y <= K:
ts.implies(A[i] >= y, A[j] <= x - y)
ts.implies(A[j] >= y, A[i] <= x - y)
if x <= K:
ts.set(A[i] < x)
ts.set(A[j] < x)
elif type == 3:
for y in range(1, K+1):
if 1 <= x - y <= K:
ts.implies(A[i] <= y, A[j] >= x - y)
ts.implies(A[j] <= y, A[i] >= x - y)
if x > K:
ts.set(A[i] >= x - K)
ts.set(A[j] >= x - K)
ok, sol = ts.solve()
if not ok:
out.append("-1")
else:
ans = []
for i in range(N):
for k in range(K, 0, -1):
if sol[A[i] >= k]:
ans.append(str(k))
break
else:
assert False
out.append(" ".join(ans))
print("\n".join(out))
|
1655044500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES", "NO", "NO", "NO", "NO", "NO"]
|
6405161be280fea943201fa00ef6f448
|
NoteIn the first example, the given picture contains one "+".In the second example, two vertical branches are located in a different column.In the third example, there is a dot outside of the shape.In the fourth example, the width of the two vertical branches is $$$2$$$.In the fifth example, there are two shapes.In the sixth example, there is an empty space inside of the shape.
|
You have a given picture with size $$$w \times h$$$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below: A "+" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction. All other cells are empty. Find out if the given picture has single "+" shape.
|
If the given picture satisfies all conditions, print "YES". Otherwise, print "NO". You can output each letter in any case (upper or lower).
|
The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \le h$$$, $$$w \le 500$$$) — the height and width of the picture. The $$$i$$$-th of the next $$$h$$$ lines contains string $$$s_{i}$$$ of length $$$w$$$ consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_000.jsonl
|
37ede566651e9e71eb35d9e137c401fa
|
256 megabytes
|
["5 6\n......\n..*...\n.****.\n..*...\n..*...", "3 5\n..*..\n****.\n.*...", "7 7\n.......\n...*...\n..****.\n...*...\n...*...\n.......\n.*.....", "5 6\n..**..\n..**..\n******\n..**..\n..**..", "3 7\n.*...*.\n***.***\n.*...*.", "5 10\n..........\n..*.......\n.*.******.\n..*.......\n.........."]
|
PASSED
|
n,m=map(int,input().split())
a=[]
for i in range(n):
a.append(list(input()))
b=0
for i in a:
b+=i.count('*')
x=y=-1
for i in range(1,n-1):
for j in range(1,m-1):
if a[i][j]==a[i][j-1]==a[i][j+1]==a[i-1][j]==a[i+1][j]=='*':
x=i
y=j
break
if x==y==-1:
exit(print('NO'))
r=1
for i in range(x+1,n):
if a[i][y]=='*':
r+=1
else:
break
for i in range(x-1,-1,-1):
if a[i][y]=='*':
r+=1
else:
break
for i in range(y+1,m):
if a[x][i]=='*':
r+=1
else:
break
for i in range(y-1,-1,-1):
if a[x][i]=='*':
r+=1
else:
break
if r==b:
print('YES')
else:
print('NO')
|
1560258300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["? 1 1\n\n? 1 2\n\n? 1 3\n\n? 2 2 3\n\n! 1 3"]
|
28a14d68fe01c4696ab1ccb7f3932901
|
NoteThe tree from the first test is shown below, and the hidden nodes are $$$1$$$ and $$$3$$$.
|
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.You are given a tree consisting of $$$n$$$ nodes numbered with integers from $$$1$$$ to $$$n$$$. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.More formally, let's define two hidden nodes as $$$s$$$ and $$$f$$$. In one query you can provide the set of nodes $$$\{a_1, a_2, \ldots, a_c\}$$$ of the tree. As a result, you will get two numbers $$$a_i$$$ and $$$dist(a_i, s) + dist(a_i, f)$$$. The node $$$a_i$$$ is any node from the provided set, for which the number $$$dist(a_i, s) + dist(a_i, f)$$$ is minimal.You can ask no more than $$$14$$$ queries.
| null |
The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of test cases. Please note, how the interaction process is organized. The first line of each test case consists of a single integer $$$n$$$ $$$(2 \le n \le 1000)$$$ — the number of nodes in the tree. The next $$$n - 1$$$ lines consist of two integers $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$ — the edges of the tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_005.jsonl
|
9375afcca41149cfb5fbe1002e9e7a02
|
256 megabytes
|
["1\n3\n1 2\n1 3\n\n1 1\n\n2 3\n\n3 1\n\n3 1\n\nCorrect"]
|
PASSED
|
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[nex] > ret[now] + 1:
ret[nex] = ret[now] + 1
plis[nex] = now
q.append(nex)
return ret,plis
tt = int(input())
for loop in range(tt):
n = int(input())
lis = [ [] for i in range(n)]
for i in range(n-1):
v,u = map(int,input().split())
v -= 1
u -= 1
lis[v].append(u)
lis[u].append(v)
print ("?",n,*[i+1 for i in range(n)] , flush=True)
x1,d1 = map(int,input().split())
x1 -= 1
dlis,plis = NC_Dij(lis,x1)
r = max(dlis)+1
l = 0
dic = {}
dic[0] = x1
while r-l != 1:
m = (l+r)//2
#print (l,r,m)
nodes = []
for i in range(n):
if dlis[i] == m:
nodes.append(i+1)
print ("?",len(nodes), *nodes , flush=True)
nx,nd = map(int,input().split())
nx -= 1
dic[m] = nx
if nd == d1:
l = m
else:
r = m
ans1 = dic[l]
dlis2,plis2 = NC_Dij(lis,ans1)
nodes = []
for i in range(n):
if dlis2[i] == d1:
nodes.append(i+1)
print ("?",len(nodes), *nodes , flush=True)
ans2,tmp = map(int,input().split())
print ("!",ans1+1,ans2 , flush=True)
ret = input()
|
1592663700
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
3 seconds
|
["1 0 1 1", "1 1 2 3 4 3 1"]
|
fa71dbe5a8399c963bb2dda121a9bec0
|
NoteHere are all possible ways to separate all computers into $$$4$$$ groups in the second example: $$$\{1, 2\}, \{3, 4\}, \{5\}, \{6, 7\}$$$; $$$\{1\}, \{2\}, \{3, 4\}, \{5, 6, 7\}$$$; $$$\{1, 2\}, \{3\}, \{4\}, \{5, 6, 7\}$$$.
|
There are $$$n$$$ computers in the company network. They are numbered from $$$1$$$ to $$$n$$$.For each pair of two computers $$$1 \leq i < j \leq n$$$ you know the value $$$a_{i,j}$$$: the difficulty of sending data between computers $$$i$$$ and $$$j$$$. All values $$$a_{i,j}$$$ for $$$i<j$$$ are different.You want to separate all computers into $$$k$$$ sets $$$A_1, A_2, \ldots, A_k$$$, such that the following conditions are satisfied: for each computer $$$1 \leq i \leq n$$$ there is exactly one set $$$A_j$$$, such that $$$i \in A_j$$$; for each two pairs of computers $$$(s, f)$$$ and $$$(x, y)$$$ ($$$s \neq f$$$, $$$x \neq y$$$), such that $$$s$$$, $$$f$$$, $$$x$$$ are from the same set but $$$x$$$ and $$$y$$$ are from different sets, $$$a_{s,f} < a_{x,y}$$$. For each $$$1 \leq k \leq n$$$ find the number of ways to divide computers into $$$k$$$ groups, such that all required conditions are satisfied. These values can be large, so you need to find them by modulo $$$998\,244\,353$$$.
|
Print $$$n$$$ integers: the $$$k$$$-th of them should be equal to the number of possible ways to divide computers into $$$k$$$ groups, such that all required conditions are satisfied, modulo $$$998\,244\,353$$$.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1500$$$): the number of computers. The $$$i$$$-th of the next $$$n$$$ lines contains $$$n$$$ integers $$$a_{i,1}, a_{i,2}, \ldots, a_{i,n}$$$($$$0 \leq a_{i,j} \leq \frac{n (n-1)}{2}$$$). It is guaranteed that: for all $$$1 \leq i \leq n$$$ $$$a_{i,i} = 0$$$; for all $$$1 \leq i < j \leq n$$$ $$$a_{i,j} > 0$$$; for all $$$1 \leq i < j \leq n$$$ $$$a_{i,j} = a_{j,i}$$$; all $$$a_{i,j}$$$ for $$$i <j$$$ are different.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_041.jsonl
|
760f91f2cf5fbaee4a8dc55fce18e84b
|
256 megabytes
|
["4\n0 3 4 6\n3 0 2 1\n4 2 0 5\n6 1 5 0", "7\n0 1 18 15 19 12 21\n1 0 16 13 17 20 14\n18 16 0 2 7 10 9\n15 13 2 0 6 8 11\n19 17 7 6 0 4 5\n12 20 10 8 4 0 3\n21 14 9 11 5 3 0"]
|
PASSED
|
# import itertools as it
# import functools as ft
import math
teststring = """4
0 3 4 6
3 0 2 1
4 2 0 5
6 1 5 0
"""
online = __file__ != "/home/jhli/py/Grakn/Problem_G2.py"
true, false = True, False
if True:
def spitout():
for c in teststring.splitlines():
yield c
_ito = spitout()
if not online:
def input():
return next(_ito)
def build_enum(*a):
built = dict()
for i, c in enumerate(a):
built[c] = i
return lambda x: built[x]
# T = 1
# T = int(input())
##-----------------start coding-----------------
n = int(input())
E = [(0, 0)] * (int(n*(n-1)/2))
P = 998244353
for i in range(n):
L = list(map(int, input().split(" ")))
for j in range(i+1, n):
E[L[j]-1] = (i, j)
R = list(range(n))
C = [[0, 1] for _ in range(n)]
Nv = [1] * n
Ne = [0] * n
def root(x):
if x == R[x]:
return x
else:
R[x] = y = root(R[x])
return y
def prod(A, B, da, db):
C = [0] * (min(da+db, n) + 1)
for i in range(da+1):
for j in range(db+1):
if i + j <= n:
C[i+j] += A[i] * B[j]
C[i+j] %= P
return C
# print(E)
# print("")
for (x, y) in E:
r = rx = root(x)
ry = root(y)
# print((x, y, w), (rx, ry))
if rx != ry:
if r > ry: r = ry
R[rx] = R[ry] = r
C[r] = prod(C[rx], C[ry], Nv[rx], Nv[ry])
Nv[r] = Nv[rx] + Nv[ry]
Ne[r] = Ne[rx] + Ne[ry] + 1
else:
Ne[r] += 1
if Ne[r]*2 == Nv[r] * (Nv[r] - 1):
C[r][1] = 1
# print("R", R)
# print("Nv", Nv)
# print("Ne", Ne)
# print("C", C)
# print("")
print(" ".join(map(str, C[0][1:n+1])))
# print('Case #{}: {}'.format(ti, '...'))
|
1601476500
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["4.2426406871", "6.1622776602"]
|
900a509495f4f63f4fa5b66b7edd84f7
|
NoteThe first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot.
|
In this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind $$$x = c$$$ and $$$y = c$$$ for every integer $$$c$$$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $$$(x, y)$$$ for which $$$ax + by + c = 0$$$.One can walk along streets, including the avenue. You are given two integer points $$$A$$$ and $$$B$$$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $$$B$$$ from $$$A$$$.
|
Find the minimum possible travel distance between $$$A$$$ and $$$B$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
The first line contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$-10^9\leq a, b, c\leq 10^9$$$, at least one of $$$a$$$ and $$$b$$$ is not zero) representing the Diagonal Avenue. The next line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9\leq x_1, y_1, x_2, y_2\leq 10^9$$$) denoting the points $$$A = (x_1, y_1)$$$ and $$$B = (x_2, y_2)$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_005.jsonl
|
701fb48b8a43d491c2907c65e77732ea
|
256 megabytes
|
["1 1 -3\n0 3 3 0", "3 1 -9\n0 3 3 -1"]
|
PASSED
|
from math import ceil,floor
a,b,c = (int(e) for e in input().split(' '))
x1,y1,x2,y2 = (int(e) for e in input().split(' '))
def dist(x1,y1,x2,y2):
return ((x1-x2)**2+(y1-y2)**2)**.5
def m_dist(x1,y1,x2,y2):
return abs(x1-x2)+abs(y1-y2)
def project(x,y):
if(a==0 and b==0):return (float('inf'),float('inf'))
return ((-c*a+b*b*x-a*b*y)/(a*a+b*b),(-a*b*x+a*a*y-b*c)/(a*a+b*b))
def x_to_y(x):
if(b==0):return float('inf')
return (-c-a*x)/b
def y_to_x(y):
if(a==0):return float('inf')
return (-c-b*y)/a
point1x,point1y = project(x1,y1)
point1s = []
t = ceil(point1x)
point1s.append((t,x_to_y(t)))
t = floor(point1x)
point1s.append((t,x_to_y(t)))
t = ceil(point1y)
point1s.append((y_to_x(t),t))
t = floor(point1y)
point1s.append((y_to_x(t),t))
point1s.append((y_to_x(y1),y1))
point1s.append((x1,x_to_y(x1)))
point2x,point2y = project(x2,y2)
point2s = []
t = ceil(point2x)
point2s.append((t,x_to_y(t)))
t = floor(point2x)
point2s.append((t,x_to_y(t)))
t = ceil(point2y)
point2s.append((y_to_x(t),t))
t = floor(point2y)
point2s.append((y_to_x(t),t))
point2s.append((y_to_x(y2),y2))
point2s.append((x2,x_to_y(x2)))
res = m_dist(x1,y1,x2,y2)
for p1 in point1s:
for p2 in point2s:
t = m_dist(x1,y1,p1[0],p1[1])
t += dist(p1[0],p1[1],p2[0],p2[1])
t += m_dist(x2,y2,p2[0],p2[1])
# print(p1,p2,t)
if(res>t):
res = t
print(res)
# print(point1x,point1y)
# print(point2x,point2y)
|
1542557100
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"]
|
a291ee66980d8b5856b24d1541e66fd0
|
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
|
This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_026.jsonl
|
ba187886f099ff7620afdc75f4593b91
|
256 megabytes
|
["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"]
|
PASSED
|
import collections
import sys
def getAnc(u,v):
print('? {} {}'.format(u,v))
w = int(input())
sys.stdout.flush()
return w
def f():
n = int(input())
neibors = [set() for i in range(n+1)]
for i in range(n-1):
a, b = [int(s) for s in input().split()]
neibors[a].add(b)
neibors[b].add(a)
visited = [0]*(n+1)
rem = [n]
def bfs(u,v,w):
q = collections.deque()
if u != w:
visited[u] = 1
rem[0] -= 1
q.append(u)
if v != w:
visited[v] = 1
rem[0] -= 1
q.append(v)
while q:
node = q.popleft()
for nb in neibors[node]:
if (nb != w) and (not visited[nb]):
visited[nb] = 1
rem[0] -= 1
q.append(nb)
while rem[0] > 1:
for i in range(1,n+1):
if not visited[i]:
u = i
break
for i in range(u+1,n+1):
if not visited[i]:
v = i
break
if (v in neibors[u]) and rem[0] > 2:
for i in range(v+1,n+1):
if not visited[i]:
x = i
break
if x in neibors[u]:
u = x
else:
v = x
w = getAnc(u,v)
bfs(u,v,w)
for i in range(1,n+1):
if not visited[i]:
print('! {}'.format(i))
return
f()
|
1583246100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["YES\nabacaba", "NO", "YES\naaaaaaaaa"]
|
02845c8982a7cb6d29905d117c4a1079
| null |
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
|
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO". If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
|
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got. Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_043.jsonl
|
504146461e3f019f8702cff9d68b165b
|
256 megabytes
|
["5\naca\naba\naba\ncab\nbac", "4\nabc\nbCb\ncb1\nb13", "7\naaa\naaa\naaa\naaa\naaa\naaa\naaa"]
|
PASSED
|
n = int(input())
g = {}
ins = {}
outs = {}
vs = set()
for _ in range(n):
s = input().strip()
left = s[:-1]
right = s[1:]
g.setdefault(left, []).append(right)
outs[left] = outs.get(left, 0) + 1
ins[right] = ins.get(right, 0) + 1
vs.add(left)
vs.add(right)
# print(g)
# print(outs)
# print(ins)
wrong = []
for v in vs:
# print(v, outs.get(v, 0), ins.get(v, 0))
if outs.get(v, 0) != ins.get(v, 0):
wrong.append(v)
# print(wrong)
if len(wrong) not in (0, 2):
print("NO")
exit()
if wrong:
a, b = wrong
if abs(ins.get(a, 0) - outs.get(a, 0)) != 1 or abs(ins.get(b, 0) - outs.get(b, 0)) != 1:
print("NO")
exit()
if ins.get(a, 0) < outs.get(a, 0):
a, b = b, a
stack = [a, b]
else:
stack = [next(iter(g))]
ans = []
while stack:
v = stack[-1]
# print("ON STACK", v)
if not g.get(v, []):
if ans:
ans.append(v[0])
else:
ans.append(v)
# print("TO ANS", v)
stack.pop(-1)
else:
u = g[v].pop()
# print("GO TO", u, g)
stack.append(u)
if wrong:
ans.pop(-1)
ans.reverse()
if len(ans) != n + 1:
print("NO")
else:
print("YES")
print("".join(ans))
|
1422376200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["3\naca\nba\nca", "0"]
|
dd7ccfee8c2a19bf47d65d5a62ac0071
|
NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
|
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction — it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
|
On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order.
|
The only line contains a string s (5 ≤ |s| ≤ 104) consisting of lowercase English letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_006.jsonl
|
f48d2bfb0aa9858161bdb7fd198e3620
|
256 megabytes
|
["abacabaca", "abaca"]
|
PASSED
|
s = input()
n = len(s)
res = set()
from collections import defaultdict
two = ["$", "", "$"]
thr = ["$", "", "$"]
works = lambda w, i : (two[i] != "$" and w != two[i]) or (thr[i] != "$" and w != thr[i])
i = n - 2
while i > 4:
ntwo = s[i: i + 2]
if works(ntwo, 1):
res.add(ntwo)
else:
ntwo = "$"
if (i <= n - 3):
nthr = s[i: i + 3]
if works(nthr, 2):
res.add(nthr)
else:
nthr = "$"
else:
nthr = "$"
two = [ntwo] + two[0:2]
thr = [nthr] + thr[0:2]
i -= 1
res = list(res)
res.sort()
print(len(res))
for word in res:
print(word)
|
1461947700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["3", "1"]
|
c547e32f114546638973e0f0dd16d1a4
|
NoteIn the first sample any pair (i, j) will do, so the answer is 3.In the second sample only pair (1, 2) will do.
|
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0) = 0; f(2·x) = f(x); f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.
|
In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). The numbers in the lines are separated by single spaces.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_039.jsonl
|
895a477819d71788a14add9a33757af1
|
256 megabytes
|
["3\n1 2 4", "3\n5 3 1"]
|
PASSED
|
def f(x):
return str(bin(x)).count('1')
n = int(input())
a = list(map(int, input().split()))
ans = [f(x) for x in a]
# print(ans)
s = set(ans)
counts = {x:ans.count(x) for x in s}
# print(counts)
count = 0
for item in counts:
count += (counts[item]*(counts[item]-1))//2
print(count)
|
1360769400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n0\n3"]
|
bfc2e7de37db4a0a74cdd55f2124424a
|
NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.
|
You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second: Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.
|
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 single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. 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}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_010.jsonl
|
199130a00997bbfa57cd8fe0621e5b2f
|
256 megabytes
|
["3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4"]
|
PASSED
|
#logic#####maintain two pointer that will maintain the maximum difference between
#two values and values that are not follwing the a<=b condition
def powerof2(x):
i=0
while 2**i<=x:
i+=1
return i
from sys import stdout
for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
maz,miz=l[0],l[0]
cnt_max=0
for i in range(1,n):
cnt=0
if l[i]<maz:
if l[i]<miz:
miz=l[i]
else:
cnt=powerof2(maz-miz)
maz,miz=l[i],l[i]
if cnt>cnt_max:
cnt_max=cnt
if i==n-1 and maz-miz>0:
cnt=powerof2(maz-miz)
if cnt>cnt_max:
cnt_max=cnt
stdout.write(str(cnt_max) + "\n")
|
1586700300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["144", "48", "4", "9"]
|
c9b4ff8729ab152b7c58dd9fdb5d89a7
| null |
You have a large rectangular board which is divided into $$$n \times m$$$ cells (the board has $$$n$$$ rows and $$$m$$$ columns). Each cell is either white or black.You paint each white cell either red or blue. Obviously, the number of different ways to paint them is $$$2^w$$$, where $$$w$$$ is the number of white cells.After painting the white cells of the board, you want to place the maximum number of dominoes on it, according to the following rules: each domino covers two adjacent cells; each cell is covered by at most one domino; if a domino is placed horizontally (it covers two adjacent cells in one of the rows), it should cover only red cells; if a domino is placed vertically (it covers two adjacent cells in one of the columns), it should cover only blue cells. Let the value of the board be the maximum number of dominoes you can place. Calculate the sum of values of the board over all $$$2^w$$$ possible ways to paint it. Since it can be huge, print it modulo $$$998\,244\,353$$$.
|
Print one integer — the sum of values of the board over all $$$2^w$$$ possible ways to paint it, taken modulo $$$998\,244\,353$$$.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$; $$$nm \le 3 \cdot 10^5$$$) — the number of rows and columns, respectively. Then $$$n$$$ lines follow, each line contains a string of $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th string is * if the $$$j$$$-th cell in the $$$i$$$-th row is black; otherwise, that character is o.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100 |
train_089.jsonl
|
fa702afe87e2c0e29056f9360786072d
|
512 megabytes
|
["3 4\n**oo\noo*o\n**oo", "3 4\n**oo\noo**\n**oo", "2 2\noo\no*", "1 4\noooo"]
|
PASSED
|
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
n,m = I()
l = []
w = 0
mod = 998244353
an = 0
N = 3*10**5 + 20
dp = [0]*(N)
s = prev = dp[2] = 1
for i in range(n):
l.append(input().strip())
w += l[-1].count('o')
for i in range(w-2):
dp[i+3] = (2*prev + s) % mod
if (i & 1): s = (s * 2 - 1) % mod
else: s = (s * 2 + 1) % mod
prev = dp[i+3]
dp[i+3] = (dp[i+3]*pow(2,w-2-i-1,mod))%mod
dp[2] = (dp[2]*pow(2,w-2,mod) if w>=2 else 0)%mod
for i in range(n):
ct = 0
for j in range(m):
if l[i][j] == 'o':
ct+=1
else:
an = (an + dp[ct])%mod
ct=0
an = (an + dp[ct])%mod
for j in range(m):
ct = 0
for i in range(n):
if l[i][j] == 'o':
ct+=1
else:
an = (an + dp[ct])%mod
ct=0
an = (an + dp[ct])%mod
print(an)
|
1618238100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["aaa", "nisteaadddiiklooprrvz", "ababacabcc"]
|
9dc956306e2826229e393657f2d0d9bd
|
NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.
|
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?
|
Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.
|
The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters. It is possible that b and c coincide.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,800 |
train_008.jsonl
|
0e795f753c9fd7ab66ee9b3145a19008
|
256 megabytes
|
["aaa\na\nb", "pozdravstaklenidodiri\nniste\ndobri", "abbbaaccca\nab\naca"]
|
PASSED
|
__author__ = 'trunghieu11'
from string import ascii_lowercase
def main():
s = raw_input()
a = raw_input()
b = raw_input()
totalS = dict()
totalA = dict()
totalB = dict()
for c in ascii_lowercase:
totalS.setdefault(c, s.count(c))
totalA.setdefault(c, a.count(c))
totalB.setdefault(c, b.count(c))
maxA = min(totalS[c] / totalA[c] for c in ascii_lowercase if totalA[c] > 0)
maxVal = [0, 0]
for i in range(maxA + 1):
tempS = totalS.copy()
for c in ascii_lowercase:
if totalA[c] > 0:
tempS[c] -= totalA[c] * i
remainB = min(tempS[c] / totalB[c] for c in ascii_lowercase if totalB[c] > 0)
for c in ascii_lowercase:
if totalB[c] > 0:
tempS[c] -= totalB[c] * remainB
if maxVal[0] + maxVal[1] < i + remainB:
maxVal = [i, remainB]
answer = maxVal[0] * a + maxVal[1] * b
for c in ascii_lowercase:
answer += c * (totalS[c] - totalA[c] * maxVal[0] - totalB[c] * maxVal[1])
print answer
if __name__ == '__main__':
main()
|
1434127500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1\n1\n-1\n6\n1 2 3 5 6 7"]
|
afe8710473db82f8d53d28dd32646774
|
NoteIn the first test case, you can take the item of weight $$$3$$$ and fill the knapsack just right.In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is $$$-1$$$.In the third test case, you fill the knapsack exactly in half.
|
You have a knapsack with the capacity of $$$W$$$. There are also $$$n$$$ items, the $$$i$$$-th one has weight $$$w_i$$$. You want to put some of these items into the knapsack in such a way that their total weight $$$C$$$ is at least half of its size, but (obviously) does not exceed it. Formally, $$$C$$$ should satisfy: $$$\lceil \frac{W}{2}\rceil \le C \le W$$$. Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack.
|
For each test case, if there is no solution, print a single integer $$$-1$$$. If there exists a solution consisting of $$$m$$$ items, print $$$m$$$ in the first line of the output and $$$m$$$ integers $$$j_1$$$, $$$j_2$$$, ..., $$$j_m$$$ ($$$1 \le j_i \le n$$$, all $$$j_i$$$ are distinct) in the second line of the output — indices of the items you would like to pack into the knapsack. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack.
|
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 integers $$$n$$$ and $$$W$$$ ($$$1 \le n \le 200\,000$$$, $$$1\le W \le 10^{18}$$$). The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^9$$$) — weights of the items. The sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_003.jsonl
|
f5f0a75f2b5579756d5a897ff38c4d90
|
256 megabytes
|
["3\n1 3\n3\n6 2\n19 8 19 69 9 4\n7 12\n1 1 1 17 1 1 1"]
|
PASSED
|
from sys import stdin,stdout
from math import ceil
for _ in range(int(stdin.readline())):
# n=int(stdin.readline())
n,w=list(map(int,stdin.readline().split()))
a=list(map(int,stdin.readline().split()))
l=[]
for i in range(n):
if a[i]>w:continue
l+=[[a[i],i]]
l.sort();n=len(l)
p=-1;sm=0;ans=[]
mnw=ceil(w/2)
for i in range(n):
if mnw<=l[i][0]<=w:
p=l[i][1]+1
break
if n==0 or l[0][0] > w:
print(-1)
continue
if p!=-1:
print(1)
print(p)
continue
f=0
for i in range(n-1,-1,-1):
sm+=l[i][0]
ans+=[l[i][1]+1]
if mnw<=sm:
f=1
break
if f==0:print(-1)
else:
print(len(ans))
print(*ans)
|
1605450900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
6 seconds
|
["2\n5"]
|
951437dba30c662838b6832b194b5efe
| null |
You are given a rooted tree consisting of n vertices. Each vertex has a number written on it; number ai is written on vertex i.Let's denote d(i, j) as the distance between vertices i and j in the tree (that is, the number of edges in the shortest path from i to j). Also let's denote the k-blocked subtree of vertex x as the set of vertices y such that both these conditions are met: x is an ancestor of y (every vertex is an ancestor of itself); d(x, y) ≤ k. You are given m queries to the tree. i-th query is represented by two numbers xi and ki, and the answer to this query is the minimum value of aj among such vertices j such that j belongs to ki-blocked subtree of xi.Write a program that would process these queries quickly!Note that the queries are given in a modified way.
|
Print m integers. i-th of them has to be equal to the answer to i-th query.
|
The first line contains two integers n and r (1 ≤ r ≤ n ≤ 100000) — the number of vertices in the tree and the index of the root, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the numbers written on the vertices. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n) and representing an edge between vertices x and y. It is guaranteed that these edges form a tree. Next line contains one integer m (1 ≤ m ≤ 106) — the number of queries to process. Then m lines follow, i-th line containing two numbers pi and qi, which can be used to restore i-th query (1 ≤ pi, qi ≤ n). i-th query can be restored as follows: Let last be the answer for previous query (or 0 if i = 1). Then xi = ((pi + last) mod n) + 1, and ki = (qi + last) mod n.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,300 |
train_060.jsonl
|
636ee8d926b7ae419532b091e83824c8
|
512 megabytes
|
["5 2\n1 3 2 3 5\n2 3\n5 1\n3 4\n4 1\n2\n1 2\n2 3"]
|
PASSED
|
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
def sync_with_stdio(b):
if b: return
import os, sys
from io import BytesIO, IOBase
# FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod
class FastI(object):
def __init__(self, fd=0, buffersize=2**14):
self.stream = stream = BytesIO(); self.bufendl = 0
def read2buffer():
s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell()
stream.seek(0,2); stream.write(s); stream.seek(pos); return s
self.read2buffer = read2buffer
# Read entire input
def read(self):
while self.read2buffer(): pass
return self.stream.read() if self.stream.tell() else self.stream.getvalue()
def readline(self):
while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b"\n") + (not s)
self.bufendl -= 1; return self.stream.readline()
def input(self): return self.readline().rstrip(b'\r\n')
# Read all remaining integers, type is given by optional argument
def readnumbers(self, zero=0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; c = b"-"[0]
for c in self.read():
if c >= b"0"[0]: numb = 10 * numb + conv(c) - 48
elif c == b"-"[0]: sign = -1
elif c != b"\r"[0]: A.append(sign*numb); numb = zero; sign = 1
if c >= b"0"[0]: A.append(sign*numb)
return A
class FastO(IOBase):
def __init__(self, fd=1):
stream = BytesIO()
self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0)
self.write = stream.write if py2 else lambda s: stream.write(s.encode())
sys.stdin, sys.stdout = FastI(), FastO()
global input
input = sys.stdin.input
import sys
class ostream:
def __lshift__(self,a):
if a == endl:
sys.stdout.write("\n")
sys.stdout.flush()
else:
sys.stdout.write(str(a))
return self
def tie(self, val):pass
cout = ostream()
endl = object()
class istream:
tiedto = cout
inp = None
def __rlshift__(a,b):
if a.tiedto == cout:
sys.stdout.flush()
if type(b)==tuple or type(b)==list:
return type(b)(type(c)(a.get()) for c in b)
return type(b)(a.get())
def tie(self, val):
self.tiedto = val
def get(a):
while not a.inp:
a.inp = sys.stdin.readline().split()[::-1]
return a.inp.pop()
cin = istream()
class Vector:
def __lshift__(self, other):
self.type = other
return self
def __rshift__(self, other):
if type(other) == tuple:
return [self.type(other[1])]*other[0]
else:
return [self.type()]*other
vector = Vector()
sync_with_stdio(False);
cin.tie(0); cout.tie(0);
########################## PERSISTENT SEGMENTTREE (surprisingly good memory effecient)
BIG = 10**9
vals = []
L = []
R = []
# Create a persistant segmenttree of size n
def create(n):
ind = len(vals)
vals.append(BIG)
L.append(-1)
R.append(-1)
if n==1:
L[ind] = -1
R[ind] = -1
else:
mid = n//2
L[ind] = create(mid)
R[ind] = create(n - mid)
return ind
# Set seg[i]=val for segment tree ind, of size n,
def setter(ind, i, val, n):
ind2 = len(vals)
vals.append(BIG)
L.append(-1)
R.append(-1)
if n==1:
vals[ind2] = val
return ind2
mid = n//2
if i < mid:
L[ind2] = setter(L[ind], i, val, mid)
R[ind2] = R[ind]
else:
L[ind2] = L[ind]
R[ind2] = setter(R[ind], i - mid, val, n - mid)
vals[ind2] = min(vals[L[ind2]], vals[R[ind2]])
return ind2
# Find minimum of seg[l:r] for segment tree ind, of size n
def minimum(ind, l, r, n):
if l==0 and r==n:
return vals[ind]
mid = n//2
if r <= mid:
return minimum(L[ind], l, r, mid)
elif mid<=l:
return minimum(R[ind], l - mid, r - mid, n - mid)
else:
return min( minimum(L[ind], l, mid, mid), minimum(R[ind], 0, r - mid, n - mid))
######################################################################
import sys
inp = sys.stdin.readnumbers()
ii = 0
n = inp[ii]
ii += 1
r = inp[ii]-1
ii += 1
A = inp[ii:ii+n]
ii += n
coupl = [[] for _ in range(n)]
for _ in range(n-1):
x,y = inp[ii]-1, inp[ii+1]-1
ii += 2
coupl[x].append(y)
coupl[y].append(x)
# Start reordering the nodes after DFS ordering
found = [False]*n
found[r] = True
Qdum = [r]
Q = []
while Qdum:
node = Qdum.pop()
Q.append(node)
for nei in coupl[node]:
if not found[nei]:
found[nei] = True
Qdum.append(nei)
mapper = [-1]*n
for i,node in enumerate(Q):
mapper[node] = i
couplprim = []
for node in range(n):
couplprim.append([mapper[nei] for nei in coupl[Q[node]]])
rprim = 0
assert(rprim == mapper[r])
Aprim = [A[Q[i]] for i in range(n)]
# Nodes has been reordered, now figure out some DFS stuff like dfs, family size
depth = [-1]*n
family_size = [0]*n
depth[rprim] = 0
Qprim = [rprim]
first_time = [True]*n
while Qprim:
node = Qprim.pop()
if first_time[node]:
first_time[node] = False
Qprim.append(node)
for nei in couplprim[node]:
if depth[nei] == -1:
depth[nei] = depth[node]+1
Qprim.append(nei)
else:
f = 1
for nei in couplprim[node]:
f += family_size[nei]
family_size[node] = f
# Time to bucket sort the nodes in order of depth
D = [[] for _ in range(2*n)]
for node in range(n):
D[depth[node]].append(node)
##################### PERSISTENT SEGMENT TREE PART
# So simple, yet so much going on
Dseg = [0]*(2*n)
ind = create(n)
for i,nodes in enumerate(D):
for node in nodes:
ind = setter(ind, node, Aprim[node], n)
Dseg[i] = ind
#############################
m = inp[ii]
ii += 1
ans = 0
for _ in range(m):
p = inp[ii]
ii += 1
q = inp[ii]
ii += 1
x = mapper[(p + ans)%n]
k = (q + ans)%n
ans = minimum(Dseg[depth[x]+k], x, x + family_size[x], n)
cout << ans << "\n"
|
1511449500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["Yes\nYes\nYes\nYes\nNo\nNo\nNo\nNo"]
|
02a94c136d3fb198025242e91264823b
| null |
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".
|
Print $$$n$$$ lines, one line per a string in the input. The line should contain "Yes" if the corresponding string is diverse and "No" if the corresponding string is not diverse. You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
|
The first line contains integer $$$n$$$ ($$$1 \le n \le 100$$$), denoting the number of strings to process. The following $$$n$$$ lines contains strings, one string per line. Each string contains only lowercase Latin letters, its length is between $$$1$$$ and $$$100$$$, inclusive.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800 |
train_012.jsonl
|
ead1164382ae45ce5521ff61c97a23fb
|
256 megabytes
|
["8\nfced\nxyz\nr\ndabcef\naz\naa\nbad\nbabc"]
|
PASSED
|
from sys import stdin
lines = stdin.readlines()
n = int(lines[0])
dikte = {}
alphabet = "abcdefghijklmnopqrstuvwxyz"
j = 1
for i in alphabet:
dikte[i] = j
j += 1
for i in range(1,n+1):
c = lines[i][:-1]
c2 = (sorted(c))
liste = []
flag = True
for j in c2:
if j not in liste:
liste.append(j)
else:
print "NO"
flag = False
break
c3 = dikte[c2[-1]]-dikte[c2[0]]
if flag==True and c3!=len(c2)-1:
print "NO"
elif flag==True and c3==len(c2)-1:
print "YES"
|
1554041100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["1", "2"]
|
2535fc09ce74b829c26e1ebfc1ee17c6
|
NoteIn the first sample, Daru should reorder the boxes after adding box 3 to the stack.In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.
|
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
|
Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.
|
The first line of input contains the integer n (1 ≤ n ≤ 3·105) — the number of boxes. Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≤ x ≤ n) follows, indicating that Daru should add the box with number x to the top of the stack. It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_026.jsonl
|
2b55fadeb0f40cb59bef1a182aaf4c1d
|
256 megabytes
|
["3\nadd 1\nremove\nadd 2\nadd 3\nremove\nremove", "7\nadd 3\nadd 2\nadd 1\nremove\nadd 4\nremove\nremove\nremove\nadd 6\nadd 7\nadd 5\nremove\nremove\nremove"]
|
PASSED
|
n=int(input())
st=[]
ans=0
c=0
for _ in range(2*n):
s=input()
if s=="remove":
if len(st)==0 or c+1==st[-1] :
if len(st)!=0:
st.pop(-1)
c+=1
else:
ans+=1
c+=1
st=[]
else:
st.append(int(s[4:]))
#print (st,end=" ")
#print (ans)
print (ans)
|
1498401300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["4\n10\n0\n-1"]
|
589f3f7366d1e0f9185ed0926f5a10bb
|
NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.
|
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?
|
For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.
|
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 109; 0 ≤ p ≤ q ≤ 109; y > 0; q > 0). It is guaranteed that p / q is an irreducible fraction. Hacks. For hacks, an additional constraint of t ≤ 5 must be met.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_022.jsonl
|
3250c5ec22718575ee713bdced1eae72
|
256 megabytes
|
["4\n3 10 1 2\n7 14 3 8\n20 70 2 7\n5 6 1 1"]
|
PASSED
|
def check(k):
n1 = k*p - x
n2 = k*q - y
assert(n1 >= 0)
return n1 <= n2
t = int(input())
for _ in range(t):
[x, y, p, q] = list(map(int, input().split(" ")))
if p == 0 and x > 0:
print(-1)
continue
if p == 0 and x == 0:
print(0)
continue
st = max((x+p-1)//p, (y+q-1)//q)
a = st-1
b = 10**18
while(b - a > 1):
m = (a+b)//2
if check(m):
b = m
else:
a = m
res = -1
if b != 1e18:
res = b*q - y
print(res)
|
1494171900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["OR 1 2\n\nOR 2 3\n\nXOR 2 4\n\n! 0 0 2 3"]
|
efa7be3ab630a3797d5eb7a37202fb76
|
NoteThe array $$$a$$$ in the example is $$$[0, 0, 2, 3]$$$.
|
The only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array $$$a$$$ of $$$n$$$ integers which he wants Ashish to guess. Note that $$$n$$$ is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND $$$i$$$ $$$j$$$: ask for the bitwise AND of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ OR $$$i$$$ $$$j$$$: ask for the bitwise OR of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ XOR $$$i$$$ $$$j$$$: ask for the bitwise XOR of elements $$$a_i$$$ and $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range $$$[0, n-1]$$$ (inclusive) and Ashish can ask no more than $$$n+2$$$ queries.
| null |
The first line of input contains one integer $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — the length of the array. It is guaranteed that $$$n$$$ is a power of two.
|
standard output
|
standard input
|
PyPy 2
|
Python
| null |
train_027.jsonl
|
21d612f8faf5e09689e4e985373742d7
|
256 megabytes
|
["4\n\n0\n\n2\n\n3"]
|
PASSED
|
from collections import Counter, defaultdict, deque
import bisect
import heapq
from sys import stdin, stdout
from itertools import repeat
import math
import random
# sys.stdin = open('input')
def mod(x, y, mod):
re = 1
now = x
while y:
if y&1:
re *= now
re %= mod
y >>= 1
now = (now*now)%mod
return re
def inp(force_list=False):
re = map(int, raw_input().split())
if len(re) == 1 and not force_list:
return re[0]
return re
def inst():
return raw_input().strip()
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def ggcd(x, y):
if y:
return ggcd(y, x%y)
return x
MOD = int(1e9+7)
def query(st, x, y):
print "%s %s %s" % (st, x, y)
stdout.flush()
return inp()
def my_main():
T = 1
for _ in range(T):
n = inp()
qq = []
idx = -1
st = {}
x, y = -1, -1
xx, yy = -1, -1
for i in range(2, n+1):
qq.append(query('XOR', 1, i))
if qq[-1] == 0:
idx = i
if qq[-1] in st:
x, y = st[qq[-1]], i
if qq[-1] == 1:
xx = i
if qq[-1] == 2:
yy = i
st[qq[-1]] = i
if idx != -1:
a = query('OR', 1, idx)
elif x!=-1 and y!=-1:
t = query('OR', x, y)
a = t^qq[x-2]
else:
pre = query('OR', 1, xx)
fix = query('AND', 1, yy)
a = pre - pre%2 + fix%2
ans = [a]
for re in qq:
ans.append(re^a)
print '!', ' '.join(map(str, ans))
my_main()
|
1605969300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4\naabbbbbba"]
|
3ffb3a2ae3e96fc26d539c9676389ae5
|
NoteThe tree from the sample is shown below: The tree after assigning characters to every node (according to the output) is the following: Strings for all nodes are the following: string of node $$$1$$$ is: a string of node $$$2$$$ is: aa string of node $$$3$$$ is: aab string of node $$$4$$$ is: aab string of node $$$5$$$ is: aabb string of node $$$6$$$ is: aabb string of node $$$7$$$ is: aabb string of node $$$8$$$ is: aabb string of node $$$9$$$ is: aa The set of unique strings is $$$\{\text{a}, \text{aa}, \text{aab}, \text{aabb}\}$$$, so the number of distinct strings is $$$4$$$.
|
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd. The problem is:You are given a connected tree rooted at node $$$1$$$.You should assign a character a or b to every node in the tree so that the total number of a's is equal to $$$x$$$ and the total number of b's is equal to $$$n - x$$$.Let's define a string for each node $$$v$$$ of the tree as follows: if $$$v$$$ is root then the string is just one character assigned to $$$v$$$: otherwise, let's take a string defined for the $$$v$$$'s parent $$$p_v$$$ and add to the end of it a character assigned to $$$v$$$. You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.
|
In the first line, print the minimum possible total number of distinct strings. In the second line, print $$$n$$$ characters, where all characters are either a or b and the $$$i$$$-th character is the character assigned to the $$$i$$$-th node. Make sure that the total number of a's is equal to $$$x$$$ and the total number of b's is equal to $$$n - x$$$. If there is more than one answer you can print any of them.
|
The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$; $$$0 \leq x \leq n$$$) — the number of vertices in the tree the number of a's. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_{n}$$$ ($$$1 \leq p_i \leq n$$$; $$$p_i \neq i$$$), where $$$p_i$$$ is the parent of node $$$i$$$. It is guaranteed that the input describes a connected tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 3,100 |
train_107.jsonl
|
5726db2b032796c9c35d4404b6a194cb
|
256 megabytes
|
["9 3\n1 2 2 4 4 4 3 1"]
|
PASSED
|
n, a = map(int, raw_input().split());p = [-1] + [int(x) - 1 for x in raw_input().split()];g = [[] for i in range(n)]
for i in range(1, n): g[p[i]].append(i)
d = [-1 for i in range(n)];d_all = [[] for i in range(n)];d_lv = [[] for i in range(n)];d_nlv = [[] for i in range(n)];q = [0];d[0] = 0
while len(q) > 0:
v = q.pop()
d_all[d[v]].append(v)
if len(g[v]) == 0:
d_lv[d[v]].append(v)
else:
d_nlv[d[v]].append(v)
for u in g[v]:
if d[u] == -1:
d[u] = d[v] + 1
q.append(u)
mx = max(d) + 1
mx_lv_pos = -1
for i in range(mx):
if mx_lv_pos == -1 or len(d_lv[i]) > len(d_lv[mx_lv_pos]):
mx_lv_pos = i
wg = [len(d_all[i]) if i != mx_lv_pos else 0 for i in range(mx)]
un = sorted(list(set(wg)))[1:]
pos = {}
for i in range(len(un)):
pos[un[i]] = i
vals = [[] for i in range(len(un))]
for i in range(len(wg)):
if wg[i] != 0:
vals[pos[wg[i]]].append(i)
lst = [[-1, -1] for i in range(n + 1)]
dp = [[False for j in range(n + 1)] for i in range(2)]
dp[0][0] = True
l = len(un)
for ii in range(l):
i = ii & 1
ni = i ^ 1
dp[ni] = [False for j in range(n + 1)]
lst_tk = [-1 for j in range(un[ii])]
for j in range(n + 1):
rm = j % un[ii]
if dp[i][j]:
lst_tk[rm] = j
dp[ni][j] = True
elif lst_tk[rm] >= 0 and (j - lst_tk[rm]) // un[ii] <= len(vals[ii]):
dp[ni][j] = True
lst[j] = [lst_tk[rm], ii]
dp = dp[l & 1]
ans = mx
res = -1
if dp[a]:
res = a
elif a - len(d_all[mx_lv_pos]) >= 0 and dp[a - len(d_all[mx_lv_pos])]:
res = a - len(d_all[mx_lv_pos])
else:
for i in range(a + 1):
if dp[i] and ((len(d_nlv[mx_lv_pos]) <= a - i <= len(d_all[mx_lv_pos])) or (0 <= a - i <= len(d_lv[mx_lv_pos]))):
res = i
break
ans += 1
cur = res
fin = set()
while cur > 0:
p = lst[cur][0]
x = lst[cur][1]
while cur > p:
fin.add(vals[x].pop())
cur -= un[x]
s = [1 for i in range(n)]
a -= res
for i in range(mx + 1):
if i in fin:
for v in d_all[i]:
s[v] = 0
if i == mx_lv_pos:
if a == len(d_all[i]):
for v in d_all[i]:
s[v] = 0
a -= len(d_nlv[i])
elif a != 0 and len(d_nlv[i]) <= a <= len(d_all[i]):
a -= len(d_nlv[i])
for v in d_nlv[i]:
s[v] = 0
for _ in range(a):
s[d_lv[i].pop()] = 0
print(ans)
print("".join(["ab"[x] for x in s]))
|
1612535700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["Yes\nYes\nNo\nYes\nNo"]
|
2ff40423619cefd8c2fb35a18549c411
|
NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},4,2]\to [1,\color{red}{4},4,2]$$$.In the second testcase of the sample, we can: do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},8,2,2]\to [1,\color{red}{4},8,2,2]$$$. do the second operation with $$$i=4$$$: $$$[1,4,8,\color{red}{2,2}]\to [1,4,8,\color{red}{4}]$$$. do the first operation with $$$i=3$$$: $$$[1,4,\color{red}{8},4]\to [1,4,\color{red}{4,4},4]$$$. do the second operation with $$$i=2$$$: $$$[1,\color{red}{4,4},4,4]\to [1,\color{red}{8},4,4]$$$. do the second operation with $$$i=3$$$: $$$[1,8,\color{red}{4,4}]\to [1,8,\color{red}{8}]$$$. do the second operation with $$$i=2$$$: $$$[1,\color{red}{8,8}]\to [1,\color{red}{16}]$$$.
|
Fishingprince is playing with an array $$$[a_1,a_2,\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it: Select $$$1\le i\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$. Select $$$1\le i\le n-m+1$$$ such that $$$a_i=a_{i+1}=\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.
|
For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).
|
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 $$$m$$$ ($$$1\le n\le 5\cdot 10^4$$$, $$$2\le m\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\le k\le 5\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\ldots,b_k$$$ ($$$1\le b_i\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,400 |
train_105.jsonl
|
21502cf957cbeeb386dcda2a58c40020
|
512 megabytes
|
["5\n\n5 2\n\n1 2 2 4 2\n\n4\n\n1 4 4 2\n\n6 2\n\n1 2 2 8 2 2\n\n2\n\n1 16\n\n8 3\n\n3 3 3 3 3 3 3 3\n\n4\n\n6 6 6 6\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n16\n\n9 3 2 2 2 3 4 12 4 12 4 12 4 12 4 4\n\n8 3\n\n3 9 6 3 12 12 36 12\n\n7\n\n12 2 4 3 4 12 56"]
|
PASSED
|
import sys
input = sys.stdin.readline
rounds=int(input())
for ii in range(rounds):
out='Yes'
length1,magic=map(int,input().split())
arr1=list(map(int,input().split()))
length2=int(input())
arr2=list(map(int,input().split()))
a1=[]
a2=[]
for a in arr1:
ori=a
while a%magic==0:
a=a//magic
if len(a1)>0 and a1[-1][0]==a:
a1[-1][1]+=(ori//a)
else:
a1.append([a,ori//a])
for aa in arr2:
ori=aa
while aa%magic==0:
aa=aa//magic
if len(a2)>0 and a2[-1][0]==aa:
a2[-1][1]+=(ori//aa)
else:
a2.append([aa,ori//aa])
if a1!=a2:
out='No'
print(out)
|
1656167700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4 8", "6 9", "8 15", "500000 500000"]
|
3ea971165088fae130d866180c6c868b
|
NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
|
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.
|
Output two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.
|
The only line contains an integer n (12 ≤ n ≤ 106).
|
standard output
|
standard input
|
Python 2
|
Python
| 800 |
train_006.jsonl
|
f45d1a614ffc6cbc966f08be94557b5e
|
256 megabytes
|
["12", "15", "23", "1000000"]
|
PASSED
|
n = int(raw_input().strip())
if n%2==0:
print '4 ' +str(n-4)
else:
print '9 ' +str(n-9)
|
1411918500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.