prob_desc_time_limit
stringclasses
21 values
prob_desc_sample_outputs
stringlengths
5
329
src_uid
stringlengths
32
32
prob_desc_notes
stringlengths
31
2.84k
prob_desc_description
stringlengths
121
3.8k
prob_desc_output_spec
stringlengths
17
1.16k
prob_desc_input_spec
stringlengths
38
2.42k
prob_desc_output_to
stringclasses
3 values
prob_desc_input_from
stringclasses
3 values
lang
stringclasses
5 values
lang_cluster
stringclasses
1 value
difficulty
int64
-1
3.5k
file_name
stringclasses
111 values
code_uid
stringlengths
32
32
prob_desc_memory_limit
stringclasses
11 values
prob_desc_sample_inputs
stringlengths
5
802
exec_outcome
stringclasses
1 value
source_code
stringlengths
29
58.4k
prob_desc_created_at
stringlengths
10
10
tags
listlengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
listlengths
8
8
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
016bf7989ba58fdc3894a4cf3e0ac302
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to ">", in the opposite case $$$a_{ij}$$$ is equal to "<". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "<", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is ">", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "<", ">" and "=".
standard output
standard input
Python 3
Python
2,000
train_029.jsonl
1105e4e520630e0c038466958c22f635
256 megabytes
["3 4\n>>>>\n>>>>\n>>>>", "3 3\n>>>\n<<<\n>>>", "3 2\n==\n=<\n=="]
PASSED
n, m = map(int, input().split()) dishes = [0 for _ in range(n + m)] father = [-1 for _ in range(n + m)] e_out = dict() v_in = [0 for _ in range(n + m)] def get_father(n): if father[n] == -1: return n else: father[n] = get_father(father[n]) return father[n] compare_matrix = [] for i in range(n): compare_matrix.append(input()) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": fi = get_father(i) fj = get_father(j + n) if fi != fj: father[fj] = fi children = dict() for i in range(n + m): fi = get_father(i) if fi != i: if fi not in children: children[fi] = [i] else: children[fi].append(i) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": continue fi = get_father(i) fj = get_father(j + n) if fi == fj: print("NO") exit(0) if compare_matrix[i][j] == ">": v_in[fi] += 1 if fj in e_out: e_out[fj].append(fi) else: e_out[fj] = [fi] if compare_matrix[i][j] == "<": v_in[fj] += 1 if fi in e_out: e_out[fi].append(fj) else: e_out[fi] = [fj] # print(v_in) # print(e_out) score = 1 visited = [False for _ in range(n + m)] v_total = 0 q = [v for v in range(n + m) if v_in[v] == 0] while q: t = [] for i in q: dishes[i] = score v_total += 1 if i in children: for j in children[i]: dishes[j] = score v_total += 1 if i in e_out: for j in e_out[i]: v_in[j] -= 1 if v_in[j] == 0: t.append(j) q = t score += 1 if v_total < n + m: print("NO") exit(0) print("YES") for i in dishes[:n]: print(i, end=" ") print() for i in dishes[n:n + m]: print(i, end=" ")
1550917200
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
c3df88e22a17492d4eb0f3239a27d404
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,300
train_108.jsonl
146f825f0fdf5c72770365ff8caeea1c
256 megabytes
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
PASSED
t = int(input()) for _ in range(t): n = int(input()) A = list(map(int, input().split())) B = [] R = [] S = input() for a, s in zip(A, S): if s == "B": B.append(a) else: R.append(a) B.sort() R.sort() flag = True for i in range(len(B)): if B[i] < i+1: flag = False for i in range(len(R)): if R[i] > len(B)+i+1: flag = False if flag: print("YES") else: print("NO")
1635863700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["6", "15", "7"]
2090c7382ef9bc8dfd9ca1fc1743d3a7
NoteIn the second sample the only optimal answer is to use two circles: a circle with $$$5$$$ chairs accomodating guests $$$1$$$ and $$$2$$$, and another one with $$$10$$$ chairs accomodationg guests $$$3$$$ and $$$4$$$.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7.
You invited $$$n$$$ guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the $$$i$$$-th guest wants to have a least $$$l_i$$$ free chairs to the left of his chair, and at least $$$r_i$$$ free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the $$$l_i$$$ chairs to his left and $$$r_i$$$ chairs to his right may overlap.What is smallest total number of chairs you have to use?
Output a single integer — the smallest number of chairs you have to use.
First line contains one integer $$$n$$$  — number of guests, ($$$1 \leqslant n \leqslant 10^5$$$). Next $$$n$$$ lines contain $$$n$$$ pairs of space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \leqslant l_i, r_i \leqslant 10^9$$$).
standard output
standard input
Python 3
Python
1,900
train_017.jsonl
b0fedd4835cfb0069279a40c181793ec
512 megabytes
["3\n1 1\n1 1\n1 1", "4\n1 2\n2 1\n3 5\n5 3", "1\n5 6"]
PASSED
n = int(input()) l = [] r = [] for i in range(n): numbers_in_line = [int(num) for num in input().split()] l_new, r_new = numbers_in_line l.append(l_new) r.append(r_new) l.sort() r.sort() maxes = [max(lv, rv) for lv, rv in zip(l, r)] print(n + sum(maxes))
1538636700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["6\n2\n15\n30"]
5a544816938d05da4f85fe7589d3289a
NoteConsider the example: boundaries for first query are $$$(0 + 1) \bmod 3 + 1 = 2$$$ and $$$(0 + 3) \bmod 3 + 1 = 1$$$. LCM for segment $$$[1, 2]$$$ is equal to $$$6$$$; boundaries for second query are $$$(6 + 3) \bmod 3 + 1 = 1$$$ and $$$(6 + 3) \bmod 3 + 1 = 1$$$. LCM for segment $$$[1, 1]$$$ is equal to $$$2$$$; boundaries for third query are $$$(2 + 2) \bmod 3 + 1 = 2$$$ and $$$(2 + 3) \bmod 3 + 1 = 3$$$. LCM for segment $$$[2, 3]$$$ is equal to $$$15$$$; boundaries for fourth query are $$$(15 + 2) \bmod 3 + 1 = 3$$$ and $$$(15 + 3) \bmod 3 + 1 = 1$$$. LCM for segment $$$[1, 3]$$$ is equal to $$$30$$$.
Yura owns a quite ordinary and boring array $$$a$$$ of length $$$n$$$. You think there is nothing more boring than that, but Vladik doesn't agree!In order to make Yura's array even more boring, Vladik makes $$$q$$$ boring queries. Each query consists of two integers $$$x$$$ and $$$y$$$. Before answering a query, the bounds $$$l$$$ and $$$r$$$ for this query are calculated: $$$l = (last + x) \bmod n + 1$$$, $$$r = (last + y) \bmod n + 1$$$, where $$$last$$$ is the answer on the previous query (zero initially), and $$$\bmod$$$ is the remainder operation. Whenever $$$l &gt; r$$$, they are swapped.After Vladik computes $$$l$$$ and $$$r$$$ for a query, he is to compute the least common multiple (LCM) on the segment $$$[l; r]$$$ of the initial array $$$a$$$ modulo $$$10^9 + 7$$$. LCM of a multiset of integers is the smallest positive integer that is divisible by all the elements of the multiset. The obtained LCM is the answer for this query.Help Vladik and compute the answer for each query!
Print $$$q$$$ integers — the answers for the queries.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the elements of the array. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. The next $$$q$$$ lines contain two integers $$$x$$$ and $$$y$$$ each ($$$1 \le x, y \le n$$$) — the description of the corresponding query.
standard output
standard input
PyPy 2
Python
2,700
train_033.jsonl
2c9b01f4d0b76f096e10b0fcc22b1f6b
512 megabytes
["3\n2 3 5\n4\n1 3\n3 3\n2 3\n2 3"]
PASSED
import sys range = xrange input = raw_input # MOD MOD = 10**9 + 7 def fast_modder(MOD): """ Returns function modmul(a,b) that quickly calculates a * b % MOD, assuming 0 <= a,b < MOD """ import sys, platform impl = platform.python_implementation() maxs = sys.maxsize if 'PyPy' in impl and MOD <= maxs and MOD ** 2 > maxs: import __pypy__ intsub = __pypy__.intop.int_sub intmul = __pypy__.intop.int_mul intmulmod = __pypy__.intop.int_mulmod if MOD < 2**30: MODINV = 1.0 / MOD def modmul(a, b): x = intsub(intmul(a,b), intmul(MOD, int(MODINV * a * b))) return x - MOD if x >= MOD else (x if x >= 0 else x + MOD) else: def modmul(a, b): return intmulmod(a, b, MOD) else: def modmul(a, b): return a * b % MOD return modmul modmul = fast_modder(MOD) # GCD def gcd(a,b): while b: a, b = b, a % b return a # Prime sieve big = 2 * 10**5 + 1 marker = [1] * big primeid = [-1] * big pid = 0 for i in range(2, big): if marker[i] == 1: primeid[i] = pid pid += 1 for j in range(i, big, i): marker[j] = i # input and precalc inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii+= 1 A = inp[ii : ii + n]; ii += n maxsqrt = 1 for i in range(big): if i * i < big and marker[i] == i: maxsqrt = i base = [1] * (primeid[maxsqrt] + 1) # B is to keep track of small prime factors # C is for large factors B = [] C = [] for a in A: b = list(base) c = 1 while a > 1: p = marker[a] count = 1 while a % p == 0: a //= p count *= p if p <= maxsqrt: b[primeid[p]] = count else: c = p B.append(b) C.append(c) def merge(A,B): return [max(A[i], B[i]) for i in range(len(A))] ### Segtree 1 class brute_seg: def __init__(self, A): n = len(A) data = [base] * (2 * n) data[n:n + n] = A for i in reversed(range(1, n)): data[i] = merge(data[2 * i], data[2 * i + 1]) def __call__(l,r): l += n r += n B = base while l < r: if l & 1: B = merge(B, data[l]) l += 1 if r & 1: r -= 1 B = merge(B, data[r]) l >>= 1 r >>= 1 ans = 1 for b in B: ans = modmul(ans, b) return ans self.__call__ = __call__ smallseg = brute_seg(B) ### Segtree 2 from bisect import bisect_left as binsearch class mod_mergesort_seg: def __init__(self, A, B): n = len(A) data = [[]] * (2 * n) data[n:2 * n] = [[a] for a in A] for i in reversed(range(1, n)): data[i] = sorted(data[2 * i] + data[2 * i + 1]) cumsummer = [[1]] * (2 * n) for i in range(1, 2 * n): C = [1] cumsummer[i] = C for d in data[i]: C.append(modmul(C[-1], B[d])) def query(l, r, x): """ Count number of i in [l,r) such that A[i] < x """ l += n r += n ans = 1 while l < r: if l & 1: ans = modmul(ans, cumsummer[l][binsearch(data[l], x)]) l += 1 if r & 1: r -= 1 ans = modmul(ans, cumsummer[r][binsearch(data[r], x)]) l >>= 1 r >>= 1 return ans self.query = query class unique_seg: def __init__(self, A): n = len(A) I = [] seen = {} for i in range(n): a = A[i] I.append(seen[a] if a in seen else i - n) seen[a] = i seg = mod_mergesort_seg(I, A) self.__call__ = lambda l, r: seg.query(l, r, l) largeseg = unique_seg(C) ### Queries q = inp[ii]; ii += 1 L = inp[ii + 0: ii + 2 * q: 2] R = inp[ii + 1: ii + 2 * q: 2] ii += 2 * q ans = [] last = 0 for qind in range(q): l = (last + L[qind]) % n r = (last + R[qind]) % n if l > r: l,r = r,l r += 1 #val = 1 #for a in A[l:r]: # val = val * a // gcd(val, a) #last = val last = modmul(smallseg(l,r), largeseg(l,r)) ans.append(last) print '\n'.join(str(x) for x in ans)
1601827500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["D\nLR\nLRULR\nDDDDDD"]
b894e16e8c00f8d97fde4a104466b3ef
NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like: In the second test case, Alice shows Bob the bottom row, the whole grid may look like: In the third test case, Alice shows Bob the bottom row, the whole grid may look like: In the fourth test case, Alice shows Bob the top row, the whole grid may look like:
Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \times 2$$$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!
For each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid. Additional constraint on the input: each input corresponds to at least one valid tiling.
standard output
standard input
Python 3
Python
800
train_089.jsonl
ead399f8737f3a5e4c18bb937feaf30f
256 megabytes
["4\n1\nU\n2\nLR\n5\nLRDLR\n6\nUUUUUU"]
PASSED
n1 = int(input()) for a in range(n1): n2 = int(input()) string1 = input().upper().strip() str = "" for i in string1: if i == "U": str += "D" elif i == "D": str += "U" else: str += i print(str)
1630852500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["25", "2", "Impossible"]
14b65af01caf1f3971a2f671589b86a8
null
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
standard output
standard input
Python 2
Python
1,800
train_014.jsonl
18e5cdd84f36fc2a2ccf6d53818ed86e
256 megabytes
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
PASSED
from collections import defaultdict #import sys #sys.setrecursionlimit(3*10**5) n = int(raw_input()) A = [0]+map(int, raw_input().split()) AdjOf = [ [] for x in xrange(n+5)] for i in xrange(n-1): u,v = map(int, raw_input().split()) AdjOf[u].append(v) AdjOf[v].append(u) ChildrenOf = [ [] for x in xrange(n+5)]#defaultdict(list) Seen = [0] * (n+5) que = [1]*n dq,cq = 0,0 while dq<=cq: u = que[dq] dq+=1 Seen[u]=1 for v in AdjOf[u]: if Seen[v]<1: ChildrenOf[u].append(v) cq+=1 que[cq]=v NINF = -10**16 TakeSum = [NINF] * (n+5) BestSum = [NINF]* (n+5) ans = NINF for x in que[::-1]: if len(ChildrenOf[x])<1: TakeSum[x] = A[x] BestSum[x] = A[x] continue TakeSum[x]=A[x] #for c in ChildrenOf[x]: # TakeSum[x] += TakeSum[c] BestSum[x] = NINF fi,se = NINF, NINF for c in ChildrenOf[x]: TakeSum[x] += TakeSum[c] BestSum[x] = max(BestSum[x], BestSum[c]) if BestSum[c]>fi: se,fi = fi, BestSum[c] elif BestSum[c]>se: se = BestSum[c] BestSum[x] = max(BestSum[x], TakeSum[x]) if fi>NINF and se>NINF: ans = max(ans, fi+se) """ def takeSum(x): global TakeSum if len(ChildrenOf[x])<1: TakeSum[x] = A[x] return A[x] if TakeSum[x]>NINF: return TakeSum[x] TakeSum[x]=A[x] for c in ChildrenOf[x]: TakeSum[x] += takeSum(c) return TakeSum[x] def bestSum(x): global BestSum if len(ChildrenOf[x])<1: BestSum[x] = A[x] return A[x] if BestSum[x]>NINF: return BestSum[x] BestSum[x] = takeSum(x) for c in ChildrenOf[x]: if A[x]>0: BestSum[x] = max(BestSum[x], bestSum(c)) else: BestSum[x] = max(BestSum[x], bestSum(c)) return BestSum[x] for u in que[::-1]: takeSum(u) bestSum(u) #print TakeSum #print BestSum #print ChildrenOf def getAns(bestList): if len(bestList)<2: return NINF fi,se = NINF, NINF for x in bestList: if x>fi: se=fi fi=x elif x>se: se=x return fi+se ans = NINF for x in que:#[::-1]: fi,se = NINF, NINF bestList = [BestSum[c] for c in ChildrenOf[x] if BestSum[c]>NINF] if len(bestList)<2: continue fi,se = NINF, NINF for x in bestList: if x>fi: se=fi fi=x elif x>se: se=x ans = max(ans, se+fi) #if ans>NINF: break ans = NINF Seen = set([1]) que = [1] dq,cq = 0,0 while dq<=cq: u = que[dq] dq+=1 Seen.add(u) best=[] for v in ChildrenOf[u]: if v not in Seen: que.append(v) cq+=1 if BestSum[v]>NINF: best.append(BestSum[v]) ans = max(ans, getAns(best)) """ print ans if ans>NINF else "Impossible"
1481726100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["2", "3", "5"]
60776cefd6c1a2f3c16b3378ebc31a9a
NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.
Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house. The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.
standard output
standard input
Python 3
Python
1,500
train_001.jsonl
7dfb199bc37b4d5b53b4e6ca9a2f664f
256 megabytes
["3\nAaA", "7\nbcAAcbc", "6\naaBCCe"]
PASSED
n = int(input()) s = input() D = dict() A = set() for i in range(n): if s[i] not in A: A.add(s[i]) l = 100001 for i in A: D[i] = 0 g = 0 c = '0' for i in range(n): D[s[i]] += 1 q = 0 if c == '0': for k in A: if D[k] == 0: break else: q = 1 if q == 1 or s[i] == c: for k in range(g,i+1): D[s[k]] -= 1 if D[s[k]] == 0: D[s[k]] += 1 l = min(l,i-k+1) g = max(k,0) c = s[k] break print(l)
1469205300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n0\n0\n1\n2\n1\n1\n0"]
a4b8e1ffe14c91381ae69e3b23ee4937
Note The tree before the task pow 1. The tree after the task pow 1.
Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.There are two types of tasks: pow v describes a task to switch lights in the subtree of vertex v. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v.Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.
For each task get v print the number of rooms in the subtree of v, in which the light is turned on.
The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≤ pi &lt; i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≤ ti ≤ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≤ q ≤ 200 000) — the number of tasks. The next q lines are get v or pow v (1 ≤ v ≤ n) — the tasks described above.
standard output
standard input
PyPy 2
Python
2,000
train_013.jsonl
72fda9afd2e47f8a6323e698b2beb69d
256 megabytes
["4\n1 1 1\n1 0 0 1\n9\nget 1\nget 2\nget 3\nget 4\npow 1\nget 1\nget 2\nget 3\nget 4"]
PASSED
from sys import stdin, stdout from itertools import repeat def main(): n = int(stdin.readline()) p = map(int, stdin.readline().split(), repeat(10, n - 1)) ch = [[] for _ in xrange(n)] for i, x in enumerate(p, 1): ch[x-1].append(i) st = [] pu = st.append po = st.pop col = [None] * n L = [0] * n R = [0] * n c = 0 pu(0) while st: x = po() if col[x] is None: L[x] = c c += 1 pu(x) col[x] = 1 for y in ch[x]: pu(y) else: col[x] = 0 R[x] = c N = 1 << 18 b = [0] * (N + N) lz = [0] * (N + N) t = stdin.readline().split() for i, x in enumerate(t): if x == '1': b[L[i]+N] += 1 for i in xrange(N - 1, 0, -1): b[i] = b[i+i] + b[i+i+1] ans = [] def inv(b, lz, v, lh): b[v] = lh - b[v] lz[v] ^= 1 def push(b, lz, o, ln): for i in xrange(18, 0, -1): j = o >> i if lz[j]: inv(b, lz, j+j, ln) inv(b, lz, j+j+1, ln) lz[j] = 0 ln /= 2 q = int(stdin.readline()) for _ in xrange(q): ln, x = stdin.readline().split() x = int(x, 10) - 1 l, r = L[x] + N, R[x] + N - 1 push(b, lz, l, N / 2) push(b, lz, r, N / 2) if ln[0] == 'g': l, r = L[x] + N, R[x] + N tmp = 0 while l < r: if l & 1: tmp += b[l] l += 1 if r & 1: r -= 1 tmp += b[r] l /= 2 r /= 2 ans.append(tmp) else: l, r = L[x] + N, R[x] + N n = 1 while l < r: if l & 1: inv(b, lz, l, n) l += 1 if r & 1: r -= 1 inv(b, lz, r, n) l /= 2 r /= 2 n += n l, r = L[x] + N, R[x] + N - 1 n = 1 while l > 1: l /= 2 r /= 2 n += n b[l] = b[l+l] + b[l+l+1] if lz[l]: b[l] = n - b[l] b[r] = b[r+r] + b[r+r+1] if lz[r]: b[r] = n - b[r] stdout.write('\n'.join(map(str, ans))) main()
1508773500
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
3 seconds
["0 1 1", "0 1 4 6", "0 1", "0 1 2 2 3"]
261b22421590cf6bb1d602e1dc7e0243
NoteIn the first sample, it takes no time to get to city 1; to get to city 2 it is possible to use a flight between 1 and 2, which will take 1 unit of time; to city 3 you can get via a road from city 1, which will take 1 unit of time. In the second sample, it also takes no time to get to city 1. To get to city 2 Stanley should use a flight between 1 and 2, which will take 1 unit of time. To get to city 3 Stanley can ride between cities 1 and 2, which will take 3 units of time, and then use a flight between 2 and 3. To get to city 4 Stanley should use a flight between 1 and 2, then take a ride from 2 to 4, which will take 5 units of time.
Stanley lives in a country that consists of $$$n$$$ cities (he lives in city $$$1$$$). There are bidirectional roads between some of the cities, and you know how long it takes to ride through each of them. Additionally, there is a flight between each pair of cities, the flight between cities $$$u$$$ and $$$v$$$ takes $$$(u - v)^2$$$ time.Stanley is quite afraid of flying because of watching "Sully: Miracle on the Hudson" recently, so he can take at most $$$k$$$ flights. Stanley wants to know the minimum time of a journey to each of the $$$n$$$ cities from the city $$$1$$$.
Print $$$n$$$ integers, $$$i$$$-th of which is equal to the minimum time of traveling to city $$$i$$$.
In the first line of input there are three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \leq n \leq 10^{5}$$$, $$$1 \leq m \leq 10^{5}$$$, $$$1 \leq k \leq 20$$$) — the number of cities, the number of roads, and the maximal number of flights Stanley can take. The following $$$m$$$ lines describe the roads. Each contains three integers $$$u$$$, $$$v$$$, $$$w$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$, $$$1 \leq w \leq 10^{9}$$$) — the cities the road connects and the time it takes to ride through. Note that some pairs of cities may be connected by more than one road.
standard output
standard input
PyPy 3-64
Python
2,400
train_082.jsonl
1c473ae3f909b3bb1daa8513937b896f
256 megabytes
["3 1 2\n1 3 1", "4 3 1\n1 2 3\n2 4 5\n3 4 7", "2 1 1\n2 1 893746473", "5 5 2\n2 1 33\n1 5 93\n5 3 48\n2 3 21\n4 2 1"]
PASSED
from sys import stdin input=lambda :stdin.readline()[:-1] n,m,k=map(int,input().split()) edge=[[] for i in range(n)] for _ in range(m): a,b,c=map(int,input().split()) a,b=a-1,b-1 edge[a].append((b,c)) edge[b].append((a,c)) from heapq import heappop,heappush mask=(1<<17)-1 def dijkstra(): hq=[] for i in range(n): if dist[i]!=inf: heappush(hq,(dist[i]<<17)+i) seen=[0]*n while hq: x=heappop(hq) w,v=x>>17,x&mask if dist[v]<w: continue seen[v]=True for to,cost in edge[v]: if seen[to]==False and dist[v]+cost<dist[to]: dist[to]=dist[v]+cost heappush(hq,(dist[to]<<17)+to) from collections import deque class ConvexHullTrick(): # 追加する直線の傾きが単調 # 計算する x 座標が単調 # O(N+Q) def __init__(self): self.deq=deque() def check(self,f1,f2,f3): return (f2[0]-f1[0])*(f3[1]-f2[1])>=(f2[1]-f1[1])*(f3[0]-f2[0]) def f(self,f1,x): return f1[0]*x+f1[1] # add f_i(x)=a*x+b def add_line(self,a,b): f1=(a,b) while len(self.deq)>=2 and self.check(self.deq[-2],self.deq[-1],f1): self.deq.pop() self.deq.append(f1) # min f_i(x) def query(self,x): while len(self.deq)>=2 and self.f(self.deq[0],x)>=self.f(self.deq[1],x): self.deq.popleft() return self.f(self.deq[0],x) inf=1<<60 dist=[inf]*n dist[0]=0 dijkstra() for _ in range(k): CHT=ConvexHullTrick() for i in range(n): CHT.add_line(-2*i,dist[i]+i*i) for i in range(n): dist[i]=CHT.query(i)+i*i dijkstra() print(*dist)
1661006100
[ "geometry", "graphs" ]
[ 0, 1, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n1.1\n1.2\n1.3\n1\n1.1\n1.1.1\n1.1.2\n1.2\n1.2.1\n2\n2.1\n2.2"]
c1bf6c8a9a20f377cf2a5dbea2267c88
NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below: Original list with a single item $$$1$$$. Insert item $$$2$$$ by using the insertion operation of the second type after item $$$1$$$. Insert item $$$1.1$$$ by using the insertion operation of the first type after item $$$1$$$. Insert item $$$1.2$$$ by using the insertion operation of the second type after item $$$1.1$$$. Insert item $$$1.1.1$$$ by using the insertion operation of the first type after item $$$1.1$$$. Insert item $$$1.1.2$$$ by using the insertion operation of the second type after item $$$1.1.1$$$. Insert item $$$1.2.1$$$ by using the insertion operation of the first type after item $$$1.2$$$. Insert item $$$2.1$$$ by using the insertion operation of the first type after item $$$2$$$. Insert item $$$2.2$$$ by using the insertion operation of the second type after item $$$2.1$$$.
William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \,\cdots\, \,.\,a_k$$$ and can be one of two types: Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, a_k \,.\, 1$$$ (starting a list of a deeper level), or Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, (a_k + 1)$$$ (continuing the current level). Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.
For each test case output $$$n$$$ lines which represent a valid nested list, which could become the data provided to you by William. If there are multiple answers, print any.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$), which is the number of lines in the list. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$1 \le a_i \le n$$$), which is what remains of William's nested list. It is guaranteed that in each test case at least one fitting list exists. It is guaranteed that the sum of values $$$n$$$ across all test cases does not exceed $$$10^3$$$.
standard output
standard input
PyPy 3-64
Python
1,600
train_082.jsonl
37fe5b8f35db843504398fccc877948f
256 megabytes
["2\n4\n1\n1\n2\n3\n9\n1\n1\n1\n2\n2\n1\n2\n1\n2"]
PASSED
for h in range(int(input())): n=int(input()) s=[] for i in range(n): j = int(input()) if j==1: s.append(j) else: while j-s[-1]!=1: s.pop() s[-1]=j print('.'.join(map(str, s)))
1622385300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["3 2 2 0 0 0 0 \n0 3 0 2 0 0 \n1 \n0 0 1 1 1 \n1 0 4 0 0 0 \n2 2 2 2 0 0 0 0"]
c63640fd70e0268f03cb4eec18540f3a
NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is: place block $$$1$$$ at position $$$(0, 0)$$$; place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$; place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$; place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$; place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$; place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$; place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$. The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$: It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$.
You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way. Initially, you place block $$$1$$$ at $$$(0, 0)$$$. For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently: Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.
For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le n$$$). 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_093.jsonl
2484f6d989a143c0b9d42c956809e3d8
256 megabytes
["6\n\n7\n\n1 2 3 1 2 3 1\n\n6\n\n4 2 2 2 4 4\n\n1\n\n1\n\n5\n\n5 4 5 3 5\n\n6\n\n3 3 3 1 3 3\n\n8\n\n1 2 3 4 4 3 2 1"]
PASSED
def solveonecolor(array): m = len(array) if m==0: return 0 elif m==1: return 1 else: maxi = 1 for i in range(m-1): if (array[i+1]-array[i])%2==1: maxi+=1 return maxi def solve(n, array): allans = [] subarrays = [[] for _ in range(n)] for i in range(n): color = array[i]-1 subarrays[color].append(i) for color in range(n): allans.append(solveonecolor(subarrays[color])) print(" ".join(str(i) for i in allans)) tests = int(input()) for _ in range(tests): n = int(input()) array = list(map(int, input().split())) solve(n, array)
1658154900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["2", "2"]
9a64ee19cf2d20978870c03311bf6cbf
NoteGraph from first sample:Graph from second sample:
You are given a set of size $$$m$$$ with integer elements between $$$0$$$ and $$$2^{n}-1$$$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $$$x$$$ and $$$y$$$ with an edge if and only if $$$x \&amp; y = 0$$$. Here $$$\&amp;$$$ is the bitwise AND operation. Count the number of connected components in that graph.
Print the number of connected components.
In the first line of input there are two integers $$$n$$$ and $$$m$$$ ($$$0 \le n \le 22$$$, $$$1 \le m \le 2^{n}$$$). In the second line there are $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$0 \le a_{i} &lt; 2^{n}$$$) — the elements of the set. All $$$a_{i}$$$ are distinct.
standard output
standard input
PyPy 2
Python
2,500
train_033.jsonl
08e46f6cf2e865e6bb4993acb797fb70
256 megabytes
["2 3\n1 2 3", "5 5\n5 19 10 20 12"]
PASSED
def main(): inp = readnumbers() ii = 0 n = inp[ii] ii += 1 m = inp[ii] ii += 1 pow2 = 2**n index = [-1]*pow2 #coupl = [[] for _ in range(pow2 + m)] for _ in range(m): u = inp[ii] ii += 1 index[pow2 - 1 - u] = pow2 + _ # coupl[pow2 - 1 - u].append(pow2 + _) found = [False]*(pow2 + m) ii = 2 ans = 0 A = [] for _ in range(m): root = pow2 + _ ii += 1 if found[root]:continue A = [root] found[root] = True for node in A: #for nei in coupl[node]: # if not found[nei]: # found[nei] = 1 # A.append(nei) if node < pow2: if index[node]>=0: nei = index[node] if not found[nei]: found[nei] = True A.append(nei) j = 1 while j<pow2: if node&j == 0 and not found[node^j]: found[node^j] = True A.append(node^j) j *= 2 else: nei = inp[2 + node - pow2] if not found[nei]: found[nei] = True A.append(nei) ans += 1 print(ans) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main()
1527608100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1 0 1\n3 2 1\n12 7 1\n42 27 1\n341102826 248150916 1"]
63fc2fb08d248f8ccdb3f5364c96dac1
NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case: Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$; Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$; the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.
Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x &gt; y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows: if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw; if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.
For each test case, print three integers: the number of ways to distribute the cards so that Alex wins; the number of ways to distribute the cards so that Boris wins; the number of ways to distribute the cards so that the game ends in a draw. Since the answers can be large, print them modulo $$$998244353$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).
standard output
standard input
PyPy 3-64
Python
1,500
train_109.jsonl
680b048f60b68c37836f2a9dabb3f14d
512 megabytes
["5\n\n2\n\n4\n\n6\n\n8\n\n60"]
PASSED
# Libraries import sys from math import * from queue import PriorityQueue # Definitions mod = 998244353 e = pow(10,-6) input = sys.stdin.readline pq = PriorityQueue() # sys.setrecursionlimit(10**6) #Input forms def imap(): return map(int,input().split()) def ilist(): return list(map(int,input().split())) # Common functions def freq(l): d = {} for i in l: d[i] = d.get(i,0)+1 return d def lgcd(l): a = 0 for i in l: a = gcd(a,i) return a def SieveOfEratosthenes(num): prime = [True for i in range(num+1)] p = 2 while (p * p <= num): if (prime[p] == True): for i in range(p * p, num+1, p): prime[i] = False p += 1 return p[2:] def bs_on_ans(l,r): for i in range(100): mid = (l+r)/2 # if f(mid)>f(mid+e): # l = mid+e # else: # if f(mid-e)>f(mid): # break # else: # r = mid-e return mid # Starting off; f = {0:1} for i in range(1,61): f[i] = (f[i-1]*i) t = int(input()) for _ in range(t): n = int(input()) a = 1 sum = -(f[n-1]//(f[n//2-1]*f[n//2]))%mod total = (f[n]//(f[n//2]*f[n//2])) while n>=2: sum = ((sum)%mod + (2*f[n-1]//(f[n//2-1]*f[n//2]))%mod)%mod if n-4>=0 and a==0: sum = ((sum)%mod + (f[n-1]//(f[n//2-2]*f[n//2+1]))%mod)%mod n-=4 a = 0 print(sum,(total-sum-1)%mod,1) ###################################################### By Shri ##############################################################
1664462100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1\n000\n1010\n00"]
b37bbf1fe9ac5144cfa230633ccbdd79
NoteThe explanation of the sample case (equal characters in equal positions are bold):The first test case: $$$\mathbf{1}$$$ is similar to $$$s[1..1] = \mathbf{1}$$$. The second test case: $$$\mathbf{000}$$$ is similar to $$$s[1..3] = \mathbf{000}$$$; $$$\mathbf{000}$$$ is similar to $$$s[2..4] = \mathbf{000}$$$; $$$\mathbf{000}$$$ is similar to $$$s[3..5] = \mathbf{000}$$$. The third test case: $$$\mathbf{1}0\mathbf{10}$$$ is similar to $$$s[1..4] = \mathbf{1}1\mathbf{10}$$$; $$$\mathbf{1}01\mathbf{0}$$$ is similar to $$$s[2..5] = \mathbf{1}10\mathbf{0}$$$; $$$\mathbf{10}1\mathbf{0}$$$ is similar to $$$s[3..6] = \mathbf{10}0\mathbf{0}$$$; $$$1\mathbf{0}1\mathbf{0}$$$ is similar to $$$s[4..7] = 0\mathbf{0}0\mathbf{0}$$$. The fourth test case: $$$0\mathbf{0}$$$ is similar to $$$s[1..2] = 1\mathbf{0}$$$; $$$\mathbf{0}0$$$ is similar to $$$s[2..3] = \mathbf{0}1$$$.
A binary string is a string where each character is either 0 or 1. Two binary strings $$$a$$$ and $$$b$$$ of equal length are similar, if they have the same character in some position (there exists an integer $$$i$$$ such that $$$a_i = b_i$$$). For example: 10010 and 01111 are similar (they have the same character in position $$$4$$$); 10010 and 11111 are similar; 111 and 111 are similar; 0110 and 1001 are not similar. You are given an integer $$$n$$$ and a binary string $$$s$$$ consisting of $$$2n-1$$$ characters. Let's denote $$$s[l..r]$$$ as the contiguous substring of $$$s$$$ starting with $$$l$$$-th character and ending with $$$r$$$-th character (in other words, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$$$).You have to construct a binary string $$$w$$$ of length $$$n$$$ which is similar to all of the following strings: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.
For each test case, print the corresponding binary string $$$w$$$ of length $$$n$$$. If there are multiple such strings — print any of them. It can be shown that at least one string $$$w$$$ meeting the constraints always exists.
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 a single integer $$$n$$$ ($$$1 \le n \le 50$$$). The second line of each test case contains the binary string $$$s$$$ of length $$$2n - 1$$$. Each character $$$s_i$$$ is either 0 or 1.
standard output
standard input
Python 3
Python
800
train_024.jsonl
24dc8ec1f269c95ad32d47fb3b2eca1b
256 megabytes
["4\n1\n1\n3\n00000\n4\n1110000\n2\n101"]
PASSED
t = int(input()) for _ in range(t): n, s = int(input()), input() print(*[s[i] for i in range(0,len(s),2)], sep='')
1598366100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1", "2", "6720"]
14da0cdf2939c796704ec548f49efb87
null
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7).
In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7).
The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.
standard output
standard input
Python 3
Python
1,900
train_063.jsonl
30ae3de8b79560873a74800fab9e2496
256 megabytes
["3 1\n1", "4 2\n1 4", "11 2\n4 8"]
PASSED
import math def solve( n, list1): list1.sort() inf = int(1e9 + 7) t1 = [list1[0] - 1, n - list1[-1]] t2 = [] for i in range(1, len(list1)): t2.append((list1[i] - list1[i - 1] - 1)) num1 = 1 for i in range(n - len(list1)): num1 = num1 * (i + 1) num1 = num1 % inf num2 = 1 num2 = math.factorial(t1[0]) % inf num2 = num2 % inf num2 = num2 * math.factorial(t1[1]) % inf num2 = num2 % inf for i in range(len(t2)): num2 = num2 * math.factorial(t2[i]) num2 = num2 % inf num2 = pow(num2, inf - 2, inf) num3 = 1 for i in range(len(t2)): if t2[i] - 1 < 0: continue num3 = (num3 * pow(2, t2[i] - 1, inf)) % inf num1 = num1 * num2 num1 = num1 % inf num1 = num1 * num3 num1 = num1 % inf return int(num1) n,m = map(int,input().split()) list1 = list(map(int,input().split())) print(solve(n,list1))
1365348600
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2\n-1\n10\n-1\n1"]
9afcf090806cc9c3b87120b1b61f8f17
NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$. For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.
For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.
Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \le x \lt y \le 10^9$$$, $$$1 \le a,b \le 10^9$$$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.
standard output
standard input
Python 3
Python
800
train_000.jsonl
964ed75e9176ed9bbcd4caa596b89c05
256 megabytes
["5\n0 10 2 3\n0 10 3 3\n900000000 1000000000 1 9999999\n1 2 1 1\n1 3 1 1"]
PASSED
arr =[] test_cases =int(input('')) for x in range(test_cases): a=[] a = list(map(int,input().split())) arr.append(a) for t in range(test_cases): x=arr[t][0] y=arr[t][1] a=arr[t][2] b=arr[t][3] if abs(y-x)%(a+b)==0: if abs(y-x)%(a+b)==0: print (int((y-x)/(a+b))) else : print("-1")
1581771900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0\n\n2\n4 4\n3\n2 6 2"]
cced3c3d3f1a63e81e36c94fc2ce9379
NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\oplus$$$ of numbers in it is $$$8$$$.
Let's call an array $$$a_1, a_2, \dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.
For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\le s\le 3$$$) — the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \dots, b_s$$$ ($$$0\le b_i \le 10^{18}$$$) — the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). The 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 size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,400
train_002.jsonl
c313a8d7bd8e233bce222ed35bba9043
256 megabytes
["3\n4\n1 2 3 6\n1\n8\n2\n1 1"]
PASSED
for i in range(int(input())): x=int(input()) m=list(map(int,input().split())) s=0 ss=0 for j in range(x): s=s^m[j] ss+=m[j] if s==0: print("1") print(ss) else: print("2") print(str(s)+" "+str(ss+s))
1577628300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2", "3"]
eea7860e6bbbe5f399b9123ebd663e3e
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
Print single integer — the maximum number of Pokemons Bash can take.
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
standard output
standard input
Python 3
Python
1,400
train_012.jsonl
5ff303b7b41d94173510a011c561a205
512 megabytes
["3\n2 3 4", "5\n2 3 4 6 7"]
PASSED
from collections import defaultdict from math import sqrt def solve(): n = int(input()) numbers = list(map(int, input().split(" "))) if n == 1: print(1) return amount = {} for number in numbers: if number not in amount: amount[number] = 1 else: amount[number] += 1 freq = defaultdict(int) for key, value in sorted(amount.items()): if key == 1: freq[key] += value continue freq[key] += value for j in range(2, int(sqrt(key)) + 1): if key % j == 0: freq[j] += value if key // j != j: freq[key//j] += value highest = sorted(freq.items(), key=lambda x:x[1])[-1] if highest[0] == 1: print(1) else: print(highest[1]) solve()
1484235300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["2"]
0ef324e3e314ea17c01aafb822e90c63
null
You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.
Print the answer to the problem.
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105). The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).
standard output
standard input
Python 3
Python
2,100
train_000.jsonl
d4176629e96d618983cf756526b2f1d1
256 megabytes
["3\n3 4 5"]
PASSED
input() s = sorted(set(map(int, input().split()))) c = m = 0 d = [] for b in s: d += [c] * (b - c) c = b for b in s[-1::-1]: if b < m + 2: break m = max(m, c % b, *(a % b for a in d[2 * b - 1::b])) print(m)
1415205000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES", "NO", "NO"]
42b6ada19f6f6276bb2f99049e2b9b76
NoteSample 1. The tenth row of table G starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence a.Sample 2. This time the width of table G equals 8. Sequence a doesn't occur there.
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b.You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 ≤ i ≤ n and 1 ≤ j ≤ m - k + 1 should exist that G(i, j + l - 1) = al for all 1 ≤ l ≤ k.Determine if the sequence a occurs in table G.
Print a single word "YES", if the given sequence occurs in table G, otherwise print "NO".
The first line contains three space-separated integers n, m and k (1 ≤ n, m ≤ 1012; 1 ≤ k ≤ 10000). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ 1012).
standard output
standard input
Python 3
Python
2,900
train_052.jsonl
10b3f5031d3f7f4234c491d9f507103d
256 megabytes
["100 100 5\n5 2 1 2 1", "100 8 5\n5 2 1 2 1", "100 100 7\n1 2 3 4 5 6 7"]
PASSED
''' Created on Aug 28, 2016 @author: Md. Rezwanul Haque ''' def gcd(a,b): if b == 0: return a return gcd(b, a%b) def extend_euclid(a,b): if b == 0: return 1,0 else: y,x = extend_euclid(b, a%b) y = y - (a//b)*x return x,y n,m,k = map(int,input().split()) a = list(map(int,input().split())) lcm = 1 for i in a: lcm = (lcm*i)//gcd(lcm, i) if lcm>n: print('NO') exit() j = 0 m1 = 1 s = True for i in range(k): x,y = extend_euclid(m1, a[i]) res = m1*x + a[i]*y if (-i-j)%res != 0: s = False break res = (-i-j)//res x,y = x*res , y*res j += m1*x t = m1*a[i] if j>t: j -= (j//t)*t if j<0: j += ((-j+t-1)//t)*t if j == 0: j = t m1 = (m1*a[i])//gcd(m1, a[i]) if j+k-1 >m or s == False: print('NO') exit() b = [gcd(lcm, j+i) for i in range(k)] for i in range(k): if (a[i] != b[i]): print('NO') exit() print('YES')
1376668800
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["4\n3\n1\n28\n510049495001"]
eb3d8259ca598c3c455ddfdbe433cb78
NoteIn the first test case, Alice can set $$$1,2,3$$$ or $$$4$$$ days as the number of days in a week.There are $$$6$$$ possible paintings shown in the picture, but there are only $$$4$$$ different shapes. So, the answer is $$$4$$$. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides. In the last test case, be careful with the overflow issue, described in the output format.
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \leq k \leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.
For each test case, print a single integer  — the answer to the problem. Please note, that the answer for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains two integers $$$n$$$, $$$r$$$ ($$$1 \le n \le 10^9, 1 \le r \le 10^9$$$).
standard output
standard input
PyPy 3
Python
1,200
train_000.jsonl
854e94faac0d6749d0d2f0928eeac83e
256 megabytes
["5\n3 4\n3 2\n3 1\n13 7\n1010000 9999999"]
PASSED
from sys import stdin input=stdin.readline for _ in range(int(input())): n,m=map(int,input().split()) if n<=m: print((n*(n-1))//2+1) else: print((m*(m+1))//2)
1593610500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["12.000000\n11.000000\n10.000000\n9.000000\n8.000000", "-1"]
65fea461d3caa5a932d1e2c13e99a59e
null
A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously: there were b milliliters poured in total. That is, the bottle need to be emptied; after the process is over, the volumes of the drink in the mugs should be equal.
Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.
The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.
standard output
standard input
Python 3
Python
1,100
train_029.jsonl
5d018348eca4cf8eb9a3129ef2388b1c
256 megabytes
["5 50\n1 2 3 4 5", "2 2\n1 100"]
PASSED
x=[int(i) for i in input().split()] n=x[0] y=[int(i) for i in input().split()] if x[1]<max(y)*n-sum(y): print(-1) raise SystemExit for i in range(n): s=x[1]/n-y[i]++sum(y)/n print('%.6f'% s)
1333897500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["4", "6"]
0cb9a20ca0a056b86885c5bcd031c13f
NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last.
Print the total number of moves Alice and Bob will make.
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n). Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
standard output
standard input
Python 3
Python
1,700
train_032.jsonl
0c77d424bd54fe58ef5e016a538a5d48
256 megabytes
["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"]
PASSED
from collections import deque from sys import stdin #Algoritmo BFS def BFS(s): if s==0: distance=distance_Alice else: distance=distance_Bob distance[s]=0 q=deque() q.append(s) while len(q)>0: v=q.popleft() for u in adjacents_list[v]: if distance[u] == -1: distance[u]=distance[v]+1 q.append(u) #Recibiendo los valores de n y x n,x=map(int, stdin.readline().split()) #Creando los arrays necesarios para la ejecucion de DFS #visitados distance_Alice=[-1 for i in range(n)] distance_Bob=[-1 for i in range(n)] #Armando el arbol adjacents_list=[[] for i in range(n)] for i in range(n-1): v1,v2=map(int, stdin.readline().split()) adjacents_list[v1-1].append(v2-1) adjacents_list[v2-1].append(v1-1) BFS(0) BFS(x-1) #Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice max=0 for i in range(n): if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]: max=distance_Alice[i] print(max*2)
1496675100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2\n4"]
24f4bd10ae714f957920afd47ac0c558
NoteIn first case, for $$$m=2$$$, polynomials that satisfy the constraint are $$$x$$$ and $$$2$$$.In second case, for $$$m=4$$$, polynomials that satisfy the constraint are $$$x^2$$$, $$$x + 2$$$, $$$2x$$$ and $$$4$$$.
The Bubble Cup hypothesis stood unsolved for $$$130$$$ years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:Given a number $$$m$$$, how many polynomials $$$P$$$ with coefficients in set $$${\{0,1,2,3,4,5,6,7\}}$$$ have: $$$P(2)=m$$$?Help Jerry Mao solve the long standing problem!
For each test case $$$i$$$, print the answer on separate lines: number of polynomials $$$P$$$ as described in statement such that $$$P(2)=m_i$$$, modulo $$$10^9 + 7$$$.
The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 5\cdot 10^5)$$$ - number of test cases. On next line there are $$$t$$$ numbers, $$$m_i$$$ $$$(1 \leq m_i \leq 10^{18})$$$ - meaning that in case $$$i$$$ you should solve for number $$$m_i$$$.
standard output
standard input
Python 3
Python
2,400
train_079.jsonl
446fffa36187d1bef88d0cc5f4867624
256 megabytes
["2\n2 4"]
PASSED
t = int(input()) a = list(map(int, input().split())) out = [] for n in a: ans = (n//2 + 2) ans = ans*ans ans //= 4 out.append(ans%1000000007) print(' '.join(str(x) for x in out))
1601903100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["7\n4\n76"]
64a375c7c49591c676dbdb039c93d218
NoteIn the first example, $$$f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$$$.
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: $$$f(0) = a$$$; $$$f(1) = b$$$; $$$f(n) = f(n-1) \oplus f(n-2)$$$ when $$$n &gt; 1$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. You are given three integers $$$a$$$, $$$b$$$, and $$$n$$$, calculate $$$f(n)$$$.You have to answer for $$$T$$$ independent test cases.
For each test case, output $$$f(n)$$$.
The input contains one or more independent test cases. The first line of input contains a single integer $$$T$$$ ($$$1 \le T \le 10^3$$$), the number of test cases. Each of the $$$T$$$ following lines contains three space-separated integers $$$a$$$, $$$b$$$, and $$$n$$$ ($$$0 \le a, b, n \le 10^9$$$) respectively.
standard output
standard input
Python 2
Python
900
train_004.jsonl
4215d67ceb22d705844ff2e13e69e8b7
256 megabytes
["3\n3 4 2\n4 5 0\n325 265 1231232"]
PASSED
t=int(input()) for i in xrange(t): a,b,n=map(int,raw_input().split()) dp=[a,b,a^b] if n%3==0: print dp[0] elif n%3==1: print dp[1] elif n%3==2: print dp[2]
1566743700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "2"]
c01da186ee69936eb274dce6e1222e43
NoteNote that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.It is possible that for some numbers $$$b_i$$$ and $$$b_j$$$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
For a given sequence of distinct non-negative integers $$$(b_1, b_2, \dots, b_k)$$$ we determine if it is good in the following way: Consider a graph on $$$k$$$ nodes, with numbers from $$$b_1$$$ to $$$b_k$$$ written on them. For every $$$i$$$ from $$$1$$$ to $$$k$$$: find such $$$j$$$ ($$$1 \le j \le k$$$, $$$j\neq i$$$), for which $$$(b_i \oplus b_j)$$$ is the smallest among all such $$$j$$$, where $$$\oplus$$$ denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an undirected edge between vertices with numbers $$$b_i$$$ and $$$b_j$$$ in this graph. We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers $$$b_i$$$ and $$$b_j$$$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.You can find an example below (the picture corresponding to the first test case). Sequence $$$(0, 1, 5, 2, 6)$$$ is not good as we cannot reach $$$1$$$ from $$$5$$$.However, sequence $$$(0, 1, 5, 2)$$$ is good. You are given a sequence $$$(a_1, a_2, \dots, a_n)$$$ of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?It can be shown that for any sequence, we can remove some number of elements, leaving at least $$$2$$$, so that the remaining sequence is good.
You should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200,000$$$) — length of the sequence. The second line contains $$$n$$$ distinct non-negative integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the sequence.
standard output
standard input
Python 3
Python
2,100
train_012.jsonl
653fe61bde06bed578df895538ea6ef7
256 megabytes
["5\n0 1 5 2 6", "7\n6 9 8 7 3 5 2"]
PASSED
n = int(input()) l = list(map(int,input().split())) def fun(a): if len(a) <= 3: return len(a) maxE = max(a) if maxE == 0: return len(a) msb = 1 while 2 * msb <= maxE: msb *= 2 l1 = [] l2 = [] for x in a: if x >= msb: l1.append(x-msb) else: l2.append(x) max1 = fun(l1) max2 = fun(l2) if max1 == 0: return max2 if max2 == 0: return max1 return max(1+max1,1+max2) print(n - fun(l))
1605450900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["NO\nNO\nNO\nNO\nYES\nYES", "NO\nYES\nYES"]
7f934f96cbe3990945e5ebcf5c208043
NoteIn test case 1, for i = 5 there exists j = 3 such that si = sj and j &lt; i, which means that answer for i = 5 is "YES".
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j &lt; i, otherwise, output "NO" (without quotes).
Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower).
First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.
standard output
standard input
Python 3
Python
800
train_008.jsonl
d10d8b9602b66c9a79532a16e4875ae7
256 megabytes
["6\ntom\nlucius\nginny\nharry\nginny\nharry", "3\na\na\na"]
PASSED
numer = int(input()) newWords = list() for i in range(numer): inn = input() if not inn in newWords: newWords.append(inn) print("NO") else: print("YES")
1506263700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["3", "3", "1", "2"]
0c4dad4f65ad986d87c968520111e995
null
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ​​may be unknown. Such values are represented by number -1.For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ​​-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ​​-1 may correspond to an arbitrary positive integer and the values ai &gt; 0 must be equal to the corresponding elements of sought consecutive record of the progressions.Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
The first line of the input contains integer n (1 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 ≤ ai ≤ 109 or ai =  - 1).
standard output
standard input
Python 3
Python
2,400
train_029.jsonl
c7fbc88ae02cfb6a7420bc1200d2707d
256 megabytes
["9\n8 6 4 2 1 4 7 10 2", "9\n-1 6 -1 2 -1 4 7 -1 2", "5\n-1 -1 -1 -1 -1", "7\n-1 -1 4 5 1 2 3"]
PASSED
n = int(input()) a = list(map(int, input().split())) i = 0 ans = 0 while i < n: ans += 1 i1 = i while i1 < n and a[i1] == -1: i1 += 1 if i1 == n: break i2 = i1 + 1 while i2 < n and a[i2] == -1: i2 += 1 if i2 == n: break dist = i2 - i1 step = (a[i2] - a[i1]) // dist if (a[i2] - a[i1]) % dist != 0 or (step > 0 and a[i1] - (i1 - i) * step <= 0): i = i2 continue i3 = i2 + 1 while i3 < n: nxt = a[i2] + step * (i3 - i2) if nxt <= 0 or (a[i3] != -1 and a[i3] != nxt): break i3 += 1 i = i3 print(ans)
1397376000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["YES\nYES\nNO\n1\n2\n2\n2", "YES\nYES\nYES\nYES\nNO\nYES\n3\n3\n1\n1\n2"]
c4f97a986dccc433835addca8efec972
null
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes). After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3. See the samples for better understanding.
The first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations. The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary. Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi. Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered. All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
standard output
standard input
PyPy 2
Python
2,000
train_007.jsonl
0e2c6f8b50f65df269ef9882a1c3f3c7
256 megabytes
["3 3 4\nhate love like\n1 love like\n2 love hate\n1 hate like\nlove like\nlove hate\nlike hate\nhate like", "8 6 5\nhi welcome hello ihateyou goaway dog cat rat\n1 hi welcome\n1 ihateyou goaway\n2 hello ihateyou\n2 hi goaway\n2 hi hello\n1 hi hello\ndog cat\ndog hi\nhi hello\nihateyou goaway\nwelcome ihateyou"]
PASSED
n, m, q = [int(x) for x in raw_input().split()] a = raw_input().split() c = {x: ([x], []) for x in a} for _ in range(m): t, x, y = raw_input().split() sign = 1 if t == '2' else 0 if c[x][0] is c[y][1-sign]: print "NO" continue print "YES" if c[x][0] is c[y][sign]: continue c1, c2 = c[x], c[y] if len(c1[0]) + len(c1[1]) < len(c2[0]) + len(c2[1]): c1, c2 = c2, c1 s1, a1 = c1 if sign == 0: s2, a2 = c2 else: a2, s2 = c2 s1 += s2 a1 += a2 cs = s1, a1 for x in s2: c[x] = cs ca = a1, s1 for x in a2: c[x] = ca for _ in range(q): x, y = raw_input().split() if c[x][0] is c[y][0]: print 1 elif c[x][0] is c[y][1]: print 2 else: print 3
1486487100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2\n6\n0\n4"]
58ee86d4913787582ccdb54073656dc0
NoteIn the first test case, we can choose the $$$k=2$$$ characters $$$\texttt{"_ol"}$$$ and rearrange them as $$$\texttt{"_lo"}$$$ (so the resulting string is $$$\texttt{"llo"}$$$). It is not possible to sort the string choosing strictly less than $$$2$$$ characters.In the second test case, one possible way to sort $$$s$$$ is to consider the $$$k=6$$$ characters $$$\texttt{"_o__force_"}$$$ and rearrange them as $$$\texttt{"_c__efoor_"}$$$ (so the resulting string is $$$\texttt{"ccdeefoors"}$$$). One can show that it is not possible to sort the string choosing strictly less than $$$6$$$ characters.In the third test case, string $$$s$$$ is already sorted (so we can choose $$$k=0$$$ characters).In the fourth test case, we can choose all $$$k=4$$$ characters $$$\texttt{"dcba"}$$$ and reverse the whole string (so the resulting string is $$$\texttt{"abcd"}$$$).
A string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the English alphabet, is given.You must choose some number $$$k$$$ between $$$0$$$ and $$$n$$$. Then, you select $$$k$$$ characters of $$$s$$$ and permute them however you want. In this process, the positions of the other $$$n-k$$$ characters remain unchanged. You have to perform this operation exactly once.For example, if $$$s=\texttt{"andrea"}$$$, you can choose the $$$k=4$$$ characters $$$\texttt{"a_d_ea"}$$$ and permute them into $$$\texttt{"d_e_aa"}$$$ so that after the operation the string becomes $$$\texttt{"dneraa"}$$$.Determine the minimum $$$k$$$ so that it is possible to sort $$$s$$$ alphabetically (that is, after the operation its characters appear in alphabetical order).
For each test case, output the minimum $$$k$$$ that allows you to obtain a string sorted alphabetically, through the operation described above.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 40$$$) — the length of the string. The second line of each test case contains the string $$$s$$$. It is guaranteed that $$$s$$$ contains only lowercase letters of the English alphabet.
standard output
standard input
Python 3
Python
800
train_098.jsonl
26d5ca23c959da3d29b42d75ace12192
256 megabytes
["4\n3\nlol\n10\ncodeforces\n5\naaaaa\n4\ndcba"]
PASSED
for i in range(int(input())): n=int(input()) s=[i for i in input()] t=sorted(s) print(sum([int(s[i]!=t[i]) for i in range(n)]))
1627223700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20", "dummy 0 0\npack 10 10\nx 40 10\ny 10 10"]
258f54f32c6df5390edd804294aad235
NoteIn the first sample the widgets are arranged as follows:
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k ≥ 2, for which ci is packed directly to ci + 1 for any 1 ≤ i &lt; k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 × 0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.
For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator)
The first line contains an integer n — the number of instructions (1 ≤ n ≤ 100). Next n lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. "HBox [name]" — create a new widget [name] of the type HBox. "VBox [name]" — create a new widget [name] of the type VBox. "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget.
standard output
standard input
Python 2
Python
2,300
train_028.jsonl
79ee7c1dbfa4ef3522c6c6602d985350
256 megabytes
["12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)", "15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dummy)\ny.set_border(5)\ny.set_spacing(55)\ndummy.set_border(10)\ndummy.set_spacing(20)\nx.set_border(10)\nx.set_spacing(10)\nx.pack(pack)\nx.pack(dummy)\nx.pack(pack)\nx.set_border(0)"]
PASSED
import re class Widget(object): def __init__(self, type, w = 0, h = 0): self.type = type if type == 'Widget': self.w = w self.h = h def calc_wh(self): if not hasattr(self, 'w'): if self.children: self.w = self.border * 2 self.h = self.border * 2 for c in self.children: cw, ch = c.calc_wh() if self.type == "VBox": self.h += ch self.w = max(self.w, cw + self.border * 2) else: self.w += cw self.h = max(self.h, ch + self.border * 2) if self.type == "HBox": self.w += (len(self.children) - 1) * self.spacing else: self.h += (len(self.children) - 1) * self.spacing else: self.w = 0 self.h = 0 return self.w, self.h widgets = {} n = input() rp = re.compile(r'(\w+)\.(\w+)\((.+)\)') for _ in xrange(n): str = raw_input() if str.find(' ') != -1: type, rhs = str.split(' ') if type == 'Widget': name, other = rhs.split('(') w, h = map(int, other[:-1].split(',')) widgets[name] = Widget(type, w, h) else: widgets[rhs] = Widget(type) widgets[rhs].children = [] widgets[rhs].spacing = 0 widgets[rhs].border = 0 else: name, op, arg = rp.match(str).groups() if op == "set_border": widgets[name].border = int(arg) elif op == "set_spacing": widgets[name].spacing = int(arg) else: widgets[name].children.append(widgets[arg]) for k, v in sorted(widgets.items(), key = lambda x: x[0]): w, h = v.calc_wh() print k, w, h
1308236400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1\n0"]
4b33db3950303b8993812cb265fa9819
NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\{[2, 4], [4, 6], [6, 8]\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element.
Given a sequence $$$a_1, a_2, \ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.
For each test case, print a single integer — the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\dots,a_n$$$ ($$$1\leq a_i\leq10^9$$$) — elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3-64
Python
800
train_089.jsonl
d4e7042f26b8b6e13853aba2649cacfa
256 megabytes
["2\n\n5\n\n2 4 3 6 8\n\n6\n\n3 5 9 7 1 3"]
PASSED
def ss(n, arr): countOdd = 0 for i in range(n): if (arr[i] % 2): countOdd += 1 return min(countOdd, n - countOdd) t = int(input()) while t: ans = 0 n = int(input()) nums = list(map(int, input().split())) print(ss(n, nums)) t -= 1
1654007700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nYES\nYES"]
a8201326dda46542b23dc4e528d413eb
NoteIn the first test case, you can first cut the $$$2 \times 2$$$ sheet into two $$$2 \times 1$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$. We can choose any three of them and send them to our friends.In the second test case, a $$$3 \times 3$$$ sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a $$$5 \times 10$$$ sheet into two $$$5 \times 5$$$ sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the $$$1 \times 4$$$ sheet into two $$$1 \times 2$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$.
For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \times h$$$ that he has in only two cases: If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\frac{w}{2} \times h$$$; If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \times \frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.
For each test case, output on a separate line: "YES", if it is possible to cut a sheet of size $$$w \times h$$$ into at least $$$n$$$ pieces; "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 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$w$$$, $$$h$$$, $$$n$$$ ($$$1 \le w, h \le 10^4, 1 \le n \le 10^9$$$) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.
standard output
standard input
PyPy 3-64
Python
800
train_089.jsonl
b1a430a24b32d6cfd018378f76cc8ecf
256 megabytes
["5\n2 2 3\n3 3 2\n5 10 2\n11 13 1\n1 4 4"]
PASSED
for i in range(int(input())): l=list(map(int,input().split())) if (l[2]<=1): print("YES") else: ans=1 while l[1] % 2 == 0: ans *= 2 l[1] /= 2 while l[0]%2==0: ans*=2 l[0]/=2 print("NO"if ans <l[2] else "YES" )
1609770900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n1\n3\n-1\n0"]
c15bce9c4b9eddf5c8c3421b768da98c
NoteIn the third sample test case the array will change as follows: At the beginning $$$a = [1, 1, 0, 1, 0]$$$, and $$$a^{\rightarrow 2} = [1, 0, 1, 1, 0]$$$. Their element-by-element "AND" is equal to $$$$$$[1 \,\&amp;\, 1, 1 \,\&amp;\, 0, 0 \,\&amp;\, 1, 1 \,\&amp;\, 1, 0 \,\&amp;\, 0] = [1, 0, 0, 1, 0]$$$$$$ Now $$$a = [1, 0, 0, 1, 0]$$$, then $$$a^{\rightarrow 2} = [1, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&amp;\, 1, 0 \,\&amp;\, 0, 0 \,\&amp;\, 1, 1 \,\&amp;\, 0, 0 \,\&amp;\, 0] = [1, 0, 0, 0, 0]$$$$$$ And finally, when $$$a = [1, 0, 0, 0, 0]$$$ we get $$$a^{\rightarrow 2} = [0, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&amp;\, 0, 0 \,\&amp;\, 0, 0 \,\&amp;\, 1, 0 \,\&amp;\, 0, 0 \,\&amp;\, 0] = [0, 0, 0, 0, 0]$$$$$$ Thus, the answer is $$$3$$$ steps.In the fourth sample test case, the array will not change as it shifts by $$$2$$$ to the right, so each element will be calculated as $$$0 \,\&amp;\, 0$$$ or $$$1 \,\&amp;\, 1$$$ thus not changing its value. So the answer is -1, the array will never contain only zeros.
You are given an array $$$a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}]$$$ of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array $$$a$$$ is replaced by another array of length $$$n$$$ according to the following rules: First, a new array $$$a^{\rightarrow d}$$$ is defined as a cyclic shift of the array $$$a$$$ to the right by $$$d$$$ cells. The elements of this array can be defined as $$$a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}$$$, where $$$(i + n - d) \bmod n$$$ is the remainder of integer division of $$$i + n - d$$$ by $$$n$$$. It means that the whole array $$$a^{\rightarrow d}$$$ can be represented as a sequence $$$$$$a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \ldots, a_{n - 1}, a_0, a_1, \ldots, a_{n - d - 1}]$$$$$$ Then each element of the array $$$a_i$$$ is replaced by $$$a_i \,\&amp;\, a^{\rightarrow d}_i$$$, where $$$\&amp;$$$ is a logical "AND" operator. For example, if $$$a = [0, 0, 1, 1]$$$ and $$$d = 1$$$, then $$$a^{\rightarrow d} = [1, 0, 0, 1]$$$ and the value of $$$a$$$ after the first step will be $$$[0 \,\&amp;\, 1, 0 \,\&amp;\, 0, 1 \,\&amp;\, 0, 1 \,\&amp;\, 1]$$$, that is $$$[0, 0, 0, 1]$$$.The process ends when the array stops changing. For a given array $$$a$$$, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.
Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the number of steps after which the array will contain only zeros for the first time. If there are still elements equal to $$$1$$$ in the array after the end of the process, print -1.
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains two integers: $$$n$$$ ($$$1 \le n \le 10^6$$$) — array size and $$$d$$$ ($$$1 \le d \le n$$$) — cyclic shift offset. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$0 \le a_i \le 1$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_095.jsonl
cf9555ce57f7b6092eb06b56dd84a4dc
256 megabytes
["5\n2 1\n0 1\n3 2\n0 1 0\n5 2\n1 1 0 1 0\n4 2\n0 1 0 1\n1 1\n0"]
PASSED
for _ in range(int(input())): n,d=map(int,input().split()) a = list(map(int, input().split())) used = [False]*n fail = False res = 0 for i in range(n): if used[i]: continue cur = i pr = last = it = ans = 0 used[cur] = True if (a[cur] == 0): ans = max(ans, last) last = 0 else: last += 1 if (it == pr): pr+=1 cur = (cur+d)%n it += 1 while cur != i: used[cur] = True if (a[cur] == 0): ans = max(ans, last) last = 0 else: last += 1 if (it == pr): pr+=1 cur = (cur+d)%n it += 1 if it != pr: ans = max(ans, pr+last) else: fail = True break res = max(res, ans) if fail: print(-1) continue print(res)
1632839700
[ "number theory", "math", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 0 ]
1 second
["0\n4\n3"]
354e27c81d3d57a64062b5daa05705ad
NoteIn the first test case, the original array is $$$[3, 2, 1, 0]$$$. In the second test case, the original array is $$$[0, 3, 2, 1]$$$.In the third test case, the original array is $$$[2, 1, 0]$$$.
This is the easy version of the problem. The difference in the constraints between both versions is 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 performs the following steps: First, Gojou chooses $$$2$$$ integers $$$l$$$ and $$$r$$$ such that $$$l \leq r$$$. Then, Gojou makes 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{=} \boldsymbol{l}} \le r &lt; 2^{17}$$$). The second line contains $$$r - l + 1$$$ integers of $$$a_1,a_2,\ldots,a_{r-l+1}$$$ ($$$0 \le a_i &lt; 2^{17}$$$). It is guaranteed that $$$a$$$ can be generated using the steps performed by Gojou. 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
1,600
train_095.jsonl
d65168aa672f153cb07188b1f957ffd3
256 megabytes
["3\n\n0 3\n\n3 2 1 0\n\n0 3\n\n4 7 6 5\n\n0 2\n\n1 2 3"]
PASSED
import sys input=sys.stdin.readline for iii in range(int(input())): n,m=map(int,input().split()) q=list(map(int,input().split())) q1=[0 for i in range(18)] for i in q: x=bin(i) x=x[2:] x=x[::-1] for j in range(len(x)): if x[j]=='1': q1[j]+=1 q2=[0 for i in range(18)] for i in range(n,m+1,1): x = bin(i) x = x[2:] x = x[::-1] for j in range(len(x)): if x[j] == '1': q2[j] += 1 summ=0 for i in range(18): if q1[i]!=q2[i]: summ=summ+2**i print(summ)
1648391700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["5", "4"]
ad5ec7026cbefedca288df14c2bc58e5
NoteIn the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.
There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that: each ball belongs to exactly one of the sets, there are no empty sets, there is no set containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.
Print one integer number — the minimum possible number of sets.
The first line contains one integer number n (1 ≤ n ≤ 500). The second line contains n integer numbers a1, a2, ... , an (1 ≤ ai ≤ 109).
standard output
standard input
Python 3
Python
2,500
train_050.jsonl
32dcdc039a97045a0616090e02ebd59d
256 megabytes
["3\n4 7 8", "2\n2 7"]
PASSED
# Returns the number of coins that is necessary for paying the amount # with the two types of coins that have value of coin and coin + 1 def pay(coin, amount): if amount // coin < amount % coin: return -1; if amount < coin * (coin + 1): return amount // coin return (amount - 1) // (coin + 1) + 1; def pay_all(coin): sum = 0 for i in range(n): p = pay(coin, a[i]) if p == -1: return -1 sum += p return sum n = int(input()) a = list(map(int, input().split())) amin = min(a) coin = amin k = 1 p = -1 while p == -1: p = pay_all(coin) if p == -1 and amin % coin == 0: p = pay_all(coin - 1) k += 1 coin = amin // k print(p)
1490625300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3\n4\n2\n3"]
1ca582e932ac93ae2e1555deb16e3c3c
NoteThe split in the first test case is explained in the statement, it can be shown that it is optimal.In the second test case, it is possible to split into segments only by leaving a single segment. Then the thickness of this split is equal to the length of the entire sequence, that is, $$$4$$$.In the third test case, the optimal split will be $$$[10, 55], [35, 30], [65]$$$. The thickness of the split equals to $$$2$$$.In the fourth test case possible splits are: $$$[4] + [1, 1, 1, 1] + [4]$$$; $$$[4, 1, 1] + [1, 1, 4]$$$.
You are given a sequence $$$a=[a_1,a_2,\dots,a_n]$$$ consisting of $$$n$$$ positive integers.Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $$$a[l,r]$$$ a segment of the sequence $$$a$$$ with the left end in $$$l$$$ and the right end in $$$r$$$, i.e. $$$a[l,r]=[a_l, a_{l+1}, \dots, a_r]$$$.For example, if $$$a=[31,4,15,92,6,5]$$$, then $$$a[2,5]=[4,15,92,6]$$$, $$$a[5,5]=[6]$$$, $$$a[1,6]=[31,4,15,92,6,5]$$$ are segments.We split the given sequence $$$a$$$ into segments so that: each element is in exactly one segment; the sums of elements for all segments are equal. For example, if $$$a$$$ = [$$$55,45,30,30,40,100$$$], then such a sequence can be split into three segments: $$$a[1,2]=[55,45]$$$, $$$a[3,5]=[30, 30, 40]$$$, $$$a[6,6]=[100]$$$. Each element belongs to exactly segment, the sum of the elements of each segment is $$$100$$$.Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $$$3$$$.Find the minimum thickness among all possible splits of the given sequence of $$$a$$$ into segments in the required way.
For each test case, output one integer — the minimum possible thickness of a split of the sequence $$$a$$$ into segments. Note that there always exist a split, you can always consider whole sequence as one segment.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case is described by two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the length of the sequence $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_084.jsonl
29fb3401fd7df0891a6f6d7ddb693a60
256 megabytes
["4\n\n6\n\n55 45 30 30 40 100\n\n4\n\n10 23 7 13\n\n5\n\n10 55 35 30 65\n\n6\n\n4 1 1 1 1 4"]
PASSED
import sys input = sys.stdin.readline tests = int(input()) for _ in range(tests): n = int(input()) arr = list(map(int, input().split())) minsum, totsum = max(arr) - 1, sum(arr) possible = [] while True: brr = [] for elem in arr: brr.append(elem) k = 0 thick = 0 while k <= minsum or totsum % k != 0: k += brr.pop() thick += 1 pot = k k = 0 indicator = 0 x = 0 while len(brr) > 0: k += brr.pop() x += 1 if k == pot: k = 0 if x > thick: thick = x x = 0 elif k > pot: indicator = 1 minsum = pot break if indicator == 0 and k == 0: possible.append(thick) if thick == n: break minsum = pot print(min(possible))
1665498900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3\n2 3 3\n2 1 1", "9\n3 5 5\n4 3 3\n4 1 1\n4 2 2"]
ac25d2519df81490ea0e7997ab73aa24
null
You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: choose two leaves; add the length of the simple path between them to the answer; remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!
In the first line print one integer number — maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi — pair of the leaves that are chosen in the current operation (1 ≤ ai, bi ≤ n), ci (1 ≤ ci ≤ n, ci = ai or ci = bi) — choosen leaf that is removed from the tree in the current operation. See the examples for better understanding.
The first line contains one integer number n (2 ≤ n ≤ 2·105) — the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that given graph is a tree.
standard output
standard input
Python 3
Python
2,400
train_037.jsonl
a2c7d7b8774ebbf44de1664a325df7a1
256 megabytes
["3\n1 2\n1 3", "5\n1 2\n1 3\n2 4\n2 5"]
PASSED
import sys def main(): n = int(input()) edges = list(map(int, sys.stdin.read().split())) tree_edges = dict() for i in range(n): tree_edges[i + 1] = set() for i in range(0, len(edges) - 1, 2): tree_edges[edges[i]].add(edges[i + 1]) tree_edges[edges[i + 1]].add(edges[i]) init_distants = [-1] * (n + 1) queue = [1] init_distants[1] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if init_distants[next_vertex] == -1: init_distants[next_vertex] = init_distants[process] + 1 next_queue.append(next_vertex) queue = next_queue head = init_distants.index(max(init_distants)) distants_from_head = [-1] * (n + 1) queue = [head] distants_from_head[head] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if distants_from_head[next_vertex] == -1: distants_from_head[next_vertex] = distants_from_head[process] + 1 next_queue.append(next_vertex) queue = next_queue tail = distants_from_head.index(max(distants_from_head)) distants_from_tail = [-1] * (n + 1) queue = [tail] distants_from_tail[tail] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if distants_from_tail[next_vertex] == -1: distants_from_tail[next_vertex] = distants_from_tail[process] + 1 next_queue.append(next_vertex) queue = next_queue path_len_sum = 0 removal_history = list() process_queue = [] for vertex, adj in tree_edges.items(): if len(adj) == 1: process_queue.append(vertex) while process_queue: next_queue = [] for leaf in process_queue: if leaf == head or leaf == tail: continue if distants_from_tail[leaf] > distants_from_head[leaf]: path_len_sum += distants_from_tail[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) next_queue.extend(new_leaves) removal_history.append("{0} {1} {0}".format(leaf, tail)) else: path_len_sum += distants_from_head[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) next_queue.extend(new_leaves) removal_history.append("{0} {1} {0}".format(leaf, head)) process_queue = next_queue process_queue = [tail] while process_queue: leaf = process_queue[0] if leaf == head: continue path_len_sum += distants_from_head[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) process_queue = new_leaves removal_history.append("{0} {1} {0}".format(leaf, head)) print(str(path_len_sum)) sys.stdout.write("\n".join(removal_history)) sys.stdout.write("\n") main()
1514469900
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["Yes\nNo\nNo\nYes\nNo\nYes"]
0f960d19e576b7421a7c7a7166a884ea
NoteIn the first test case, let's consider the order $$$\{1, 2, 2\}$$$ of types of guests. Then: The first guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$1$$$ chocolate cookie. The second guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$0$$$ chocolate cookies. The last guest selects a chocolate cookie, but there are no chocolate cookies. So, the guest gets angry. So, this order can't be chosen by Anna.Let's consider the order $$$\{2, 2, 1\}$$$ of types of guests. Then: The first guest eats a vanilla cookie. After that, there is $$$1$$$ vanilla cookie and $$$2$$$ chocolate cookies. The second guest eats a vanilla cookie. After that, there are $$$0$$$ vanilla cookies and $$$2$$$ chocolate cookies. The last guest eats a chocolate cookie. After that, there are $$$0$$$ vanilla cookies and $$$1$$$ chocolate cookie. So, the answer to this test case is "Yes".In the fifth test case, it is illustrated, that the number of cookies ($$$a + b$$$) can be equal to zero, but the number of guests ($$$n + m$$$) can't be equal to zero.In the sixth test case, be careful about the overflow of $$$32$$$-bit integer type.
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $$$a$$$ vanilla cookies and $$$b$$$ chocolate cookies for the party.She invited $$$n$$$ guests of the first type and $$$m$$$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are $$$v$$$ vanilla cookies and $$$c$$$ chocolate cookies at the moment, when the guest comes, then if the guest of the first type: if $$$v&gt;c$$$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie. if the guest of the second type: if $$$v&gt;c$$$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that: If there is at least one cookie of the selected type, the guest eats one. Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.
For each test case, print the answer in one line. If there exists at least one valid order, print "Yes". Otherwise, print "No". You can print each letter in any case (upper or lower).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains four integers $$$a$$$, $$$b$$$, $$$n$$$, $$$m$$$ ($$$0 \le a,b,n,m \le 10^{18}, n+m \neq 0$$$).
standard output
standard input
PyPy 2
Python
1,300
train_000.jsonl
e48daaec34f873ef69951a7092df49f5
256 megabytes
["6\n2 2 1 2\n0 100 0 1\n12 13 25 1\n27 83 14 25\n0 0 1 0\n1000000000000000000 1000000000000000000 1000000000000000000 1000000000000000000"]
PASSED
FAST_IO = 1 if FAST_IO: import io, sys, atexit rr = iter(sys.stdin.read().splitlines()).next sys.stdout = _OUTPUT_BUFFER = io.BytesIO() @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) else: rr = raw_input rri = lambda: int(rr()) rrm = lambda: map(int, rr().split()) rrmm = lambda n: [rrm() for _ in xrange(n)] rrd = lambda: map(float, rr().split()) def solve(a,b,c,d): if (a+b)<(c+d): print("No") else: if min(a,b)<d: print("No") else: print("Yes") t = rri() for _ in range(t): a, b, c, d = rrm() solve(a,b,c,d) """ 4 3 1 28 510049495001 """
1593610500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Infinity", "-Infinity", "0/1", "1/2", "-9/5"]
37cf6edce77238db53d9658bc92b2cab
NoteLet's consider all samples: You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function
You are given two polynomials: P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm. Calculate limit .
If the limit equals  + ∞, print "Infinity" (without quotes). If the limit equals  - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction — the value of limit , in the format "p/q" (without the quotes), where p is the — numerator, q (q &gt; 0) is the denominator of the fraction.
The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers — the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≤ ai ≤ 100, a0 ≠ 0). The third line contains m + 1 space-separated integers — the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≤ bi ≤ 100, b0 ≠ 0).
standard output
standard input
Python 2
Python
1,400
train_000.jsonl
5e64b90cf2ad19927903fb5804805ac2
256 megabytes
["2 1\n1 1 1\n2 5", "1 0\n-1 3\n2", "0 1\n1\n1 0", "2 2\n2 1 6\n4 5 -7", "1 1\n9 0\n-5 2"]
PASSED
n, m = map(int, raw_input().split()) P = map(int, raw_input().split()) Q = map(int, raw_input().split()) if n > m: if P[0] > 0 and Q[0] > 0 or P[0] < 0 and Q[0] < 0: print "Infinity" else: print "-Infinity" elif n < m: print "0/1" else: a, b = abs(P[0]), abs(Q[0]) for i in xrange(100, 0, -1): if a%i == 0 and b%i == 0: a /= i b /= i if P[0] > 0 and Q[0] > 0 or P[0] < 0 and Q[0] < 0: print str(a) + "/" + str(b) else: print "-" + str(a) + "/" + str(b)
1339506000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n0\n0"]
0ba97bcfb5f539c848f2cd097b34ff33
NoteIn the first test case we can delete any character in string &lt;&gt;.In the second test case we don't need to delete any characters. The string &gt; &lt; &lt; is good, because we can perform the following sequence of operations: &gt; &lt; &lt; $$$\rightarrow$$$ &lt; &lt; $$$\rightarrow$$$ &lt;.
You have a string $$$s$$$ of length $$$n$$$ consisting of only characters &gt; and &lt;. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character &gt;, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character &lt;, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character &gt; in string &gt; &gt; &lt; &gt;, the string will become to &gt; &gt; &gt;. And if we choose character &lt; in string &gt; &lt;, the string will become to &lt;.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings &gt;, &gt; &gt; are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $$$n - 1$$$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.
For each test case print one line. For $$$i$$$-th test case print the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of test cases. Each test case is represented by two lines. The first line of $$$i$$$-th test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) – the length of string $$$s$$$. The second line of $$$i$$$-th test case contains string $$$s$$$, consisting of only characters &gt; and &lt;.
standard output
standard input
Python 3
Python
1,200
train_003.jsonl
1aeb8a70844e40040a2694416b79a313
256 megabytes
["3\n2\n&lt;&gt;\n3\n&gt;&lt;&lt;\n1\n&gt;"]
PASSED
for _ in range(int(input())): n = int(input()) s = input().strip() ans = 0 i = 0 while(i < n and s[i] == "<"): ans += 1 i += 1 ans1 = 0 i = n - 1 while(i > -1 and s[i] == ">"): ans1 += 1 i -= 1 print(min(ans, ans1))
1553267100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2.5 seconds
["8", "4"]
1fe6daf718b88cabb2e956e81add3719
NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016"
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Print the number of ways to correctly split the given sequence modulo 109 + 7.
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
standard output
standard input
PyPy 2
Python
2,000
train_008.jsonl
de7dd131809a05b77a30ecd4e217a269
512 megabytes
["6\n123434", "8\n20152016"]
PASSED
modulo = 10**9 + 7 def get_order(inp): n = len(inp) gt = [[-1] * i for i in range(n)] for j in range(i)[::-1]: if inp[n-1] > inp[j]: gt[n-1][j] = 0 for i in range(n-1)[::-1]: for j in range(i)[::-1]: if inp[i] > inp[j]: gt[i][j] = 0 elif inp[i] == inp[j]: pos = gt[i + 1][j + 1] if pos >= 0 and pos + 1 < i - j: gt[i][j] = pos + 1 return gt def solve(inp): inp = tuple(map(int, inp)) n = len(inp) gt = get_order(inp) posg = [[None]*(n+1) for _ in range(n)] for i in range(0, n)[::-1]: for l in range(1, n+1)[::-1]: end = i + l if inp[i] == 0 or end > n: posg[i][l] = 0 continue if end + l > n: posg[i][l] = 1 continue sameok = gt[end][i] >= 0 res = posg[i][l+1] if sameok: res += posg[i + l][l] else: res += posg[i + l][l + 1] posg[i][l] = res % modulo return posg[0][1] raw_input() print(solve(tuple(raw_input().strip())))
1451487900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["5 2 3 1 5"]
26aef004295df530352485ce53b47364
NoteDescription of the sample: the deck is $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$; the deck is $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$; the deck is $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$; the deck is $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$; the deck is $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$.
You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should: find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index; print the position of the card you found; take the card and place it on top of the deck.
Print $$$q$$$ integers — the answers for each query.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.
standard output
standard input
PyPy 3-64
Python
1,100
train_089.jsonl
6188494415985410424cd111460b2e7c
256 megabytes
["7 5\n2 1 1 4 3 3 1\n3 2 1 1 4"]
PASSED
import sys n,q=map(int,sys.stdin.readline().split()) a=[int(i) for i in sys.stdin.readline().split()] t=[int(i) for i in sys.stdin.readline().split()] # print(a.index(t[0])) for i in range(0,len(t)): x=a.index(t[i]) print(x+1,end=" ") a[:x+1]=[a[x]]+a[:x] # print(a)
1618238100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["4", "100"]
6cc6db6f426bb1bce59f23bfcb762b08
NoteThe first example is explained in the legend.
Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov".
Output a single integer, the wow factor of $$$s$$$.
The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$.
standard output
standard input
Python 3
Python
1,300
train_041.jsonl
bda2d24f8bcc551d5e24e57f1f043e93
256 megabytes
["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"]
PASSED
s = input() ws = [] i = 0 while i < len(s): cnt = 0 while i < len(s) and s[i] == 'v' : cnt += 1 i += 1 if cnt != 0: ws += ['w'] * (cnt - 1) if i >= len(s): break ws.append('o') i += 1 W = 0 WO = 0 WOW = 0 for c in ws: if c == 'w': W += 1 WOW += WO else: WO += W print(WOW)
1563636900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
4 seconds
["2.666666666666667"]
7bdb68ab0752f8df94b4d5c7df759dfb
null
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:Suppose we want to analyze the segment of $$$n$$$ consecutive days. We have measured the temperatures during these $$$n$$$ days; the temperature during $$$i$$$-th day equals $$$a_i$$$.We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $$$x$$$ to day $$$y$$$, we calculate it as $$$\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$$$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. For example, if analyzing the measures $$$[3, 4, 1, 2]$$$ and $$$k = 3$$$, we are interested in segments $$$[3, 4, 1]$$$, $$$[4, 1, 2]$$$ and $$$[3, 4, 1, 2]$$$ (we want to find the maximum value of average temperature over these segments).You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?
Print one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. Your answer will be considered correct if the following condition holds: $$$|res - res_0| &lt; 10^{-6}$$$, where $$$res$$$ is your answer, and $$$res_0$$$ is the answer given by the jury's solution.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 5000$$$) — the temperature measures during given $$$n$$$ days.
standard output
standard input
PyPy 3
Python
1,300
train_002.jsonl
617fb7a9a0116c3e42c32128ac05d3e6
256 megabytes
["4 3\n3 4 1 2"]
PASSED
n,k = map(int,input().split()) l = list(map(int,input().split())) i = 0 m = -10000 while i < len(l): j = i x = 1 som = 0 while j < len(l): if x < k: som += l[j] x = x + 1 j = j + 1 continue else: som += l[j] av = som/(j-i+1) if av > m: m = av j = j+1 i += 1 print(m)
1530628500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Anton", "Danik", "Friendship"]
0de32a7ccb08538a8d88239245cef50b
NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.
If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.
standard output
standard input
Python 3
Python
800
train_004.jsonl
e8159bffaa83d3c7a083730a2b620162
256 megabytes
["6\nADAAAA", "7\nDDDAADA", "6\nDADADA"]
PASSED
n = int(input()) s = input() p = 0 q = 0 for x in s: if x=='A': p+=1 else: q+=1 if p>q: print("Anton") elif q>p: print("Danik") else: print("Friendship")
1479227700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["YES\nNO\nNO\nYES"]
67856314f24ed718eb9b0d9fc9ab1abe
NoteConsider the example test from the statement.In order to obtain "ba" from "ababa", you may press Backspace instead of typing the first and the fourth characters.There's no way to obtain "bb" while typing "ababa".There's no way to obtain "aaaa" while typing "aaa".In order to obtain "ababa" while typing "aababa", you have to press Backspace instead of typing the first character, then type all the remaining characters.
You are given two strings $$$s$$$ and $$$t$$$, both consisting of lowercase English letters. You are going to type the string $$$s$$$ character by character, from the first character to the last one.When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if $$$s$$$ is "abcbd" and you press Backspace instead of typing the first and the fourth characters, you will get the string "bd" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if $$$s$$$ is "abcaa" and you press Backspace instead of the last two letters, then the resulting text is "a".Your task is to determine whether you can obtain the string $$$t$$$, if you type the string $$$s$$$ and press "Backspace" instead of typing several (maybe zero) characters of $$$s$$$.
For each test case, print "YES" if you can obtain the string $$$t$$$ by typing the string $$$s$$$ and replacing some characters with presses of "Backspace" button, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of test cases. The first line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$). Each character of $$$s$$$ is a lowercase English letter. The second line of each test case contains the string $$$t$$$ ($$$1 \le |t| \le 10^5$$$). Each character of $$$t$$$ is a lowercase English letter. It is guaranteed that the total number of characters in the strings over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,500
train_105.jsonl
c9283d50f2f81b1034949fd581dff554
256 megabytes
["4\nababa\nba\nababa\nbb\naaa\naaaa\naababa\nababa"]
PASSED
#!/usr/bin/env python3 def solve(s, t): #print('---------') #print(s) #print(t) if 0: if t == s: return 'YES' if len(t) >= len(s): return 'NO' if t in s: return 'YES' #s = f' {s} ' #t = f' {t} ' max_tries = len(s) - len(t) +2 #print(len(s), len(t)) #max_tries = len(s) +2 #print('max_tries', max_tries) len_s = len(s) len_t = len(t) max_tries = 500 if max_tries > len_s: max_tries = len_s + 3 for i in range(max_tries): j = 0 #i = 0 last_i = 0 for i in range(i, len_s): if j == 0 and s[i] == t[j]: j += 1 last_i = i elif j > 0 and s[i] == t[j] and (i - last_i) % 2 == 1: j += 1 last_i = i #print(3, last_i) #print('in') if j == len_t: if (len_s - i) % 2 == 0: break else: return 'YES' elif len_s - i < len_t - j: break i += 1 #print('--------') #print(s, t) #print(j, len(t)) #print('--------') return 'NO' def main(): if 0: #print(solve('aabcddeff', 'adf')) #print(solve('ababa', 'bb')) #print(solve('aababaaababa', 'ababa')) #print(solve('baabacbaas', 'ababa')) #print(solve('paxghjnihn', 'hn')) #print(solve('aababa', 'ababa')) #print(solve('aaaa', 'aaaaa')) #print(solve('aabcdaaef', 'abcdef')) #print(solve('aabcabcad', 'abcd')) #print(solve('wlclsnht', 'ct')) #print(solve('aabbabababb', 'bbb')) print(solve('aaaaabc', 'abc')) ''' aaaaabca abca abc ''' exit() if 0: tests = [] tests.append(('cccabcaacba', 'acba', 'YES')) tests.append(('eowhldode', 'dode', 'YES')) tests.append(('wlclsnht', 'ct', 'YES')) tests.append(('ababxc', 'abc', 'NO')) tests.append(('ababa', 'bb', 'NO')) tests.append(('aaaaaababa', 'ababa', 'YES')) tests.append(('aaabcdaaef', 'abcdef', 'YES')) tests.append(('aaaa', 'aaaaa', 'NO')) tests.append(('aaaaa', 'aaaa', 'YES')) tests.append(('aaaaaa', 'aaaa', 'YES')) tests.append(('aaaaaa', 'aaaaa', 'YES')) tests.append(('aababa', 'aababa', 'YES')) tests.append(('ababa', 'ba', 'YES')) tests.append(('ababa', 'bb', 'NO')) tests.append(('aaa', 'aaaa', 'NO')) tests.append(('aababa', 'ababa', 'YES')) tests.append(('paxghjnihn','hn', 'YES')) tests.append(('hdmevxvn','n', 'YES')) tests.append(('azdfhfxem','xem', 'YES')) tests.append(('eowhldode','dode', 'YES')) tests.append(('wlclsnht','ct', 'YES')) tests.append(('bpflheocamv','v', 'YES')) tests.append(('flejfh','hixqqbnikthccagc', 'NO')) tests.append(('dugt','eebmbpykcsmi', 'NO')) tests.append(('oivgrzwppny','zhfyiuu', 'NO')) tests.append(('ebkqjcbcwviqkojnzyruwygtbvwws','bofzr', 'NO')) tests.append(('heaveltnpirkveysmhnvriwifohpwddgqrqdmeszfgsyvuzccztrcmgafwunyfmauoajdasezxwnthqqszieayziraftsqcsrarcccjnmoxbvuuxfktsqphhbqypmxvpdjscyjbvkqhgdimvbkggzvwpdyuutmyicjfsgmovbotgaktouyessybvpvhgcycdolepfltgiohzgcbrgieamlnqukdpazjsbjpzhkuexxtjgktqtuimgzuhkjdjadccvzhmrmzwwpywldclghgsvdjhzkpzyqirxinqmizepkkoeiotrnkkpbczjxjddmshrjmzcfnhuxrbwdnvipgirpcgyhpiwxvydeyhutkfheadrvqztpnskmifbpouimfxzlrwaocxosbgiynpwflgexldzxypsiualdxwijqgapittmcykqxishgvynnxoxvtgantznjvpzzsafjufvtkemzsfakhlvvhgxnskazrhizytjwxnyjerywapuxh', 'zhvhnx', 'YES')) tests.append((tests[-1][0]*4, tests[-1][1]*4, tests[-1][2])) tests.append(('a'*100000 + 'abc', 'abc', 'YES')) for test in tests: if solve(test[0], test[1]) == test[2]: print('pass') pass else: print(test[0], test[1], test[2], 'failed') exit() #print('input:') if True: tests = input() tests = int(tests.strip()) sa = [] ta = [] for _ in range(tests): sa.append(input()) ta.append(input()) #print() for i, _ in enumerate(sa): s = sa[i] t = ta[i] result = solve(s, t) print(result) if __name__ == '__main__': main()
1626964500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1\n4\n1\n3"]
dc1a20d875572a3f45a9844030b0fcf4
NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is $$$\{2, 3, 4, 5\}$$$.In the fourth test case, one of the maximum cliques is $$$\{3, 4, 6\}$$$.
Soroush and Keshi each have a labeled and rooted tree on $$$n$$$ vertices. Both of their trees are rooted from vertex $$$1$$$.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $$$n$$$ vertices.They add an edge between vertices $$$u$$$ and $$$v$$$ in the memorial graph if both of the following conditions hold: One of $$$u$$$ or $$$v$$$ is the ancestor of the other in Soroush's tree. Neither of $$$u$$$ or $$$v$$$ is the ancestor of the other in Keshi's tree. Here vertex $$$u$$$ is considered ancestor of vertex $$$v$$$, if $$$u$$$ lies on the path from $$$1$$$ (the root) to the $$$v$$$.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.
For each test case print a single integer — the size of the maximum clique in the memorial graph.
The first line contains an integer $$$t$$$ $$$(1\le t\le 3 \cdot 10^5)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2\le n\le 3 \cdot 10^5)$$$. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \ldots, a_n$$$ $$$(1 \le a_i &lt; i)$$$, $$$a_i$$$ being the parent of the vertex $$$i$$$ in Soroush's tree. The third line of each test case contains $$$n-1$$$ integers $$$b_2, \ldots, b_n$$$ $$$(1 \le b_i &lt; i)$$$, $$$b_i$$$ being the parent of the vertex $$$i$$$ in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.
standard output
standard input
PyPy 2
Python
2,300
train_085.jsonl
52dfb9e6684e60f172c36358acbd4dcc
256 megabytes
["4\n4\n1 2 3\n1 2 3\n5\n1 2 3 4\n1 1 1 1\n6\n1 1 1 1 2\n1 2 1 2 2\n7\n1 1 3 4 4 5\n1 2 1 4 2 5"]
PASSED
import sys import os from io import BytesIO from operator import getitem if sys.version_info[0] < 3: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) f = sys.stdin if os.environ.get('USER') == "loic": f = open("data.in") line = lambda: f.readline().strip('\r\n').split() def write(w): sys.stdout.write(w) sys.stdout.write("\n") # From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def dfs_time(g, start): times_vis = [-1] * len(g) q = [start] times_vis[start] = 0 c = 0 while q: n = q[-1] if times_vis[n] == 1: t_out[n] = c c += 1 q.pop() else: t_in[n] = c c += 1 times_vis[n] = 1 for ch in reversed(g[n]): times_vis[ch] = 0 q.append(ch) def dfs(g, start): times_vis = [-1] * len(g) q = [start] times_vis[start] = 0 mx = 0 data = [(t_in[n],t_out[n],n) for n in range(N)] sl = SortedList() rep = [None for _ in range(N)] while q: n = q[-1] if times_vis[n] == 1: sl.remove(data[n]) if rep[n] is not None: r = rep[n] sl.add(data[r]) q.pop() else: idx = sl.bisect_left(data[n]) if idx > 0: itv = getitem(sl, idx-1) if itv[1] > t_out[n]: sl.remove(itv) rep[n] = itv[2] sl.add(data[n]) mx = max(mx, len(sl)) times_vis[n] = 1 for ch in reversed(g[n]): times_vis[ch] = 0 q.append(ch) return mx def solve(): dfs_time(G2, 0) res = dfs(G1, 0) return str(res) T = int(line()[0]) for test in range(1,T+1): N = int(line()[0]) G1 = [[] for _ in range(N)] G2 = [[] for _ in range(N)] par = list(map(int,line())) for i in range(len(par)): G1[par[i]-1].append(i+1) par = list(map(int,line())) for i in range(len(par)): G2[par[i]-1].append(i+1) t_in = [-1]*N t_out = [-1]*N write(solve()) f.close()
1621866900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["2\n1 1\n2 -1", "2\n1 1\n1 1", "-1"]
ec2f247cc30144e61e76805786475622
NoteIn the first example, we can make a +1 operation on the two first digits, transforming number $$$\textbf{22}3$$$ into $$$\textbf{33}3$$$, and then make a -1 operation on the last two digits, transforming $$$3\textbf{33}$$$ into $$$3\textbf{22}$$$.It's also possible to do these operations in reverse order, which makes another correct answer.In the last example, one can show that it's impossible to transform $$$35$$$ into $$$44$$$.
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.A positive integer $$$a$$$ is initially on the screen. The player can put a coin into the machine and then add $$$1$$$ to or subtract $$$1$$$ from any two adjacent digits. All digits must remain from $$$0$$$ to $$$9$$$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $$$1$$$ to $$$9$$$, to subtract $$$1$$$ from $$$0$$$ and to subtract $$$1$$$ from the leading $$$1$$$. Once the number on the screen becomes equal to $$$b$$$, the player wins the jackpot. $$$a$$$ and $$$b$$$ have the same number of digits.Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
If it is impossible to win the jackpot, print a single integer $$$-1$$$. Otherwise, the first line must contain the minimal possible number $$$c$$$ of coins the player has to spend. $$$\min(c, 10^5)$$$ lines should follow, $$$i$$$-th of them containing two integers $$$d_i$$$ and $$$s_i$$$ ($$$1\le d_i\le n - 1$$$, $$$s_i = \pm 1$$$) denoting that on the $$$i$$$-th step the player should add $$$s_i$$$ to the $$$d_i$$$-th and $$$(d_i + 1)$$$-st digits from the left (e. g. $$$d_i = 1$$$ means that two leading digits change while $$$d_i = n - 1$$$ means that there are two trailing digits which change). Please notice that the answer may be very big and in case $$$c &gt; 10^5$$$ you should print only the first $$$10^5$$$ moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) standing for the length of numbers $$$a$$$ and $$$b$$$. The next two lines contain numbers $$$a$$$ and $$$b$$$, each one on a separate line ($$$10^{n-1} \le a, b &lt; 10^n$$$).
standard output
standard input
Python 3
Python
2,700
train_037.jsonl
3682dc884087d0475b348a1c434078ca
256 megabytes
["3\n223\n322", "2\n20\n42", "2\n35\n44"]
PASSED
def main(): n = int(input()) a = list(map(int, (x for x in input()))) b = list(map(int, (x for x in input()))) x = [0] * (n - 1) x[0] = b[0] - a[0] for i in range(1, n - 1): x[i] = b[i] - a[i] - x[i - 1] if a[n - 1] + x[n - 2] != b[n - 1]: print(-1) return cnt = sum(map(abs, x)) # prevbug: ftl print(cnt) cnt = min(cnt, 10 ** 5) index = 0 def handle_zero_nine(cur_zero): nonlocal cnt nxt = index + 1 # cur_zero = True prevbug: preserved this line while True: if cur_zero and a[nxt + 1] != 9: break if not cur_zero and a[nxt + 1] != 0: break nxt += 1 cur_zero = not cur_zero while nxt > index: if cnt == 0: break if cur_zero: print(nxt + 1, 1) a[nxt] += 1 a[nxt + 1] += 1 else: print(nxt + 1, -1) a[nxt] -= 1 a[nxt + 1] -= 1 nxt -= 1 cnt -= 1 # print(a) cur_zero = not cur_zero while cnt > 0: if a[index] == b[index]: index += 1 continue elif a[index] > b[index] and a[index + 1] == 0: handle_zero_nine(True) elif a[index] < b[index] and a[index + 1] == 9: handle_zero_nine(False) elif a[index] > b[index]: print(index + 1, -1) a[index] -= 1 a[index + 1] -= 1 cnt -= 1 # print(a) elif a[index] < b[index]: print(index + 1, 1) a[index] += 1 a[index + 1] += 1 cnt -= 1 # print(a) if __name__ == '__main__': main()
1551627300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n0\n3"]
d5627b9fe5f6c5a7247e1f9d9e9b0c6a
NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element.
Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.
For each test case print a single integer — the maximum number of elements Eshag can delete from the array $$$a$$$.
The first line contains an integer $$$t$$$ $$$(1\le t\le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 100)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1\le a_i \le 100)$$$ — the elements of the array $$$a$$$.
standard output
standard input
Python 3
Python
800
train_085.jsonl
1424e58ee903da5d88219bef5284bf05
256 megabytes
["3\n6\n1 1 1 2 2 3\n6\n9 9 9 9 9 9\n6\n6 4 1 1 4 1"]
PASSED
for i in range(int(input())): a, b = int(input()), [int(x) for x in input().split()] print(a - b.count(min(b)))
1621866900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
904af5d6a9d84b7b7b7ff8d63e6f0254
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
standard output
standard input
Python 3
Python
2,100
train_110.jsonl
765919fc9120fae0599ea4a5e2b713c2
256 megabytes
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
PASSED
from typing import List, Dict, Set, Sequence, Tuple, Deque, AnyStr, Optional # from sortedcontainers import SortedDict, SortedSet, SortedList from collections import deque, Counter, OrderedDict import bisect case_num = int(input()) for case_index in range(case_num): s = input() t = input() t_indexes = [] # 记录t在s中出现的起点索引的位置 for i in range(len(s)): if s[i:i + len(t)] == t: t_indexes.append(i) if len(t_indexes) == 0: print('0 1') continue if len(t) == 1: print(f'{len(t_indexes)} 1') continue dp1 = [0 for i in range(len(t_indexes) + 1)] # dp[i]表示从t_indexes[i]开始(包括)且t_indexes[i]处的t被删去时的最少操作次数 min1 = 1000000 # 总体的最少操作次数 for i in range(len(t_indexes) - 1, -1, -1): j = bisect.bisect_left(t_indexes, t_indexes[i] + len(t)) # 因为t_indexes[i]要被删去,那么,接下来可能要被删去的就是t_indexes[j]处开始的t dp1[i] = 100000000 if j >= len(t_indexes): dp1[i] = 1 else: l = bisect.bisect_left(t_indexes, t_indexes[j] + len(t)) # 从t_indexes[j]开始到t_indexes[l](不包括)为止,必须有一个t被删去 for k in range(j, l): # 遍历j,l间被删去的t,选择其中最小的,就是i开始且删除i时的最少操作次数 dp1[i] = min(dp1[i], 1 + dp1[k]) if t_indexes[i] - t_indexes[0] < len( t): # 当当前s中的索引t_indexes[i]已经和最小的t的索引t_indexes[0]相差小于len(t)时,说明再往前已经没有t可以删了,可以更新min1了 min1 = min(min1, dp1[i]) dp2 = [[0 for i in range(len(t_indexes) + 1)] for j in range(len(t_indexes) + 1)] # dp2[i][j]表示从t_indexes[i]开始(包括)且t_indexes[i]处的t被删去且总删除次数为j时的删除方式种数 dp2[len(t_indexes)][0] = 1 for i in range(len(t_indexes) - 1, -1, -1): j = bisect.bisect_left(t_indexes, t_indexes[i] + len(t)) # 同dp1计算时中j的作用 if j >= len(t_indexes): dp2[i][1] = 1 continue # 只需要计算t_indexes[i]开始的最少删除次数时的操作种数,因为如果从当前索引开始的删除次数不是最少的,且总体删除次数最少时用到了当前这种方式,那么可以选择当前索引开始的最少删除次数,使总体删除次数更少,就矛盾了 l = bisect.bisect_left(t_indexes, t_indexes[j] + len(t)) # 同dp1计算时的l的作用 dp2[i][dp1[i]] = sum(dp2[k][dp1[i] - 1] for k in range(j, l)) % 1000000007 # print(min1) # print(t_indexes) # print(dp1) # print(dp2) ans = 0 for i in range(len(t_indexes)): if t_indexes[i] - t_indexes[0] >= len(t): break ans = (ans + dp2[i][min1]) % 1000000007 print(f'{min1} {ans}')
1662993300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["25", "849"]
79ee1ff924432a184d8659db5f960304
NoteThe tree in the second example is given below: We have $$$21$$$ subsets of size $$$2$$$ in the given tree. Hence, $$$$$$S \in \left\{\{1, 2\}, \{1, 3\}, \{1, 4\}, \{1, 5\}, \{1, 6\}, \{1, 7\}, \{2, 3\}, \{2, 4\}, \{2, 5\}, \{2, 6\}, \{2, 7\}, \{3, 4\}, \{3, 5\}, \{3, 6\}, \{3, 7\}, \{4, 5\}, \{4, 6\}, \{4, 7\}, \{5, 6\}, \{5, 7\}, \{6, 7\} \right\}.$$$$$$ And since we have $$$7$$$ vertices, $$$1 \le r \le 7$$$. We need to find the sum of $$$f(r, S)$$$ over all possible pairs of $$$r$$$ and $$$S$$$. Below we have listed the value of $$$f(r, S)$$$ for some combinations of $$$r$$$ and $$$S$$$. $$$r = 1$$$, $$$S = \{3, 7\}$$$. The value of $$$f(r, S)$$$ is $$$5$$$ and the corresponding subtree is $$$\{2, 3, 4, 6, 7\}$$$. $$$r = 1$$$, $$$S = \{5, 4\}$$$. The value of $$$f(r, S)$$$ is $$$7$$$ and the corresponding subtree is $$$\{1, 2, 3, 4, 5, 6, 7\}$$$. $$$r = 1$$$, $$$S = \{4, 6\}$$$. The value of $$$f(r, S)$$$ is $$$3$$$ and the corresponding subtree is $$$\{4, 6, 7\}$$$.
You are given a tree $$$G$$$ with $$$n$$$ vertices and an integer $$$k$$$. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$.For a vertex $$$r$$$ and a subset $$$S$$$ of vertices of $$$G$$$, such that $$$|S| = k$$$, we define $$$f(r, S)$$$ as the size of the smallest rooted subtree containing all vertices in $$$S$$$ when the tree is rooted at $$$r$$$. A set of vertices $$$T$$$ is called a rooted subtree, if all the vertices in $$$T$$$ are connected, and for each vertex in $$$T$$$, all its descendants belong to $$$T$$$.You need to calculate the sum of $$$f(r, S)$$$ over all possible distinct combinations of vertices $$$r$$$ and subsets $$$S$$$, where $$$|S| = k$$$. Formally, compute the following: $$$$$$\sum_{r \in V} \sum_{S \subseteq V, |S| = k} f(r, S),$$$$$$ where $$$V$$$ is the set of vertices in $$$G$$$.Output the answer modulo $$$10^9 + 7$$$.
Print the answer modulo $$$10^9 + 7$$$.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le n$$$). Each of the following $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$), denoting an edge between vertex $$$x$$$ and $$$y$$$. It is guaranteed that the given edges form a tree.
standard output
standard input
Python 3
Python
2,500
train_089.jsonl
548ab908d319fee1b75d8be50ac97f0d
512 megabytes
["3 2\n1 2\n1 3", "7 2\n1 2\n2 3\n2 4\n1 5\n4 6\n4 7"]
PASSED
import sys sys.setrecursionlimit(300000) import faulthandler faulthandler.enable() n, k = map(int, input().split()) MOD = 10**9 + 7 fact = [1 for i in range(n+1)] for i in range(2, n+1): fact[i] = i*fact[i-1] % MOD inv_fact = [1 for i in range(n+1)] inv_fact[-1] = pow(fact[-1], MOD-2, MOD) for i in range(1, n): inv_fact[n-i] = (n-i+1)*inv_fact[n-i+1] % MOD def comb(a, b): if a < b: return 0 return fact[a]*inv_fact[b]*inv_fact[a-b] % MOD edges = [[] for i in range(n)] for _ in range(n-1): x, y = map(lambda a: int(a)-1, input().split()) edges[x].append(y) edges[y].append(x) ends = [[] for i in range(n)] visited = [0 for i in range(n)] totals = [1 for i in range(n)] dfs_stack = [0] while len(dfs_stack) > 0: node = dfs_stack[-1] if visited[node] == 1: visited[node] = 2 for next_node in edges[node]: if visited[next_node] == 2: totals[node] += totals[next_node] ends[node].append(totals[next_node]) ends[node].append(n-totals[node]) dfs_stack.pop() else: visited[node] = 1 for next_node in edges[node]: if visited[next_node] == 0: dfs_stack.append(next_node) z = n*n * comb(n, k) % MOD node_v = [0 for i in range(n)] for i in range(n): node_v[i] = sum(comb(e, k) for e in ends[i]) % MOD for e in ends[i]: z = (z - e*e * (comb(n-e, k) + comb(e, k) - node_v[i])) % MOD print(z)
1654007700
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
2 seconds
["tolik", "bolik"]
55099493c66b003d4261310bf2cc8f93
null
There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».
Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.
The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.
standard output
standard input
Python 3
Python
2,000
train_030.jsonl
1275c417648c12931133a58c02fe061f
64 megabytes
["2\n2 1\n3 2", "4\n1 1\n1 1\n1 1\n1 1"]
PASSED
def f(x): if x%4==0: return x elif x%4==1: return 1 elif x%4==2: return x+1 return 0 n = int(input()) res = 0 for i in range(n): x,m = input().split() x,m = int(x),int(m) res ^= f(x-1)^f(x+m-1) if res == 0: print("bolik") else: print("tolik")
1275145200
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
4 seconds
["1 0 1 2 -1 -1 \n1 \n-1 -1 -1 \n1 0 0 0 0 \n1 1 2 1"]
055346dd6d2e0cff043b52a395e31fdf
null
You are given a directed graph $$$G$$$ which can contain loops (edges from a vertex to itself). Multi-edges are absent in $$$G$$$ which means that for all ordered pairs $$$(u, v)$$$ exists at most one edge from $$$u$$$ to $$$v$$$. Vertices are numbered from $$$1$$$ to $$$n$$$.A path from $$$u$$$ to $$$v$$$ is a sequence of edges such that: vertex $$$u$$$ is the start of the first edge in the path; vertex $$$v$$$ is the end of the last edge in the path; for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from $$$u$$$ to $$$u$$$.For each vertex $$$v$$$ output one of four values: $$$0$$$, if there are no paths from $$$1$$$ to $$$v$$$; $$$1$$$, if there is only one path from $$$1$$$ to $$$v$$$; $$$2$$$, if there is more than one path from $$$1$$$ to $$$v$$$ and the number of paths is finite; $$$-1$$$, if the number of paths from $$$1$$$ to $$$v$$$ is infinite. Let's look at the example shown in the figure. Then: the answer for vertex $$$1$$$ is $$$1$$$: there is only one path from $$$1$$$ to $$$1$$$ (path with length $$$0$$$); the answer for vertex $$$2$$$ is $$$0$$$: there are no paths from $$$1$$$ to $$$2$$$; the answer for vertex $$$3$$$ is $$$1$$$: there is only one path from $$$1$$$ to $$$3$$$ (it is the edge $$$(1, 3)$$$); the answer for vertex $$$4$$$ is $$$2$$$: there are more than one paths from $$$1$$$ to $$$4$$$ and the number of paths are finite (two paths: $$$[(1, 3), (3, 4)]$$$ and $$$[(1, 4)]$$$); the answer for vertex $$$5$$$ is $$$-1$$$: the number of paths from $$$1$$$ to $$$5$$$ is infinite (the loop can be used in a path many times); the answer for vertex $$$6$$$ is $$$-1$$$: the number of paths from $$$1$$$ to $$$6$$$ is infinite (the loop can be used in a path many times).
Output $$$t$$$ lines. The $$$i$$$-th line should contain an answer for the $$$i$$$-th test case: a sequence of $$$n$$$ integers from $$$-1$$$ to $$$2$$$.
The first contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5$$$) — numbers of vertices and edges in graph respectively. The next $$$m$$$ lines contain edges descriptions. Each line contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the start and the end of the $$$i$$$-th edge. The vertices of the graph are numbered from $$$1$$$ to $$$n$$$. The given graph can contain loops (it is possible that $$$a_i = b_i$$$), but cannot contain multi-edges (it is not possible that $$$a_i = a_j$$$ and $$$b_i = b_j$$$ for $$$i \ne j$$$). The sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$. Similarly, the sum of $$$m$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,100
train_103.jsonl
f6678b90251659960cf811b8f860934c
512 megabytes
["5\n\n6 7\n1 4\n1 3\n3 4\n4 5\n2 1\n5 5\n5 6\n\n1 0\n\n3 3\n1 2\n2 3\n3 1\n\n5 0\n\n4 4\n1 2\n2 3\n1 4\n4 3"]
PASSED
from collections import Counter, deque # from itertools import combinations import bisect import heapq from locale import currency import math from re import S import sys from types import GeneratorType # sys.stdin = open('grey.in', 'r') # sys.setrecursionlimit(1 * 10**9) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc result = [] LOG = 18 array = [1, 2, 3, 4, 5, 6, 7, 8] def calc(numOne, numTwo): currentSum = 0 for i in range(32): firstBit, secondBit = min(1, numOne & (1 << i)), min(1, numTwo & (1 << i)) currentSum += (firstBit ^ secondBit) return currentSum # counter = Counter() # for i in range(0, 119000): # counter[calc(i, i + 1)] += 1 # print(counter) input = sys.stdin.readline # t = int(input()) # result = [] # for _ in range(t): # a, b = map(int, input().split()) # def solve(): # state = False # count = 0 # currentMin = float('inf') # for z in range(0, b + 5): # currentB = b + z # count = 0 # for i in range(32): # firstBit, secondBit = a & (1 << i), currentB & (1 << i) # if secondBit and not firstBit: # state = True # continue # if firstBit and not secondBit: # count += (2**i) # currentMin = min(currentMin, count + 1 + z if state else count + z) # return min(currentMin, b - a) # print(solve()) # # print(result) class SegmentTree2D: def __init__(self, row, col, inMatrix): self.rows = row self.cols = col self.inMatrix = inMatrix self.matrix = [[0 for z in range(col + 1)] for i in range(row + 1)] self.genTable() def genTable(self): self.matrix[0][0] = 0 for row in range(self.rows): currentSum = 0 for col in range(self.cols): currentSum += self.inMatrix[row][col] above = self.matrix[row][col + 1] self.matrix[row + 1][col + 1] = currentSum + above def sumRegion(self, rowOne, colOne, rowTwo, colTwo): rowOne += 1 rowTwo += 1 colOne += 1 colTwo += 1 bottomRight, above = self.matrix[rowTwo][colTwo], self.matrix[rowOne - 1][colTwo] left, topLeft = self.matrix[rowTwo][colOne - 1], self.matrix[rowOne - 1][colOne - 1] return bottomRight - above - left + topLeft class LCA: def __init__(self, neighbourNodes, rootNode): self.neighbourNodes = neighbourNodes self.log = 18 self.parentNode = [[i for i in range(self.log)] for z in range(len(neighbourNodes))] self.depth = [0 for i in range(len(neighbourNodes))] self.bfs(rootNode, rootNode, 0) def bfs(self, currentNode, parentNode, currentDepth): queue = deque() queue.append((currentNode, parentNode, currentDepth)) while(queue): currentNode, parentNode, currentDepth = queue.popleft() self.parentNode[currentNode][0] = parentNode for i in range(1, self.log): self.parentNode[currentNode][i] = self.parentNode[self.parentNode[currentNode][i - 1]][i - 1] for node in self.neighbourNodes[currentNode]: if node != parentNode: queue.append((node, currentNode, currentDepth + 1)) self.depth[currentNode] = currentDepth def lca(self, nodeOne, nodeTwo): diff = abs(self.depth[nodeOne] - self.depth[nodeTwo]) if self.depth[nodeOne] < self.depth[nodeTwo]: nodeOne, nodeTwo = nodeTwo, nodeOne for i in reversed(range(self.log)): if diff & (1 << i): nodeOne = self.parentNode[nodeOne][i] if nodeOne == nodeTwo: return nodeOne for i in reversed(range(self.log)): if self.parentNode[nodeOne][i] != self.parentNode[nodeTwo][i]: nodeOne, nodeTwo = self.parentNode[nodeOne][i], self.parentNode[nodeTwo][i] return self.parentNode[nodeOne][0] def power(a, b, mod): if not b: return 1 temp = power(a, b // 2, mod) result = temp * temp if b % 2 == 0 else temp * temp * a result %= mod return result def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def genSparseTable(array, comp): sparseTable = [[float('inf') for i in range(LOG)] for x in range(len(array))] for i in range(len(array)): sparseTable[i][0] = array[i] for i in range(1, LOG): j = 0 while((j + (1 << i) - 1) < len(array)): sparseTable[j][i] = comp(sparseTable[j][i - 1], sparseTable[j + (1 << (i - 1))][i - 1]) j += 1 return sparseTable def query(l, r, sparseTable, comp): length = (r - l) + 1 idx = int(math.log(length, 2)) return comp(sparseTable[l][idx], sparseTable[r - (1 << idx) + 1][idx]) # t = int(input()) # for _ in range(t): # n, x, y = map(int, input().split()) # stringOne, stringTwo = map(int, input().split()) # def solve(): # rightMostIdx = None # cnt = 0 # for numOne, numTwo in zip(stringOne, stringTwo): # if numOne != numTwo: # cnt += 1 # if cnt % 2: # return -1 # for i in reversed(range(n)): # if stringOne[i] == stringTwo[i]: # rightMostIdx = i # break # leftMostIdx = None # currentIdx = 0 # total = 0 # while(currentIdx < n - 1): # if stringOne[currentIdx] != stringTwo[currentIdx] and stringOne[currentIdx + 1] != stringTwo[currentIdx + 1]: # if rightMostIdx is not None and rightMostIdx - 1 > currentIdx + 1: # total += min(x, 2 * y) # elif leftMostIdx is not None and leftMostIdx + 1 < currentIdx: # total += min(x, 2 * y) # else: # total += x # if leftMostIdx is None: # leftMostIdx = currentIdx # currentIdx += 2 # elif stringOne[currentIdx] != stringTwo[currentIdx]: input = sys.stdin.readline t = int(input()) for _ in range(t): input() n, m = map(int, input().split()) neighbourNodes = [[] for i in range(n)] for i in range(m): path, toPath = map(int, input().split()) path -= 1 toPath -= 1 neighbourNodes[path].append(toPath) def solve(): revNeighbourNodes = [[] for i in range(n)] for node in range(n): for neighbour in neighbourNodes[node]: revNeighbourNodes[neighbour].append(node) component = [node for node in range(n)] visited = [False for node in range(n)] stack = [] @bootstrap def dfsOne(currentNode): if visited[currentNode]: yield None visited[currentNode] = True for node in revNeighbourNodes[currentNode]: (yield dfsOne(node)) stack.append(currentNode) yield None; for node in range(n): if not visited[node]: dfsOne(node) @bootstrap def dfsTwo(currentNode, comp): if visited[currentNode]: yield None visited[currentNode] = True component[currentNode] = comp for node in neighbourNodes[currentNode]: if not visited[node]: (yield dfsTwo(node, comp)) yield None visited = [False for node in range(n)] while(stack): currentNode = stack.pop() if not visited[currentNode]: dfsTwo(currentNode, currentNode) isCycle = [False for node in range(n)] counter = Counter(component) for comp in counter: if counter[comp] > 1: isCycle[comp] = True for node in range(n): for neighbour in neighbourNodes[node]: if node == neighbour: isCycle[component[node]] = True break newEdges = [[] for node in range(n)] for node in range(n): for neighbour in neighbourNodes[node]: if component[node] != component[neighbour]: newEdges[component[node]].append(component[neighbour]) result = [0 for node in range(n)] visited = [False for node in range(n)] toBeVisited = [] @bootstrap def dfsThree(currentNode, currentAns): result[currentNode] += currentAns visited[currentNode] = True for node in newEdges[currentNode]: if visited[node]: result[node] += currentAns toBeVisited.append(node) continue newAns = currentAns if not isCycle[node] else float('inf') (yield dfsThree(node, newAns)) yield None ans = 1 if not isCycle[component[0]] else float('inf') dfsThree(component[0], ans) visited = [False for node in range(n)] @bootstrap def dfsFour(currentNode, ans): result[currentNode] += ans visited[currentNode] = True for node in newEdges[currentNode]: if not visited[node]: (yield dfsFour(node, max(ans, result[currentNode]))) yield None toBeVisited.sort(reverse = True, key = lambda x: (result[x])) for node in toBeVisited: if not visited[node]: dfsFour(node, result[node]) for node in range(n): ans = result[component[node]] if ans not in [-1, 0, 1, 2]: if ans == float('inf'): ans = -1 elif ans > 1: ans = 2 else: ans = 0 result[node] = ans result = [str(re) for re in result] for i in range(len(result)): if result[i] == "inf": result[i] = str(-1) return result print(' '.join(solve()))
1625927700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6"]
ddbac4053bd07eada84bc44275367ae2
null
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: the graph contains exactly 2n + p edges; the graph doesn't contain self-loops and multiple edges; for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; ) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists.
standard output
standard input
PyPy 3
Python
1,500
train_001.jsonl
ffa59de54a103421c0547de702ffc6af
256 megabytes
["1\n6 0"]
PASSED
#b=b[2:].zfill(32) #for deque append(),pop(),appendleft(),popleft(),count() import math,sys from collections import Counter, defaultdict, deque from sys import stdin, stdout input = stdin.readline lili=lambda:list(map(int,sys.stdin.readlines())) li = lambda:list(map(int,input().split())) I=lambda:int(input()) S=lambda:input().strip() mod = 1000000007 for _ in range(I()): n,p=li() k=1 c=k+1 p=2*n+p while(p): print(k,c) p-=1 if(c==n): k+=1 c=k c+=1
1394983800
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2\n4 5", "1\n4"]
54c23dda2aa1d58ecf22c03015dca55c
null
Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&amp;", in Pascal — by "and".
In the first line print a single integer k (k &gt; 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 109).
standard output
standard input
PyPy 3
Python
1,800
train_053.jsonl
d0422d128e1e7f92f9e4acfeb03c63fa
256 megabytes
["5\n1 2 3 4 5", "3\n1 2 4"]
PASSED
import functools n = int(input()) nums = list(map(int, input().split())) bits = ["{0:b}".format(num) for num in nums] def possible(v): possible_vals = [ nums[x] for x in range(n) if len(bits[x]) > v and bits[x][len(bits[x])-v-1] == '1' ] if len(possible_vals) == 0: return False, [] res = functools.reduce((lambda x, y: x&y), possible_vals, pow(2, v+1)-1) return bool(res & ((1 << (v+1))-1) == (1 << v)), possible_vals for x in range(30, -1, -1): p, vals = possible(x) if p: print(len(vals)) print(' '.join(list(map(str, vals)))) break
1376062200
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["Bob\nAlice\nAlice\nBob"]
255ee92f5b860eacd9d6321195072734
NoteIn the first test case, the game ends immediately because Alice cannot make a move.In the second test case, Alice can subtract $$$2$$$ making $$$n = 2$$$, then Bob cannot make a move so Alice wins.In the third test case, Alice can subtract $$$3$$$ so that $$$n = 9$$$. Bob's only move is to subtract $$$3$$$ and make $$$n = 6$$$. Now, Alice can subtract $$$3$$$ again and $$$n = 3$$$. Then Bob cannot make a move, so Alice wins.
Alice and Bob are playing a game. They start with a positive integer $$$n$$$ and take alternating turns doing operations on it. Each turn a player can subtract from $$$n$$$ one of its divisors that isn't $$$1$$$ or $$$n$$$. The player who cannot make a move on his/her turn loses. Alice always moves first.Note that they subtract a divisor of the current number in each turn.You are asked to find out who will win the game if both players play optimally.
For each test case output "Alice" if Alice will win the game or "Bob" if Bob will win, if both players play optimally.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^9$$$) — the initial number.
standard output
standard input
PyPy 3-64
Python
1,700
train_084.jsonl
bef7825be0f6c28f21cd1fceaf41bb98
256 megabytes
["4\n1\n4\n12\n69"]
PASSED
import sys input = sys.stdin.readline inf = float('inf') def getInt(): return int(input()) def getStr(): return input().strip() def getList(split=True): s = getStr() if split: s = s.split() return map(int, s) t = getInt() # t = 1 M = 10 ** 9 + 7 A = {2**i for i in range(1, 32, 2)} def solve(): # if x is a power of 2 then Alice loose # if x is odd of x is 2 to the power off odd number then Alice loose else she will win x = getInt() if x & 1 or x in A: print("Bob") else: print("Alice") for _ in range(t): solve()
1624026900
[ "number theory", "math", "games" ]
[ 1, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["2", "3"]
4866b4b48be5833b1f5a7206a241f83d
null
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $$$n$$$ locations connected by $$$m$$$ two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.The game will start in location $$$s$$$ and end in location $$$t$$$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $$$s$$$ to $$$t$$$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $$$s$$$ or as $$$t$$$.
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for $$$s$$$ and $$$t$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$n - 1 \le m \le 3 \cdot 10^5$$$) — the number of locations and passages, respectively. Then $$$m$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) describing the endpoints of one of the passages. It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
standard output
standard input
Python 2
Python
2,100
train_033.jsonl
7b43d912307529fc1e36082abe5efadc
256 megabytes
["5 5\n1 2\n2 3\n3 1\n4 1\n5 2", "4 3\n1 2\n4 3\n3 2"]
PASSED
from sys import stdin from itertools import repeat def main(): n, m = map(int, stdin.readline().split()) dat = map(int, stdin.read().split(), repeat(10, 2 * m)) xt = [None] * (2 * m) la = [None] * (n + 1) j = 0 for i in xrange(m): x, y = dat[j], dat[j+1] xt[j] = la[y] la[y] = j j += 1 xt[j] = la[x] la[x] = j j += 1 st = [(1, 0, la[1])] po = st.pop pu = st.append itr = la[:] c = 1 low = [0] * (n + 1) d = [0] * (n + 1) gn = 0 g = [0] * (n + 1) ss = [] pos = ss.pop pus = ss.append ins = [0] * (n + 1) b = [] while st: x, p, it = po() if not d[x]: low[x] = d[x] = c c += 1 pus(x) ins[x] = 1 else: if low[x] > low[dat[it]]: low[x] = low[dat[it]] it = xt[it] while it is not None and d[dat[it]]: y = dat[it] if y != p and low[x] > d[y]: low[x] = d[y] it = xt[it] if it is None: if low[x] == d[x]: while 1: v = pos() ins[v] = 0 g[v] = gn if v == x: break if p: b.extend((x, p)) gn += 1 else: pu((x, p, it)) pu((dat[it], x, la[dat[it]])) dat = [g[x] for x in b] m = len(dat) / 2 xt = [None] * (2 * m) la = [None] * gn j = 0 for i in xrange(m): x, y = dat[j], dat[j+1] xt[j] = la[y] la[y] = j j += 1 xt[j] = la[x] la[x] = j j += 1 d = [None] * gn pu(0) d[0] = 0 while st: x = po() y = la[x] while y is not None: z = dat[y] if d[z] is None: d[z] = d[x] + 1 pu(z) y = xt[y] z = v = -1 for i, x in enumerate(d): if z < x: z = x v = i d = [None] * gn pu(v) d[v] = 0 while st: x = po() y = la[x] while y is not None: z = dat[y] if d[z] is None: d[z] = d[x] + 1 pu(z) y = xt[y] print max(d) main()
1530110100
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["BAAA\nABAA\nBBBA\nBBBB", "BABBB\nBBBBB\nAABBB\nAAABA\nAAAAB"]
d9c77057a596c946592e73e1561aad8f
NoteHere's the graph in the first sample test case: Here's the graph in the second sample test case:
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i &gt; 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?You have to determine the winner of the game for all initial positions of the marbles.
Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.
The first line of input contains two integers n and m (2 ≤ n ≤ 100, ). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.
standard output
standard input
Python 3
Python
1,700
train_023.jsonl
0b7ebb12df20cd2f59114d1439827346
256 megabytes
["4 4\n1 2 b\n1 3 a\n2 4 c\n3 4 b", "5 8\n5 3 h\n1 2 c\n3 1 c\n3 2 r\n5 1 r\n4 3 z\n5 4 r\n5 2 h"]
PASSED
# int(input()) # [int(i) for i in input().split()] import sys sys.setrecursionlimit(20000) def go(v,w,last): if game[v][w][last] >= 0: return(game[v][w][last]) flag = 0 move = 0 for p in edges_out[v]: if p[1] >= last: move = 1 if not go(w,p[0],p[1]): flag = 1 break if not move or not flag: game[v][w][last] = 0 return(0) else: game[v][w][last] = 1 return(1) n,m = [int(i) for i in input().split()] edges_in = [] edges_out = [] for i in range(n): edges_in.append([]) edges_out.append([]) for i in range(m): s1,s2,s3 = input().split() v = int(s1)-1 w = int(s2)-1 weight = ord(s3[0]) - ord('a') + 1 edges_out[v].append((w,weight)) edges_in[w].append((v,weight)) game = [] for i in range(n): tmp1 = [] for j in range(n): tmp2 = [] for c in range(27): tmp2.append(-1) tmp1.append(tmp2) game.append(tmp1) ##for v in range(n): ## for w in range(n): ## for last in range(27): ## go(v,w,last) for v in range(n): s = '' for w in range(n): if go(v,w,0): s = s + 'A' else: s = s + 'B' print(s) # Made By Mostafa_Khaled
1517236500
[ "games", "graphs" ]
[ 1, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["0\n1\n-1\n6\n10\n17"]
6f0d3a7971ffc2571838ecd8bf14238d
NoteTest case $$$1$$$: $$$n=1$$$, $$$m=1$$$, and initially you are standing in $$$(1, 1)$$$ so $$$0$$$ move is required to reach $$$(n, m) = (1, 1)$$$.Test case $$$2$$$: you should go down to reach $$$(2, 1)$$$.Test case $$$3$$$: it is impossible to reach $$$(1, 3)$$$ without moving right two consecutive times, or without leaving the grid.Test case $$$4$$$: an optimal moving sequence could be: $$$(1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2)$$$. It can be proved that this is the optimal solution. So the answer is $$$6$$$.
You are given a grid with $$$n$$$ rows and $$$m$$$ columns. Rows and columns are numbered from $$$1$$$ to $$$n$$$, and from $$$1$$$ to $$$m$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$. Initially, you are standing in the top left corner $$$(1, 1)$$$. Your goal is to reach the bottom right corner $$$(n, m)$$$.You can move in four directions from $$$(a, b)$$$: up to $$$(a-1, b)$$$, down to $$$(a+1, b)$$$, left to $$$(a, b-1)$$$ or right to $$$(a, b+1)$$$.You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $$$(n, m)$$$?
For each test case, print a single integer: $$$-1$$$ if it is impossible to reach $$$(n, m)$$$ under the given conditions, otherwise the minimum number of moves.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of the test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the size of the grid.
standard output
standard input
Python 3
Python
800
train_084.jsonl
96a0dcca545ceb8d9ee70d5712325dc3
256 megabytes
["6\n\n1 1\n\n2 1\n\n1 3\n\n4 2\n\n4 6\n\n10 5"]
PASSED
test = int(input()) steps = 0 ans = [] for tests in range(test): n, m = map(int, input().split()) if (n== 1 and m > 2) or (m == 1 and n > 2): steps = -1 ans.append(steps) if n == m == 1: steps = 0 ans.append(steps) if (m>=n) and n!=1: if (m+n)%2 == 0: steps = 2*((n-1) + (m-n)) ans.append(steps) if (m+n)% 2 != 0: steps = 2*((n-1) + (m-n)) - 1 ans.append(steps) if n>m and m!=1: if (m+n)%2 == 0: steps = 2*((m-1) + (n-m)) ans.append(steps) if (m+n)% 2 != 0: steps = 2*((m-1) + (n-m)) - 1 ans.append(steps) if (n==2 and m==1) or (m==2 and n==1): steps = 1 ans.append(steps) print(*ans, sep = "\n")
1650378900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["6", "8"]
4695aa2b3590a0734ef2c6c580e471a9
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
Output one integer — the minimum power needed to destroy the avengers base.
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
standard output
standard input
PyPy 3
Python
1,700
train_000.jsonl
e7c3fd91e0f1a37d1a760cf4f3954780
256 megabytes
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
PASSED
def inint(): return int(input()) def mp(): return map(int,input().split()) from bisect import bisect,bisect_left def sol(i,j): works=bisect(a,j)-bisect_left(a,i) if works==0:return A if i==j:return B*works m=(i+j)>>1 return min(B*(j-i+1)*works,sol(i,m)+sol(m+1,j)) n,k,A,B=mp() a=list(mp()) a.sort() #print(a) print(sol(1,2**n))
1549208100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1"]
f83c91c9e9252aba4736aa0bea82493b
null
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.What is the maximum amount of people that could stay at the party in the end?
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
standard output
standard input
Python 3
Python
1,600
train_024.jsonl
6fb67219662a242a155a5ae94aab3b3d
256 megabytes
["1\n3"]
PASSED
n = input() for i in range(0,int (n)): x = input() if int(x)-2 == -1: print(0) else: print(int(x)-2)
1278687600
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
1 second
["3", "10"]
54e2b6bea0dc6ee68366405945af50c6
NoteIn the second example the head moves in the following way: 1-&gt;2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2-&gt;3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3-&gt;4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4-&gt;5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4 + 3 + 2 + 1 = 10.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 ≤ fi ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Print the only integer — the number of time units needed to read the file.
The first line contains a positive integer n (1 ≤ n ≤ 2·105) — the number of fragments. The second line contains n different integers fi (1 ≤ fi ≤ n) — the number of the fragment written in the i-th sector.
standard output
standard input
Python 3
Python
1,200
train_013.jsonl
c69e87f38fd7386bca19f794d75c5aa7
256 megabytes
["3\n3 1 2", "5\n1 3 5 4 2"]
PASSED
from bisect import bisect from itertools import permutations,combinations n=int(input()) a=list(map(int,input().split())) cnt=1 b = [] for x in a: b.append([x,cnt]) cnt+=1 b.sort() res = 0 for i in range(1,n): res+=abs(b[i][1]-b[i-1][1]) print(res)
1451055600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["16.000000"]
bb3fc45f903588baf131016bea175a9f
NoteIn the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4·4 = 16.
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.
Output a single real number — the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10 - 9.
The first line contains integer n (4 ≤ n ≤ 300). Each of the next n lines contains two integers: xi, yi ( - 1000 ≤ xi, yi ≤ 1000) — the cartesian coordinates of ith special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide.
standard output
standard input
Python 3
Python
2,100
train_048.jsonl
b9da6adb7ff5f00a9127e39974a16d61
256 megabytes
["5\n0 0\n0 4\n4 0\n4 4\n2 3"]
PASSED
# calculate convex of polygon v. # v is list of complexes stand for points. def convex(v, eps=1e-8): # fetch the seed point v.sort(key=lambda x:(x.real,x.imag)) v = v[0:1] + sorted(v[1:], key=lambda x:(x-v[0]).imag/abs(x-v[0])) n = 1 for i in range(2, len(v)): while n > 1 and ((v[n]-v[n-1])*(v[i]-v[n]).conjugate()).imag>-eps: n -= 1 else: n += 1 v[n] = v[i] v[n+1:] = [] return v # calculate the area of a polygon v, anti-clockwise. # v is list of complexes stand for points. def area(v): ans = 0 for i in range(2, len(v)): ans += ((v[i]-v[i-1])*(v[i-1]-v[0]).conjugate()).imag return ans * 0.5 n = int(input()) v = [complex(*tuple(map(int, input().split()))) for i in range(0, n)] w = convex(v) n = len(w) ans = 0 def tri(i, j, k): return abs(((w[i]-w[j])*(w[i]-w[k]).conjugate()).imag) * 0.5 for i in range(0, n): for j in range(i+2, n): if i == 0 and j == n-1: continue l = i + 1 r = j while l < r-1: k = l+r>>1 if tri(i, j, k) > tri(i, j, k-1): l = k else: r = k s1 = tri(i, j, l) l = j - n + 1 r = i while l < r-1: k = l+r>>1 if tri(i, j, k) > tri(i, j, k-1): l = k else: r = k s2 = tri(i, j, l) ans = max(ans, s1 + s2) if n == 3: for p in v: if not p in w: w.append(p) ans = max(ans, area(w)) w.pop() print(ans)
1377876600
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
d2cc6efe7173a64482659ba59efeec16
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,100
train_108.jsonl
41f371e60d17f7738724802f7a0f13af
256 megabytes
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
PASSED
for _ in range(int(input())): n,l,r=[int(num) for num in input().split(" ",2)] truth=True for i in range(1,n+1): if i*(1+(l-1)//i)>r: print("No") truth=False break if truth: print("Yes") a=[i*(1+(l-1)//i) for i in range(1,n+1)] print(*a)
1657982100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["0 2 12 22", "0 3 5"]
857d84cfbf8c9ce5c95d36b4d2854a88
null
You have an array $$$a$$$ consisting of $$$n$$$ distinct positive integers, numbered from $$$1$$$ to $$$n$$$. Define $$$p_k$$$ as $$$$$$p_k = \sum_{1 \le i, j \le k} a_i \bmod a_j,$$$$$$ where $$$x \bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$. You have to find and print $$$p_1, p_2, \ldots, p_n$$$.
Print $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$.
The first line contains $$$n$$$ — the length of the array ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ space-separated distinct integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^5$$$, $$$a_i \neq a_j$$$ if $$$i \neq j$$$).
standard output
standard input
PyPy 3-64
Python
2,300
train_105.jsonl
510e4dee977c24b486afaabdc140aec0
256 megabytes
["4\n6 2 7 3", "3\n3 2 1"]
PASSED
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def fenwick_tree(n): tree = [0] * (n + 1) return tree def get_sum(i): s = 0 while i > 0: s += tree[i] i -= i & -i return s def add(i, x): while i < len(tree): tree[i] += x i += i & -i n = int(input()) a = list(map(int, input().split())) l = max(a) + 5 tree = fenwick_tree(l + 1) ans = [] la = 0 s = 0 for i in range(n): ai = a[i] u = s + i * ai v = 0 x = get_sum(ai - 1) for j in range(1, l + 1): z = min((j + 1) * ai - 1, l) y = get_sum(z) v += j * (y - x) x = y if z == l: break add(ai, 1) u -= ai * v ans.append(u) la = u s += ai def fenwick_tree(n): tree1 = [0] * (n + 1) tree2 = [0] * (n + 1) return tree1, tree2 def add0(i, x, tree): while i < len(tree): tree[i] += x i += i & -i def add(l, r, x): add0(l, -x * (l - 1), tree1) add0(r + 1, x * r, tree1) add0(l, x, tree2) add0(r + 1, -x, tree2) def get_sum0(i, tree): s = 0 while i > 0: s += tree[i] i -= i & -i return s def get_sum(s, t): s -= 1 x = get_sum0(s, tree1) + get_sum0(s, tree2) * s y = get_sum0(t, tree1) + get_sum0(t, tree2) * t return y - x tree1, tree2 = fenwick_tree(l + 1) for i in range(n): ai = a[i] ans[i] -= get_sum(ai, ai) u, v = ai, min(2 * ai - 1, l) while u < l: add(u, v, u) u += ai v = min(u + ai - 1, l) for i in range(1, n): ans[i] += ans[i - 1] sys.stdout.write(" ".join(map(str, ans)))
1626964500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["5 2", "15 1", "18 6"]
926c01419301caff034988aff98edc9d
NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\{[1, 1], [2, 3]\}$$$ and $$$\{[1, 2], [3, 3]\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\{[1, 2], [3, 5], [6, 7]\}$$$, $$$\{[1, 3], [4, 5], [6, 7]\}$$$, $$$\{[1, 4], [5, 5], [6, 7]\}$$$, $$$\{[1, 2], [3, 6], [7, 7]\}$$$, $$$\{[1, 3], [4, 6], [7, 7]\}$$$, $$$\{[1, 4], [5, 6], [7, 7]\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\{[1, 2], [3, 4], [5, 7]\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it.
You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \leq k \leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$$$, such that: $$$1 \leq l_i \leq r_i \leq n$$$ for all $$$1 \leq i \leq k$$$; For all $$$1 \leq j \leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \leq j \leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\,244\,353$$$.
Print two integers — the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\,244\,353$$$. Please note that you should only find the second value modulo $$$998\,244\,353$$$.
The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 200\,000$$$) — the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the given permutation.
standard output
standard input
Python 3
Python
1,300
train_008.jsonl
7ff3d6d65fac4c998cfc52939c007b38
256 megabytes
["3 2\n2 1 3", "5 5\n2 1 5 3 4", "7 3\n2 7 3 1 5 4 6"]
PASSED
[n, k]=list(map(int, input().split())) arr=list(map(int, input().split())) par_val=(k*(2*n-k+1))//2 prev, ways = 0, 1 while(arr[prev]<n-k+1): prev+=1 start=prev+1 for idx in range(start, n): if(arr[idx]>n-k): ways*=(idx-prev) prev=idx print(par_val, ways%998244353)
1584628500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["4\n3\n16"]
1f7fa6c56cb7be9404aa2ebaba89a44c
NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$. During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$; during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$; let's skip the third day; during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.
There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can: Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$. Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.
For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).
standard output
standard input
Python 3
Python
1,700
train_092.jsonl
026173628ee9e396dea69cf2d4020dad
256 megabytes
["3\n3\n1 2 4\n5\n4 4 3 5 5\n7\n2 5 4 8 3 7 4"]
PASSED
import sys from os import path def solve(word): # handel string input from codeforces hieghts=word.split(" ") trees = [int(i) for i in hieghts] Max = max(trees) Sum = 0 c1 = 0 #count number of even and odd days needed for all trees for i in trees: dist = Max - i if(dist%2 == 1): Sum += (dist//2) c1+=1 else: Sum += (dist//2) # if number of odd greater than number of even you just need twice odd number # but you don't need the last day because it's even if c1 > Sum+1: ans=c1+c1-1 #if the number of even greater than odd try to find min days that gives you #even growth by using both even and odd days elif Sum > c1: x= (Sum -c1)*2 #convert number of even days to number of days (multiply by 2) #for every 3 days we have 2 odds and one even as we have 2 evens if x%3==0: ans = x//3 *2 elif x%3==1: ans = x//3 *2+1 else: ans = x//3 *2 +2 ans+=c1*2 # if the number of even equal to number of odd- # -or smaller by one so you need thier sum else: ans = c1 +Sum # repeat the previos steps but with target length equal max+1 # because min time achived if length equal max or max+1 and get min of the two Sum = 0 c1 = 0 for i in trees: dist = Max - i +1 if(dist%2 == 1): Sum += (dist//2) c1+=1 else: Sum += (dist//2) if c1 > Sum+1: ans2=c1+c1-1 elif Sum > c1: x= (Sum -c1)*2 if x%3==0: ans2 = x//3 *2 elif x%3==1: ans2 = x//3 *2+1 else: ans2 = x//3 *2 +2 ans2+=c1*2 else: ans2 = c1 +Sum return min(ans , ans2) # common used function to handel codeforces input (online search) def get_int(): """ This function takes number of test cases """ return int(sys.stdin.readline()) def get_string(): """This function takes a string of each test case""" return sys.stdin.readline().strip() n = get_int() final_result = [] for i in range(n): num_trees=get_int() word = get_string() out=solve(word) final_result.append(out) for item in final_result: sys.stdout.write(str(item)) sys.stdout.write('\n')
1649514900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["? baa\n? aba\n? aab\n! xyz"]
e9079292d6bb328d8fe355101028cc6a
NoteIn the sample, the testcase described in the statement is used. The participant asks the first query with string baa, which is transformed to aab. The second query contains string aba, which is transformed to baa. The third query contains string aab, which is transformed to aba. The participant can deduce that the initial string $$$s$$$ was xyz.Note for hacking phase:To submit a test in hacking phase, you should provide it in the following format:The first line should contain the string $$$s$$$ you guess, consisting of $$$n \in [1, 10000]$$$ lowercase Latin letters.The second line should contain $$$k$$$ ($$$0 \le k \le n$$$) — the number of swap operations in the sequence.Then $$$k$$$ lines should follow, $$$i$$$-th of them should denote $$$i$$$-th operation with two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$).For example, the sample test would look like that:xyz21 22 3
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Then they applied a sequence of no more than $$$n$$$ (possibly zero) operations. $$$i$$$-th operation is denoted by two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), and means swapping two elements of the string with indices $$$a_i$$$ and $$$b_i$$$. All operations were done in the order they were placed in the sequence. For example, if $$$s$$$ is xyz and $$$2$$$ following operations are performed: $$$a_1 = 1, b_1 = 2$$$; $$$a_2 = 2, b_2 = 3$$$, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so $$$t$$$ is yzx.You are asked to restore the original string $$$s$$$. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is $$$n$$$, and get the resulting string after those operations.Can you guess the original string $$$s$$$ asking the testing system to run the sequence of swaps no more than $$$3$$$ times?The string $$$s$$$ and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution.
To give the answer, your program should print one line $$$!$$$ $$$s$$$ with a line break in the end. After that, it should flush the output and terminate gracefully.
Initially the testing system sends one string $$$t$$$, consisting of lowercase Latin letters ($$$1 \le |t| = n \le 10^4$$$).
standard output
standard input
Python 3
Python
2,200
train_038.jsonl
7917fd1c04b7b478590335b4e4eefa96
256 megabytes
["yzx\naab\nbaa\naba"]
PASSED
t = [tmp for tmp in input().strip()] n = len(t) az = 'abcdefghijklmnopqrstuvwxyz' s1 = [tmp for tmp in az] * (n // 26 + 1) s1 = s1[:n] s2 = [] for ch in az: s2 += [ch] * 26 s2 *= (n // 26 + 1) s2 = s2[:n] s3 = [] for ch in az: s3 += [ch] * 676 s3 *= (n // 676 + 1) s3 = s3[:n] print("? ", *s1, sep='', flush=True) t1 = input() print("? ", *s2, sep='', flush=True) t2 = input() print("? ", *s3, sep='', flush=True) t3 = input() tc = [] orda = ord('a') for i in range(n): m1 = ord(t1[i]) - orda m26 = ord(t2[i]) - orda m676 = ord(t3[i]) - orda tc.append(m676 * 676 + m26 * 26 + m1) s = ['a'] * n for pos2, pos1 in enumerate(tc): s[pos1] = t[pos2] print("! ", *s, sep='', flush=True)
1550504400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"]
753113fa5130a67423f2e205c97f8017
null
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.
Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.
The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.
standard output
standard input
Python 3
Python
900
train_006.jsonl
61868140103ea29a33149967d74b93f5
256 megabytes
["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"]
PASSED
d = { 'rat':[], 'child':[], 'man':[], 'captain':[] } i = int(input()) while i: s = input() data = s.split() if data[1] == 'child' or data[1] == 'woman': d['child'].append(data[0]) else: d[data[1]].append(data[0]) i = i -1 for p in d['rat']: print(p) for p in d['child']: print(p) for p in d['man']: print(p) for p in d['captain']: print(p)
1298908800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["2\n1\nMORTAL\n4"]
da18ca9f125d1524e7c0a2637b1fa3df
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
standard output
standard input
PyPy 2
Python
1,800
train_003.jsonl
083ed4da4425c06ce06878a75a6d9692
256 megabytes
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
PASSED
mod=10**9+7 #import resource #resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY]) #import threading #threading.stack_size(2**27) #import sys #sys.setrecursionlimit(10**6) #fact=[1] #for i in range(1,1000001): # fact.append((fact[-1]*i)%mod) #ifact=[0]*1000001 #ifact[1000000]=pow(fact[1000000],mod-2,mod) #for i in range(1000000,0,-1): # ifact[i-1]=(i*ifact[i])%mod from sys import stdin, stdout import bisect from bisect import bisect_left as bl #c++ lowerbound bl(array,element) from bisect import bisect_right as br #c++ upperbound import itertools import collections import math import heapq #from random import randint as rn #from Queue import Queue as Q def modinv(n,p): return pow(n,p-2,p) def ncr(n,r,p): #for using this uncomment the lines calculating fact and ifact t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p return t def ain(): #takes array as input return list(map(int,sin().split())) def sin(): return input().strip() def GCD(x,y): while(y): x, y = y, x % y return x """*******************************************************""" def main(): for _ in range(int(input())): n,m=ain() b=[] for i in range(n): b.append(sin()) t=0 for i in range(n): for j in range(m): if(b[i][j]=="P"): t=1 break if(t==1): break if(t==0): print 0 continue k1=0 k2=0 for i in range(m): if(b[0][i]=="P"): k1=1 if(b[n-1][i]=="P"): k2=1 if(k1==0 or k2==0): print 1 continue k1=0 k2=0 for i in range(n): if(b[i][0]=="P"): k1=1 if(b[i][m-1]=="P"): k2=1 if(k1==0 or k2==0): print 1 continue t=0 for i in range(n): k=0 for j in range(m): if(b[i][j]=="P"): k=1 break if(k==0): t=1 break if(t==1): print 2 continue for j in range(m): k=0 for i in range(n): if(b[i][j]=="P"): k=1 break if(k==0): t=1 break if(t==1): print 2 continue if(b[0][0]=="A" or b[0][m-1]=="A" or b[n-1][0]=="A" or b[n-1][m-1]=="A"): print 2 continue t=0 for i in range(m): if(b[0][i]=="A" or b[n-1][i]=="A"): t=1 break for i in range(n): if(b[i][0]=="A" or b[i][m-1]=="A"): t=1 break if(t==1): print 3 continue t=0 for i in range(n): for j in range(m): if(b[i][j]=="A"): t=1 break if(t==1): break if(t==1): print 4 else: print "MORTAL" ######## Python 2 and 3 footer by Pajenegod and c1729 py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') if __name__ == '__main__': main() #threading.Thread(target=main).start()
1576386300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3", "4", "25"]
6fbcc92541705a63666701238778a04a
NoteIn first sample there are only three suitable pairs of indexes — (1, 2), (2, 3), (3, 4).In second sample there are four suitable pairs of indexes(1, 1), (2, 2), (3, 3), (4, 4).In third sample every pair (i, j) is suitable, so the answer is 5 * 5 = 25.
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≤ aj and there are exactly k integers y such that ai ≤ y ≤ aj and y is divisible by x.In this problem it is meant that pair (i, j) is equal to (j, i) only if i is equal to j. For example pair (1, 2) is not the same as (2, 1).
Print one integer — the answer to the problem.
The first line contains 3 integers n, x, k (1 ≤ n ≤ 105, 1 ≤ x ≤ 109, 0 ≤ k ≤ 109), where n is the size of the array a and x and k are numbers from the statement. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.
standard output
standard input
Python 3
Python
1,700
train_035.jsonl
4fa449ec15c9300a4be42f932d13b2d0
256 megabytes
["4 2 1\n1 3 5 7", "4 2 0\n5 3 1 7", "5 3 1\n3 3 3 3 3"]
PASSED
import math import bisect n, x, k = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = 0 for num in a: l = math.ceil(num/x)*x + (k-1)*x r = l + x - 1 l = num if l < num else l # print(l, r, bisect.bisect_left(a, l), bisect.bisect_right(a, r), bisect.bisect_right(a, r) - bisect.bisect_left(a, l)) ans += bisect.bisect_right(a, r) - bisect.bisect_left(a, l) print(ans) ''' 7 3 2 1 3 5 9 11 16 25 ''' ''' 4 2 0 5 3 1 7 '''
1511712300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["110", "010"]
4aaeff1b38d501daf9a877667e075d49
NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \leq r$$$.
Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise.
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive.
standard output
standard input
PyPy 3
Python
2,000
train_002.jsonl
21b7c60e1c22ab828099133b35ea728c
256 megabytes
["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"]
PASSED
import sys class segmentTree: def __init__(self, n): self.n = n self.seg = [self.n + 1] * (self.n << 1) def update(self, p, value): p += self.n self.seg[p] = value while p > 1: p >>= 1 self.seg[p] = min(self.seg[p * 2], self.seg[p * 2 + 1]) def query(self, l, r): res = self.n l += self.n r += self.n while l < r: if l & 1: res = min(res, self.seg[l]) l += 1 if r & 1: res = min(res, self.seg[r - 1]) r -= 1 l >>= 1 r >>= 1 return res inp = [int(x) for x in sys.stdin.read().split()] n, m, q = inp[0], inp[1], inp[2] p = [inp[idx] for idx in range(3, n + 3)] index_arr = [0] * (n + 1) for i in range(n): index_arr[p[i]] = i a = [inp[idx] for idx in range(n + 3, n + 3 + m)] leftmost_pos = [m] * (n + 1) next = [-1] * m for i in range(m - 1, -1, -1): index = index_arr[a[i]] right_index = 0 if index == n - 1 else index + 1 right = p[right_index] next[i] = leftmost_pos[right] leftmost_pos[a[i]] = i log = 0 while (1 << log) <= n: log += 1 log += 1 dp = [[m for _ in range(m + 1)] for _ in range(log)] for i in range(m): dp[0][i] = next[i] for j in range(1, log): for i in range(m): dp[j][i] = dp[j - 1][dp[j - 1][i]] tree = segmentTree(m) for i in range(m): p = i len = n - 1 for j in range(log - 1, -1, -1): if (1 << j) <= len: p = dp[j][p] len -= (1 << j) tree.update(i, p) inp_idx = n + m + 3 ans = [] for i in range(q): l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1 inp_idx += 2 if tree.query(l, r + 1) <= r: ans.append('1') else: ans.append('0') print(''.join(ans))
1553965800
[ "math", "trees" ]
[ 0, 0, 0, 1, 0, 0, 0, 1 ]
3 seconds
["16\n0 1\n0 1\n0 -1\n0 -1", "312\n0 6\n5 -3\n-5 -3"]
345f923c42c5b5f3975a6f8c61e6030f
null
Roland loves growing flowers. He has recently grown a beautiful rose at point (0, 0) of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it. To protect the rose, Roland wants to build n watch towers. Let's assume that a tower is a point on the plane at the distance of at most r from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point (0, 0).Help Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points.
In the first line print an integer — the maximum possible sum of squared distances. In the i-th of the following n lines print two integers, xi, yi — the coordinates of the i-th tower. Each tower must be inside or on the border of the circle with radius r. Note that there may be several towers located at the same point of the plane, also some towers can be located at point (0, 0). If there are multiple valid optimal arrangements, choose any of them.
The first line contains two integers, n and r (2 ≤ n ≤ 8; 1 ≤ r ≤ 30).
standard output
standard input
Python 2
Python
2,700
train_067.jsonl
61e915a86cbef749b6d46b9401b85c28
256 megabytes
["4 1", "3 6"]
PASSED
""" #include <bits/stdc++.h> #ifdef DEMETRIO #define deb(...) fprintf(stderr,__VA_ARGS__) #define deb1(x) cerr << #x << " = " << x << endl #else #define deb(...) 0 #define deb1(x) 0 #endif #define pb push_back #define mp make_pair #define fst first #define snd second #define fore(i,a,b) for(int i=a,ThxDem=b;i<ThxDem;++i) #define SZ(x) ((int)(x).size()) #define mset(a,v) memset(a,v,sizeof(a)) #define mcopy(a,b) memcpy(a,b,sizeof(a)) using namespace std; typedef long long ll; int dp[9][512][512]; int cx[9][512][512],cy[9][512][512],rr; bool vis[9][512][512]; #define OFF 250 int f(int n, int xx, int yy){ if(vis[n][xx][yy])return dp[n][xx][yy]; vis[n][xx][yy]=true; int& r=dp[n][xx][yy]; if(n==0)return r=(xx==OFF&&yy==OFF)?0:-(1<<30); r=-(1<<30); fore(x,-rr,rr+1)fore(y,-rr,rr+1){ if(x*x+y*y>rr*rr)continue; if(xx+x<0||xx+x>=512)continue; if(yy+y<0||yy+y>=512)continue; int a=x*x+y*y+f(n-1,xx+x,yy+y); if(a>r){r=a;cx[n][xx][yy]=x;cy[n][xx][yy]=y;} } return r; } int main(){ fore(r,1,31){ rr=r; mset(vis,false); fore(n,2,9){ printf("r[%d][%d]='''",n,r); int r=-(1<<30),xx,yy; fore(i,0,512)fore(j,0,512)if(f(n,i,j)>=0){ int a=n*f(n,i,j)-(i-OFF)*(i-OFF)-(j-OFF)*(j-OFF); if(a>r)r=a,xx=i,yy=j; } printf("%d\n",r); int k=n; while(k>0){ printf("%d %d\n",cx[k][xx][yy],cy[k][xx][yy]); int nx=xx+cx[k][xx][yy],ny=yy+cy[k][xx][yy]; xx=nx;yy=ny; k--; } puts("'''"); } } return 0; } """ r=[[0]*31 for _ in range(9)] r[2][1]='''4 -1 0 1 0 ''' r[3][1]='''8 -1 0 1 0 1 0 ''' r[4][1]='''16 -1 0 -1 0 1 0 1 0 ''' r[5][1]='''24 -1 0 -1 0 1 0 1 0 1 0 ''' r[6][1]='''36 -1 0 -1 0 -1 0 1 0 1 0 1 0 ''' r[7][1]='''48 -1 0 -1 0 -1 0 1 0 1 0 1 0 1 0 ''' r[8][1]='''64 -1 0 -1 0 -1 0 -1 0 1 0 1 0 1 0 1 0 ''' r[2][2]='''16 -2 0 2 0 ''' r[3][2]='''32 -2 0 2 0 2 0 ''' r[4][2]='''64 -2 0 -2 0 2 0 2 0 ''' r[5][2]='''96 -2 0 -2 0 2 0 2 0 2 0 ''' r[6][2]='''144 -2 0 -2 0 -2 0 2 0 2 0 2 0 ''' r[7][2]='''192 -2 0 -2 0 -2 0 2 0 2 0 2 0 2 0 ''' r[8][2]='''256 -2 0 -2 0 -2 0 -2 0 2 0 2 0 2 0 2 0 ''' r[2][3]='''36 -3 0 3 0 ''' r[3][3]='''76 -2 -2 0 3 3 0 ''' r[4][3]='''144 -3 0 -3 0 3 0 3 0 ''' r[5][3]='''218 -3 0 -2 -2 0 3 3 0 3 0 ''' r[6][3]='''324 -3 0 -3 0 -3 0 3 0 3 0 3 0 ''' r[7][3]='''432 -3 0 -3 0 -3 0 3 0 3 0 3 0 3 0 ''' r[8][3]='''576 -3 0 -3 0 -3 0 -3 0 3 0 3 0 3 0 3 0 ''' r[2][4]='''64 -4 0 4 0 ''' r[3][4]='''130 -2 -3 0 4 4 0 ''' r[4][4]='''256 -4 0 -4 0 4 0 4 0 ''' r[5][4]='''384 -4 0 -4 0 4 0 4 0 4 0 ''' r[6][4]='''576 -4 0 -4 0 -4 0 4 0 4 0 4 0 ''' r[7][4]='''768 -4 0 -4 0 -4 0 4 0 4 0 4 0 4 0 ''' r[8][4]='''1024 -4 0 -4 0 -4 0 -4 0 4 0 4 0 4 0 4 0 ''' r[2][5]='''100 -5 0 5 0 ''' r[3][5]='''224 -5 0 3 -4 3 4 ''' r[4][5]='''400 -5 0 -5 0 5 0 5 0 ''' r[5][5]='''624 -5 0 -5 0 3 -4 3 4 5 0 ''' r[6][5]='''900 -5 0 -5 0 -5 0 5 0 5 0 5 0 ''' r[7][5]='''1224 -5 0 -5 0 -5 0 3 -4 3 4 5 0 5 0 ''' r[8][5]='''1600 -5 0 -5 0 -5 0 -5 0 5 0 5 0 5 0 5 0 ''' r[2][6]='''144 -6 0 6 0 ''' r[3][6]='''312 -6 0 3 -5 3 5 ''' r[4][6]='''576 -6 0 -6 0 6 0 6 0 ''' r[5][6]='''880 -6 0 -3 -5 0 6 6 0 6 0 ''' r[6][6]='''1296 -6 0 -6 0 -6 0 6 0 6 0 6 0 ''' r[7][6]='''1740 -6 0 -6 0 -3 -5 0 6 6 0 6 0 6 0 ''' r[8][6]='''2304 -6 0 -6 0 -6 0 -6 0 6 0 6 0 6 0 6 0 ''' r[2][7]='''196 -7 0 7 0 ''' r[3][7]='''416 -3 -6 -3 6 7 0 ''' r[4][7]='''784 -7 0 -7 0 7 0 7 0 ''' r[5][7]='''1188 -7 0 -3 -6 0 7 7 0 7 0 ''' r[6][7]='''1764 -7 0 -7 0 -7 0 7 0 7 0 7 0 ''' r[7][7]='''2356 -7 0 -7 0 -3 -6 0 7 7 0 7 0 7 0 ''' r[8][7]='''3136 -7 0 -7 0 -7 0 -7 0 7 0 7 0 7 0 7 0 ''' r[2][8]='''256 -8 0 8 0 ''' r[3][8]='''554 -5 -6 0 8 8 0 ''' r[4][8]='''1024 -8 0 -8 0 8 0 8 0 ''' r[5][8]='''1572 -8 0 -5 -6 0 8 8 0 8 0 ''' r[6][8]='''2304 -8 0 -8 0 -8 0 8 0 8 0 8 0 ''' r[7][8]='''3102 -8 0 -8 0 -5 -6 0 8 8 0 8 0 8 0 ''' r[8][8]='''4096 -8 0 -8 0 -8 0 -8 0 8 0 8 0 8 0 8 0 ''' r[2][9]='''324 -9 0 9 0 ''' r[3][9]='''722 -4 -8 -4 8 9 0 ''' r[4][9]='''1296 -9 0 -9 0 9 0 9 0 ''' r[5][9]='''2014 -9 0 -4 -8 -4 8 9 0 9 0 ''' r[6][9]='''2916 -9 0 -9 0 -9 0 9 0 9 0 9 0 ''' r[7][9]='''3954 -9 0 -9 0 -4 -8 -4 8 9 0 9 0 9 0 ''' r[8][9]='''5184 -9 0 -9 0 -9 0 -9 0 9 0 9 0 9 0 9 0 ''' r[2][10]='''400 -10 0 10 0 ''' r[3][10]='''896 -10 0 6 -8 6 8 ''' r[4][10]='''1600 -10 0 -10 0 10 0 10 0 ''' r[5][10]='''2496 -10 0 -10 0 6 -8 6 8 10 0 ''' r[6][10]='''3600 -10 0 -10 0 -10 0 10 0 10 0 10 0 ''' r[7][10]='''4896 -10 0 -10 0 -10 0 6 -8 6 8 10 0 10 0 ''' r[8][10]='''6400 -10 0 -10 0 -10 0 -10 0 10 0 10 0 10 0 10 0 ''' r[2][11]='''484 -11 0 11 0 ''' r[3][11]='''1064 -11 0 6 -9 6 9 ''' r[4][11]='''1936 -11 0 -11 0 11 0 11 0 ''' r[5][11]='''2984 -11 0 -11 0 6 -9 6 9 11 0 ''' r[6][11]='''4356 -11 0 -11 0 -11 0 11 0 11 0 11 0 ''' r[7][11]='''5872 -11 0 -11 0 -6 -9 0 11 11 0 11 0 11 0 ''' r[8][11]='''7744 -11 0 -11 0 -11 0 -11 0 11 0 11 0 11 0 11 0 ''' r[2][12]='''576 -12 0 12 0 ''' r[3][12]='''1248 -12 0 6 -10 6 10 ''' r[4][12]='''2304 -12 0 -12 0 12 0 12 0 ''' r[5][12]='''3520 -12 0 -6 -10 0 12 12 0 12 0 ''' r[6][12]='''5184 -12 0 -12 0 -12 0 12 0 12 0 12 0 ''' r[7][12]='''6960 -12 0 -12 0 -6 -10 0 12 12 0 12 0 12 0 ''' r[8][12]='''9216 -12 0 -12 0 -12 0 -12 0 12 0 12 0 12 0 12 0 ''' r[2][13]='''676 -13 0 13 0 ''' r[3][13]='''1512 -5 -12 -5 12 13 0 ''' r[4][13]='''2704 -13 0 -13 0 13 0 13 0 ''' r[5][13]='''4224 -13 0 -5 -12 -5 12 12 -5 12 5 ''' r[6][13]='''6084 -13 0 -13 0 -13 0 13 0 13 0 13 0 ''' r[7][13]='''8280 -13 0 -13 0 -5 -12 -5 12 12 -5 12 5 13 0 ''' r[8][13]='''10816 -13 0 -13 0 -13 0 -13 0 13 0 13 0 13 0 13 0 ''' r[2][14]='''784 -14 0 14 0 ''' r[3][14]='''1746 -14 0 7 -12 7 12 ''' r[4][14]='''3136 -14 0 -14 0 14 0 14 0 ''' r[5][14]='''4870 -14 0 -7 -12 -5 13 14 0 14 0 ''' r[6][14]='''7056 -14 0 -14 0 -14 0 14 0 14 0 14 0 ''' r[7][14]='''9564 -14 0 -14 0 -7 -12 -5 13 14 0 14 0 14 0 ''' r[8][14]='''12544 -14 0 -14 0 -14 0 -14 0 14 0 14 0 14 0 14 0 ''' r[2][15]='''900 -15 0 15 0 ''' r[3][15]='''2016 -15 0 9 -12 9 12 ''' r[4][15]='''3600 -15 0 -15 0 15 0 15 0 ''' r[5][15]='''5616 -15 0 -15 0 9 -12 9 12 15 0 ''' r[6][15]='''8100 -15 0 -15 0 -15 0 15 0 15 0 15 0 ''' r[7][15]='''11016 -15 0 -15 0 -15 0 9 -12 9 12 15 0 15 0 ''' r[8][15]='''14400 -15 0 -15 0 -15 0 -15 0 15 0 15 0 15 0 15 0 ''' r[2][16]='''1024 -16 0 16 0 ''' r[3][16]='''2264 -16 0 9 -13 9 13 ''' r[4][16]='''4096 -16 0 -16 0 16 0 16 0 ''' r[5][16]='''6336 -16 0 -16 0 9 -13 9 13 16 0 ''' r[6][16]='''9216 -16 0 -16 0 -16 0 16 0 16 0 16 0 ''' r[7][16]='''12456 -16 0 -16 0 -16 0 9 -13 9 13 16 0 16 0 ''' r[8][16]='''16384 -16 0 -16 0 -16 0 -16 0 16 0 16 0 16 0 16 0 ''' r[2][17]='''1156 -17 0 17 0 ''' r[3][17]='''2600 -8 -15 -8 15 17 0 ''' r[4][17]='''4624 -17 0 -17 0 17 0 17 0 ''' r[5][17]='''7224 -17 0 -8 -15 -8 15 17 0 17 0 ''' r[6][17]='''10404 -17 0 -17 0 -17 0 17 0 17 0 17 0 ''' r[7][17]='''14160 -17 0 -17 0 -8 -15 -8 15 17 0 17 0 17 0 ''' r[8][17]='''18496 -17 0 -17 0 -17 0 -17 0 17 0 17 0 17 0 17 0 ''' r[2][18]='''1296 -18 0 18 0 ''' r[3][18]='''2888 -8 -16 -8 16 18 0 ''' r[4][18]='''5184 -18 0 -18 0 18 0 18 0 ''' r[5][18]='''8056 -18 0 -8 -16 -8 16 18 0 18 0 ''' r[6][18]='''11664 -18 0 -18 0 -18 0 18 0 18 0 18 0 ''' r[7][18]='''15816 -18 0 -18 0 -8 -16 -8 16 18 0 18 0 18 0 ''' r[8][18]='''20736 -18 0 -18 0 -18 0 -18 0 18 0 18 0 18 0 18 0 ''' r[2][19]='''1444 -19 0 19 0 ''' r[3][19]='''3218 -10 -16 -6 18 19 0 ''' r[4][19]='''5776 -19 0 -19 0 19 0 19 0 ''' r[5][19]='''9008 -18 -6 -18 -6 0 19 18 -6 19 0 ''' r[6][19]='''12996 -19 0 -19 0 -19 0 19 0 19 0 19 0 ''' r[7][19]='''17666 -19 0 -18 -6 -18 -6 0 19 18 -6 19 0 19 0 ''' r[8][19]='''23104 -19 0 -19 0 -19 0 -19 0 19 0 19 0 19 0 19 0 ''' r[2][20]='''1600 -20 0 20 0 ''' r[3][20]='''3584 -20 0 12 -16 12 16 ''' r[4][20]='''6400 -20 0 -20 0 20 0 20 0 ''' r[5][20]='''9984 -20 0 -20 0 12 -16 12 16 20 0 ''' r[6][20]='''14400 -20 0 -20 0 -20 0 20 0 20 0 20 0 ''' r[7][20]='''19584 -20 0 -20 0 -20 0 12 -16 12 16 20 0 20 0 ''' r[8][20]='''25600 -20 0 -20 0 -20 0 -20 0 20 0 20 0 20 0 20 0 ''' r[2][21]='''1764 -21 0 21 0 ''' r[3][21]='''3912 -17 -12 0 21 20 -6 ''' r[4][21]='''7056 -21 0 -21 0 21 0 21 0 ''' r[5][21]='''10942 -21 0 -17 -12 0 21 20 -6 21 0 ''' r[6][21]='''15876 -21 0 -21 0 -21 0 21 0 21 0 21 0 ''' r[7][21]='''21500 -21 0 -21 0 -17 -12 0 21 20 -6 21 0 21 0 ''' r[8][21]='''28224 -21 0 -21 0 -21 0 -21 0 21 0 21 0 21 0 21 0 ''' r[2][22]='''1936 -22 0 22 0 ''' r[3][22]='''4344 -22 0 11 -19 11 19 ''' r[4][22]='''7744 -22 0 -22 0 22 0 22 0 ''' r[5][22]='''12080 -22 0 -22 0 11 -19 11 19 22 0 ''' r[6][22]='''17424 -22 0 -22 0 -22 0 22 0 22 0 22 0 ''' r[7][22]='''23688 -22 0 -22 0 -22 0 11 -19 11 19 22 0 22 0 ''' r[8][22]='''30976 -22 0 -22 0 -22 0 -22 0 22 0 22 0 22 0 22 0 ''' r[2][23]='''2116 -23 0 23 0 ''' r[3][23]='''4712 -11 -20 -11 20 23 0 ''' r[4][23]='''8464 -23 0 -23 0 23 0 23 0 ''' r[5][23]='''13144 -23 0 -11 -20 -11 20 23 0 23 0 ''' r[6][23]='''19044 -23 0 -23 0 -23 0 23 0 23 0 23 0 ''' r[7][23]='''25808 -23 0 -23 0 -11 -20 -11 20 23 0 23 0 23 0 ''' r[8][23]='''33856 -23 0 -23 0 -23 0 -23 0 23 0 23 0 23 0 23 0 ''' r[2][24]='''2304 -24 0 24 0 ''' r[3][24]='''5138 -24 0 13 -20 13 20 ''' r[4][24]='''9216 -24 0 -24 0 24 0 24 0 ''' r[5][24]='''14326 -24 0 -24 0 13 -20 13 20 24 0 ''' r[6][24]='''20736 -24 0 -24 0 -24 0 24 0 24 0 24 0 ''' r[7][24]='''28122 -24 0 -24 0 -24 0 13 -20 13 20 24 0 24 0 ''' r[8][24]='''36864 -24 0 -24 0 -24 0 -24 0 24 0 24 0 24 0 24 0 ''' r[2][25]='''2500 -25 0 25 0 ''' r[3][25]='''5612 -24 -7 7 24 20 -15 ''' r[4][25]='''10000 -25 0 -25 0 25 0 25 0 ''' r[5][25]='''15624 -25 0 -7 -24 -7 24 20 -15 20 15 ''' r[6][25]='''22500 -25 0 -25 0 -25 0 25 0 25 0 25 0 ''' r[7][25]='''30624 -25 0 -25 0 -7 -24 -7 24 20 -15 20 15 25 0 ''' r[8][25]='''40000 -25 0 -25 0 -25 0 -25 0 25 0 25 0 25 0 25 0 ''' r[2][26]='''2704 -26 0 26 0 ''' r[3][26]='''6062 -12 -23 -12 23 26 0 ''' r[4][26]='''10816 -26 0 -26 0 26 0 26 0 ''' r[5][26]='''16896 -26 0 -10 -24 -10 24 24 -10 24 10 ''' r[6][26]='''24336 -26 0 -26 0 -26 0 26 0 26 0 26 0 ''' r[7][26]='''33120 -26 0 -26 0 -10 -24 -10 24 24 -10 24 10 26 0 ''' r[8][26]='''43264 -26 0 -26 0 -26 0 -26 0 26 0 26 0 26 0 26 0 ''' r[2][27]='''2916 -27 0 27 0 ''' r[3][27]='''6536 -27 0 14 -23 14 23 ''' r[4][27]='''11664 -27 0 -27 0 27 0 27 0 ''' r[5][27]='''18184 -27 0 -27 0 14 -23 14 23 27 0 ''' r[6][27]='''26244 -27 0 -27 0 -27 0 27 0 27 0 27 0 ''' r[7][27]='''35664 -27 0 -27 0 -27 0 14 -23 14 23 27 0 27 0 ''' r[8][27]='''46656 -27 0 -27 0 -27 0 -27 0 27 0 27 0 27 0 27 0 ''' r[2][28]='''3136 -28 0 28 0 ''' r[3][28]='''6984 -28 0 14 -24 14 24 ''' r[4][28]='''12544 -28 0 -28 0 28 0 28 0 ''' r[5][28]='''19488 -28 0 -22 -17 0 28 26 -10 28 0 ''' r[6][28]='''28224 -28 0 -28 0 -28 0 28 0 28 0 28 0 ''' r[7][28]='''38266 -28 0 -28 0 -22 -17 0 28 26 -10 28 0 28 0 ''' r[8][28]='''50176 -28 0 -28 0 -28 0 -28 0 28 0 28 0 28 0 28 0 ''' r[2][29]='''3364 -29 0 29 0 ''' r[3][29]='''7520 -20 -21 -7 28 28 -7 ''' r[4][29]='''13456 -29 0 -29 0 29 0 29 0 ''' r[5][29]='''20968 -29 0 -7 -28 0 29 20 -21 20 21 ''' r[6][29]='''30276 -29 0 -29 0 -29 0 29 0 29 0 29 0 ''' r[7][29]='''41200 -21 -20 -21 -20 -21 20 -21 20 29 0 29 0 29 0 ''' r[8][29]='''53824 -29 0 -29 0 -29 0 -29 0 29 0 29 0 29 0 29 0 ''' r[2][30]='''3600 -30 0 30 0 ''' r[3][30]='''8084 -24 18 0 -30 27 13 ''' r[4][30]='''14400 -30 0 -30 0 30 0 30 0 ''' r[5][30]='''22480 -30 0 -24 18 0 -30 27 13 30 0 ''' r[6][30]='''32400 -30 0 -30 0 -30 0 30 0 30 0 30 0 ''' r[7][30]='''44076 -30 0 -30 0 -30 0 18 24 24 -18 24 -18 27 13 ''' r[8][30]='''57600 -30 0 -30 0 -30 0 -30 0 30 0 30 0 30 0 30 0 ''' a,b=map(int,raw_input().split()) print r[a][b],
1408548600
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Alice\nDraw"]
6cffd0fa1146b250a2608d53f3f738fa
NoteOne of the possible games Alice and Bob can play in the first testcase: Alice picks the first letter in $$$s$$$: $$$s=$$$"orces", $$$a=$$$"f", $$$b=$$$""; Bob picks the last letter in $$$s$$$: $$$s=$$$"orce", $$$a=$$$"f", $$$b=$$$"s"; Alice picks the last letter in $$$s$$$: $$$s=$$$"orc", $$$a=$$$"ef", $$$b=$$$"s"; Bob picks the first letter in $$$s$$$: $$$s=$$$"rc", $$$a=$$$"ef", $$$b=$$$"os"; Alice picks the last letter in $$$s$$$: $$$s=$$$"r", $$$a=$$$"cef", $$$b=$$$"os"; Bob picks the remaining letter in $$$s$$$: $$$s=$$$"", $$$a=$$$"cef", $$$b=$$$"ros". Alice wins because "cef" &lt; "ros". Neither of the players follows any strategy in this particular example game, so it doesn't show that Alice wins if both play optimally.
Alice and Bob are playing a game. Initially, they are given a non-empty string $$$s$$$, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty.Alice starts, then they alternate moves. In one move, a player takes either the first or the last letter of the string $$$s$$$, removes it from $$$s$$$ and prepends (adds to the beginning) it to their own string.The game ends when the string $$$s$$$ becomes empty. The winner is the player with a lexicographically smaller string. If the players' strings are equal, then it's a draw.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if there exists such position $$$i$$$ that $$$a_j = b_j$$$ for all $$$j &lt; i$$$ and $$$a_i &lt; b_i$$$.What is the result of the game if both players play optimally (e. g. both players try to win; if they can't, then try to draw)?
For each testcase, print the result of the game if both players play optimally. If Alice wins, print "Alice". If Bob wins, print "Bob". If it's a draw, print "Draw".
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each testcase consists of a single line — a non-empty string $$$s$$$, consisting of lowercase Latin letters. The length of the string $$$s$$$ is even. The total length of the strings over all testcases doesn't exceed $$$2000$$$.
standard output
standard input
Python 3
Python
1,800
train_098.jsonl
6e37abf2becbf1e73f8cb2094859efc9
512 megabytes
["2\n\nforces\n\nabba"]
PASSED
from functools import lru_cache t = int(input()) for _ in range(t): s = input() l = len(s) dp = [[True for i in range(l + 1)] for j in range(l + 1)] for k in range(2, l + 1, 2): for i in range(l + 1 - k): j = i + k dp[i][j] = (s[i] == s[j - 1] and dp[i + 1][j - 1]) or ((s[i] == s[i + 1] and dp[i + 2][j]) & (s[j - 1] == s[j - 2] and dp[i][j - 2])) if dp[0][-1]: print("Draw") else: print("Alice")
1662647700
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["-1\n57\n239\n6789"]
43996d7e052aa628a46d03086f9c5436
NoteIn the first test case, there are no possible solutions for $$$s$$$ consisting of one digit, because any such solution is divisible by itself.For the second test case, the possible solutions are: $$$23$$$, $$$27$$$, $$$29$$$, $$$34$$$, $$$37$$$, $$$38$$$, $$$43$$$, $$$46$$$, $$$47$$$, $$$49$$$, $$$53$$$, $$$54$$$, $$$56$$$, $$$57$$$, $$$58$$$, $$$59$$$, $$$67$$$, $$$68$$$, $$$69$$$, $$$73$$$, $$$74$$$, $$$76$$$, $$$78$$$, $$$79$$$, $$$83$$$, $$$86$$$, $$$87$$$, $$$89$$$, $$$94$$$, $$$97$$$, and $$$98$$$.For the third test case, one possible solution is $$$239$$$ because $$$239$$$ is not divisible by $$$2$$$, $$$3$$$ or $$$9$$$ and has three digits (none of which equals zero).
You are given a integer $$$n$$$ ($$$n &gt; 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$: $$$s &gt; 0$$$, $$$s$$$ consists of $$$n$$$ digits, no digit in $$$s$$$ equals $$$0$$$, $$$s$$$ is not divisible by any of it's digits.
For each test case, print an integer $$$s$$$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $$$s$$$, print any solution.
The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case contains one positive integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,000
train_028.jsonl
b94cdc8499c8864743e9d23a8468a2ab
256 megabytes
["4\n1\n2\n3\n4"]
PASSED
# def check(n): # strng = str(n) # if not("0" in strng or "1" in strng): # if n%2 != 0 and n%3 != 0 and n%5 !=0 and n%7 != 0 : # return True # return False def solve(n): if n<2: return -1 first = "3"*(n-1)+"7" if int(first)%7 != 0: return first else : return first[:-2]+"77" def main(): t= int(input().strip()) while t: n = int(input().strip()) print(solve(n)) t-=1 if __name__ == '__main__': main()
1584628500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2 2", "3 3 3"]
bb38c3a6a0e8b0458a4f5fd27dd3f5d8
NoteIn the first example, the distance between vertex $$$1$$$ and $$$2$$$ equals to $$$2$$$ because one can walk through the edge of weight $$$2$$$ connecting them. So the distance to the farthest node for both $$$1$$$ and $$$2$$$ equals to $$$2$$$.In the second example, one can find that distance between $$$1$$$ and $$$2$$$, distance between $$$1$$$ and $$$3$$$ are both $$$3$$$ and the distance between $$$2$$$ and $$$3$$$ is $$$2$$$.The graph may have multiple edges between and self-loops, as in the first example.
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.You are given a connected undirected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. There are $$$k$$$ special vertices: $$$x_1, x_2, \ldots, x_k$$$.Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.
The first and only line should contain $$$k$$$ integers. The $$$i$$$-th integer is the distance between $$$x_i$$$ and the farthest special vertex from it.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 10^5$$$, $$$n-1 \leq m \leq 10^5$$$) — the number of vertices, the number of edges and the number of special vertices. The second line contains $$$k$$$ distinct integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$). Each of the following $$$m$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1 \leq u,v \leq n, 1 \leq w \leq 10^9$$$), denoting there is an edge between $$$u$$$ and $$$v$$$ of weight $$$w$$$. The given graph is undirected, so an edge $$$(u, v)$$$ can be used in the both directions. The graph may have multiple edges and self-loops. It is guaranteed, that the graph is connected.
standard output
standard input
Python 3
Python
1,800
train_013.jsonl
c99af22108def166e8e22ba096d22b4c
256 megabytes
["2 3 2\n2 1\n1 2 3\n1 2 2\n2 2 1", "4 5 3\n1 2 3\n1 2 5\n4 2 1\n2 3 2\n1 4 4\n1 3 3"]
PASSED
n, m, k = map(int, input().split()) a = list(map(int, input().split())) g = [] f = list(range(n+1)) s = [0] * (n+1) def search(n): while f[n] != n: f[n] = f[f[n]] n = f[n] return n def can_merge(u, v): u = search(u) v = search(v) f[u] = v if u == v: return False r = s[u] > 0 and s[v] > 0 s[v] += s[u] return r for _ in range(m): u,v,w = map(int, input().split()) g.append((u,v,w)) g.sort(key = lambda tup: tup[2]) for i in a: s[i] += 1 ans = 0 for t in g: if can_merge(t[0],t[1]): ans = t[2] print(' '.join([str(ans)] * k))
1544970900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["5"]
a8c5b1377035f0a772510b5b80588d47
NoteIn the sample case, the suitable pairs are: $$$a_1 \cdot a_4 = 8 = 2^3$$$; $$$a_1 \cdot a_6 = 1 = 1^3$$$; $$$a_2 \cdot a_3 = 27 = 3^3$$$; $$$a_3 \cdot a_5 = 216 = 6^3$$$; $$$a_4 \cdot a_6 = 8 = 2^3$$$.
You are given $$$n$$$ positive integers $$$a_1, \ldots, a_n$$$, and an integer $$$k \geq 2$$$. Count the number of pairs $$$i, j$$$ such that $$$1 \leq i &lt; j \leq n$$$, and there exists an integer $$$x$$$ such that $$$a_i \cdot a_j = x^k$$$.
Print a single integer — the number of suitable pairs.
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 10^5$$$, $$$2 \leq k \leq 100$$$). The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$).
standard output
standard input
Python 2
Python
1,800
train_018.jsonl
0c450c4102572848fa34d6f5274ed09d
512 megabytes
["6 3\n1 3 9 8 24 1"]
PASSED
from sys import stdin from itertools import repeat from collections import defaultdict def main(): n, k = map(int, stdin.readline().split()) a = map(int, stdin.readline().split(), repeat(10, n)) b = range(100010) c = [0] * 100010 z = int(pow(100010, 1. / k)) + 1 p = [1] * 100010 for i in xrange(2, 100010): if c[i]: continue y = 1000000 if i <= z: y = x = pow(i, k - 1) j = i while j < 100010: c[j] = 1 y -= 1 if y: p[j] *= i else: y = x while b[j] % (x * i) == 0: b[j] /= x * i j += i pa = [0] * 100010 pa[1] = 1 z2 = int(pow(10 ** 10, 1. / k)) + 1 for i in xrange(2, 100010): if i != b[i]: pa[i] = pa[b[i]] continue if p[i] <= z2: pa[i] = pow(p[i], k) / i a = [b[x] for x in a] d = defaultdict(int) ans = 0 for x in a: if pa[x] in d: ans += d[pa[x]] d[x] += 1 print ans main()
1572087900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["9\n4\n7\n44\n99"]
8588dd273c9651f8d51cd3a2b7bd81bd
NoteIn the first test case, when Alice evaluates any of the sums $$$1 + 9$$$, $$$2 + 8$$$, $$$3 + 7$$$, $$$4 + 6$$$, $$$5 + 5$$$, $$$6 + 4$$$, $$$7 + 3$$$, $$$8 + 2$$$, or $$$9 + 1$$$, she will get a result of $$$100$$$. The picture below shows how Alice evaluates $$$6 + 4$$$:
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum $$$2039 + 2976$$$ would be as shown: However, Alice evaluates it as shown: In particular, this is what she does: add $$$9$$$ and $$$6$$$ to make $$$15$$$, and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$0$$$ $$$9$$$"; add $$$3$$$ and $$$7$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$2$$$ $$$2$$$"; add $$$1$$$, $$$0$$$, and $$$9$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column above the plus sign; add $$$1$$$, $$$2$$$ and $$$2$$$ to make $$$5$$$; add $$$1$$$ to make $$$1$$$. Thus, she ends up with the incorrect result of $$$15005$$$.Alice comes up to Bob and says that she has added two numbers to get a result of $$$n$$$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. Note that pairs $$$(a, b)$$$ and $$$(b, a)$$$ are considered different if $$$a \ne b$$$.
For each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number Alice shows Bob.
standard output
standard input
PyPy 3-64
Python
1,600
train_089.jsonl
1ab61c205e8d9fb69064db9ae1f858f9
256 megabytes
["5\n100\n12\n8\n2021\n10000"]
PASSED
def solve(n): s = str(n) a = int(s[0:len(s):2]) b = int(s[1:len(s):2]) if len(s) > 1 else 0 return (a + 1) * (b + 1) - 2 t = int(input()) for _ in range(t): n = int(input()) print(solve(n))
1630852500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["4\n2 3\n2 4\n6 6\n5 2\n4\n2 2\n2 3\n3 3\n3 2\n3\n2 5\n4 5\n4 2"]
2ba73e9b1359a17d10cf2f06a30c871d
NoteIt is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x1, y1) is lexicographically smaller than vertex (x2, y2) if x1 &lt; x2 or .
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!
For each test case, give the following output: The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.
The input contains multiple test cases. The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4. Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1). The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.
standard output
standard input
Python 3
Python
2,600
train_054.jsonl
1702f9ee543c773b723e54c7e7505b29
256 megabytes
["8\n00000000\n00000110\n00012210\n01234200\n02444200\n01223200\n00001100\n00000000\n5\n00000\n01210\n02420\n01210\n00000\n7\n0000000\n0122100\n0134200\n0013200\n0002200\n0001100\n0000000\n0"]
PASSED
import math def lexComp(a, b): if a[0] != b[0]: return -1 if a[0] < b[0] else 1 if a[1] != b[1]: return -1 if a[1] < b[1] else 1 return 0 def turn(a, b, c): return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) def dist2(a, b): return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 def solve(n): a = [list(map(int, input())) for _ in range(n)] points = [] for i in range(n): for j in range(n): if a[i][j] == 1: curPoints = [] for dx in range(0, 2): for dy in range(0, 2): ok = True for ddx in range(0, 2): for ddy in range(0, 2): x, y = i - 1 + dx + ddx, j - 1 + dy + ddy if 0 <= x < n and 0 <= y < n and a[x][y] == 0: ok = False if ok: curPoints.append((i + dx, j + dy)) points.append(curPoints[0]) points = list(set(points)) for i in range(1, len(points)): if lexComp(points[0], points[i]) > 0: points[0], points[i] = points[i], points[0] points[1:] = sorted(points[1:], key=lambda p: (math.atan2(p[1] - points[0][1], p[0] - points[0][0]), dist2(p, points[0]))) hull = [] for p in points: while len(hull) >= 2 and turn(hull[-2], hull[-1], p) <= 0: hull.pop() hull.append(p) hull = [(p[1], n - p[0]) for p in hull] hull = hull[::-1] start = 0 for i in range(1, len(hull)): if lexComp(hull[i], hull[start]) < 0: start = i newHull = hull[start:] newHull.extend(hull[:start]) hull = newHull print(len(hull)) for p in hull: print(p[0], p[1]) while True: n = int(input()) if n == 0: break solve(n)
1468137600
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["32\n5\n25\n14\n4", "6\n3\n98\n13\n22\n15\n3"]
af002b3aef8e7c698eb6f154a4b0bae0
NoteThe first example is explained in the legend.
Vus the Cossack has a field with dimensions $$$n \times m$$$, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way: He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was. To the current field, he adds the inverted field to the right. To the current field, he adds the inverted field to the bottom. To the current field, he adds the current field to the bottom right. He repeats it.For example, if the initial field was: $$$\begin{matrix} 1 &amp; 0 &amp; \\ 1 &amp; 1 &amp; \\ \end{matrix}$$$ After the first iteration, the field will be like this: $$$\begin{matrix} 1 &amp; 0 &amp; 0 &amp; 1 \\ 1 &amp; 1 &amp; 0 &amp; 0 \\ 0 &amp; 1 &amp; 1 &amp; 0 \\ 0 &amp; 0 &amp; 1 &amp; 1 \\ \end{matrix}$$$ After the second iteration, the field will be like this: $$$\begin{matrix} 1 &amp; 0 &amp; 0 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 0 &amp; 0 &amp; 0 &amp; 0 &amp; 1 &amp; 1 \\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 0 &amp; 0 &amp; 1 \\ 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 0 \\ 0 &amp; 1 &amp; 1 &amp; 0 &amp; 1 &amp; 0 &amp; 0 &amp; 1 \\ 0 &amp; 0 &amp; 1 &amp; 1 &amp; 1 &amp; 1 &amp; 0 &amp; 0 \\ 1 &amp; 0 &amp; 0 &amp; 1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 \\ 1 &amp; 1 &amp; 0&amp; 0 &amp; 0 &amp; 0 &amp; 1 &amp; 1 \\ \end{matrix}$$$ And so on...Let's numerate lines from top to bottom from $$$1$$$ to infinity, and columns from left to right from $$$1$$$ to infinity. We call the submatrix $$$(x_1, y_1, x_2, y_2)$$$ all numbers that have coordinates $$$(x, y)$$$ such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$.The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!
For each query, print the answer.
The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \leq n, m \leq 1\,000$$$, $$$1 \leq q \leq 10^5$$$) — the dimensions of the initial matrix and the number of queries. Each of the next $$$n$$$ lines contains $$$m$$$ characters $$$c_{ij}$$$ ($$$0 \leq c_{ij} \leq 1$$$) — the characters in the matrix. Each of the next $$$q$$$ lines contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1 \leq x_2 \leq 10^9$$$, $$$1 \leq y_1 \leq y_2 \leq 10^9$$$) — the coordinates of the upper left cell and bottom right cell, between which you need to find the sum of all numbers.
standard output
standard input
PyPy 3
Python
2,500
train_076.jsonl
073eaab86ac4edce005bf25ac6dc9c38
256 megabytes
["2 2 5\n10\n11\n1 1 8 8\n2 4 5 6\n1 2 7 8\n3 3 6 8\n5 6 7 8", "2 3 7\n100\n101\n4 12 5 17\n5 4 9 4\n1 4 13 18\n12 1 14 9\n3 10 7 18\n3 15 12 17\n8 6 8 12"]
PASSED
from sys import stdin,stdout n,m,q = map(int, stdin.readline().split()) mat = [[0]*m for i in range(n)] for i in range(n): row = stdin.readline().strip() for j,c in enumerate(row): mat[i][j] = 1 if c == '1' else -1 #print(mat) def get(a,b): if a < 0 or b < 0: return 0 x = a^b ans = 1 while x > 0: if x % 2 == 1: ans *= -1 x //= 2 return ans row_sums = [[0]*(m+1) for i in range(n+1)] for i in range(n): for j in range(m): row_sums[i+1][j+1] = row_sums[i][j+1] + mat[i][j] #print(row_sums) mat_sums = [[0]*(m+1) for i in range(n+1)] for i in range(n): for j in range(m): mat_sums[i+1][j+1] = mat_sums[i+1][j] + row_sums[i+1][j+1] #print(mat_sums) total = mat_sums[n][m] def rect_sum(a, b): if a == 0 or b == 0: return 0 top_edge = 0 right_edge = 0 small = 0 x = a//n x_rem = a%n y = b // m y_rem = b%m # print("x", x, "y", y, "x_rem", x_rem, "y_rem", y_rem) big = 0 if x % 2 == 0 or y % 2 == 0 else total big *= get(x-1,y-1) if x % 2 == 1: right_edge= mat_sums[n][y_rem] right_edge *= get(x-1,y) if y % 2 == 1: top_edge = mat_sums[x_rem][m] top_edge *= get(x,y-1) small = mat_sums[x_rem][y_rem] small *= get(x,y) # print("big", big, "top", top_edge, "right", right_edge, "small", small) return top_edge + right_edge+small+big for it in range(q): x1,y1,x2,y2 = map(int, stdin.readline().split()) ans = rect_sum(x2,y2) - rect_sum(x1-1, y2) - rect_sum(x2, y1-1) + rect_sum(x1-1,y1-1) ans = ((x2-x1+1)*(y2-y1+1) + ans)//2 stdout.write(str(ans) + '\n')
1561710000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3 1", "11 2 0 0"]
607dd33e61f57caced7b61ca8001e871
NoteConsider a string t = t1t2... t|t|, where ti denotes the i-th character of the string, and |t| denotes the length of the string.Then t[i... j] (1 ≤ i ≤ j ≤ |t|) represents the string titi + 1... tj (substring of t from position i to position j inclusive).
You are given three strings (s1, s2, s3). For each integer l (1 ≤ l ≤ min(|s1|, |s2|, |s3|) you need to find how many triples (i1, i2, i3) exist such that three strings sk[ik... ik + l - 1] (k = 1, 2, 3) are pairwise equal. Print all found numbers modulo 1000000007 (109 + 7).See notes if you are not sure about some of the denotions used in the statement.
You need to output min(|s1|, |s2|, |s3|) numbers separated by spaces — answers for the problem modulo 1000000007 (109 + 7).
First three lines contain three non-empty input strings. The sum of lengths of all strings is no more than 3·105. All strings consist only of lowercase English letters.
standard output
standard input
PyPy 2
Python
2,400
train_055.jsonl
13680e9d743be50cd1953498f8dc91c4
256 megabytes
["abc\nbc\ncbc", "abacaba\nabac\nabcd"]
PASSED
MOD = 1000000007 oo = int(2e9) class Node: def __init__(self, p, l = oo): self.spos = p self.slink = 0 self.length = l self.next_node = [0 for _ in range(28)] #Ukkonen class SuffixTree: def __init__(self, s): self.nodes = [Node(0)] self.s = [] self.pos = 0 self.node = 0 self.last_leaf = 0 for c in s: self.extend(ord(c) - 97) def get_len(self, p): if p == 0: return 0 return min(self.nodes[p].length, len(self.s) - self.nodes[p].spos) def add_node(self, p, l = oo): r = len(self.nodes) self.nodes.append(Node(p, l)) return r def extend(self, c): self.pos += 1 self.s.append(c) n = len(self.s) last = 0 while self.pos: while self.pos > self.nodes[self.nodes[self.node].next_node[self.s[n - self.pos]]].length: self.node = self.nodes[self.node].next_node[self.s[n - self.pos]] self.pos -= self.nodes[self.node].length v = self.nodes[self.node].next_node[self.s[n - self.pos]] t = self.s[self.nodes[v].spos + self.pos - 1] if v == 0: nl = self.add_node(n - self.pos) self.nodes[self.node].next_node[self.s[n - self.pos]] = nl self.nodes[last].slink = self.node last = 0 elif t == c: self.nodes[last].slink = self.node return else: u = self.add_node(self.nodes[v].spos, self.pos - 1) nl = self.add_node(n - 1) self.nodes[u].next_node[c] = nl self.nodes[u].next_node[t] = v self.nodes[v].spos += self.pos - 1 self.nodes[v].length -= self.pos - 1 self.nodes[last].slink = u self.nodes[self.node].next_node[self.s[n - self.pos]] = u last = u if self.node: self.node = self.nodes[self.node].slink else: self.pos -= 1 self.nodes[self.last_leaf].slink = nl self.last_leaf = nl def dfs(u, d): pila = [(0, u, d)] while len(pila): k, u, d = pila.pop() if k == 0: if st.nodes[u].next_node.count(0) == 28: dl = d for i in range(2, -1, -1): if dl <= l[i] + 1: suffs[u][i] += 1 break else: dl -= l[i] + 1 pila.append((1, u, d)) else: pila.append((1, u, d)) for v in st.nodes[u].next_node: if v: pila.append((0, v, d + st.get_len(v))) else: if st.nodes[u].next_node.count(0) != 28: for v in st.nodes[u].next_node: if v: for i in range(3): suffs[u][i] += suffs[v][i] nd = d - st.get_len(u) + 1 if nd <= ml: val = 1 for i in range(3): val *= suffs[u][i] val %= MOD resp[nd] += val resp[nd] %= MOD if d + 1 <= ml: resp[d + 1] -= val resp[d + 1] %= MOD s = [] l = [] for _ in range(3): r = raw_input() s.append(r) l.append(len(r)) s.append('{') s[-1] = '|' s = ''.join(s) ml = min(l) st = SuffixTree(s) suffs = [[0] * 3 for _ in range(len(st.nodes))] resp = [0] * (ml + 1) dfs(0, 0) for i in range(len(resp) - 1): resp[i + 1] += resp[i] resp[i + 1] %= MOD print(' '.join(map(str, resp[1:])))
1406480400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["1\n-1\n3\n3"]
41d791867f27a57b50eebaad29754520
NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.
Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).
The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).
standard output
standard input
Python 2
Python
2,000
train_010.jsonl
86c67b2f8b0861d5a51142640f45a880
256 megabytes
["4\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-2 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n-1 1 0 0\n2 2 0 1\n-1 0 0 -2\n3 0 0 -2\n-1 1 -2 0"]
PASSED
n = int(raw_input().strip()) ans = [4*4] * n for i in range(4*n): if i%4 == 0: coords = [[] for _ in range(4)] x,y,a,b = map(int, raw_input().strip().split()) coords[i%4] += [complex(x,y)] for _ in range(3): x, y = a - (y - b), b + (x - a) coords[i%4] += [complex(x,y)] if i%4 == 3: for b in range(4**4): cb = [(b / 4**p)%4 for p in range(4)] verts = [] for j in range(4): p = coords[j][cb[j]] if p in verts: continue verts += [p] if len(verts) < 4: continue t = [False] * 4 for k in range(4): edges = [verts[j] - verts[k] for j in range(4) if j is not k] lensq = sorted([abs(e*e.conjugate()) for e in edges]) if lensq[0] == 0: continue if lensq[0] == lensq[1] and lensq[2] == 2*lensq[0]: t[k] = True if False not in t: ans[i//4] = min(ans[i//4], sum(cb)) for i in range(n): if ans[i] == 16: print -1 else: print ans[i]
1412609400
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["2", "-1", "6", "7237"]
42d0350a0a18760ce6d0d7a4d65135ec
NoteIn first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost.
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
The first line contains an integer n (1 ≤ n ≤ 300), number of cards. The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards. The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
standard output
standard input
Python 2
Python
1,900
train_042.jsonl
bcc042319447dc20ed76302950868889
256 megabytes
["3\n100 99 9900\n1 1 1", "5\n10 20 30 40 50\n1 1 1 1 1", "7\n15015 10010 6006 4290 2730 2310 1\n1 1 1 1 1 1 10", "8\n4264 4921 6321 6984 2316 8432 6120 1026\n4264 4921 6321 6984 2316 8432 6120 1026"]
PASSED
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys import math import random import operator from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations getcontext().prec = 100 def gcd(a, b): while b: a, b = b, a % b return a MOD = 10**9 + 7 INF = float("+inf") n = int(raw_input()) arr = map(int, raw_input().split()) arr_costs = map(int, raw_input().split()) costs = {} for i, c in enumerate(arr): costs[c] = min(arr_costs[i], costs.get(c, INF)) min_cost = sum(arr_costs) for i in xrange(100): lst = arr[::] random.shuffle(lst) r = 0 cost = 0 for x in lst: r0 = r r = gcd(r, x) if r != r0: cost += costs[x] if r == 1: break if cost < min_cost: min_cost = cost if reduce(gcd, arr, 0) != 1: print -1 quit() g_min_cost = {0: 0} from Queue import PriorityQueue q = PriorityQueue() q.put((0, 0)) checked = set() while not q.empty(): cost, g = q.get() # print cost, g if g_min_cost[g] != cost: continue checked.add((cost, g)) for x in arr: cost2 = cost + costs[x] if cost2 >= min_cost: continue g2 = int(abs(gcd(g, x))) if g2 == g: continue if g2 == 1: min_cost = min(min_cost, cost2) continue if g_min_cost.get(g2, INF) > cost2: g_min_cost[g2] = cost2 q.put((cost2, g2)) # if (cost2, g2) not in checked: print min_cost
1422894600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 секунда
["1", "6"]
fa897b774525f038dc2d1b65c4ceda28
ПримечаниеВ первом примере всего один вариант для выбора состава, который удовлетворяет описанным условиям, поэтому ответ 1.Во втором примере подходят следующие игровые сочетания (в порядке вратарь-защитник-защитник-нападающий-нападающий-нападающий): 16 20 12 13 21 11 16 20 12 13 11 10 16 20 19 13 21 11 16 20 19 13 11 10 16 12 19 13 21 11 16 12 19 13 11 10 Таким образом, ответ на этот пример — 6.
Завтра у хоккейной команды, которой руководит Евгений, важный матч. Евгению нужно выбрать шесть игроков, которые выйдут на лед в стартовом составе: один вратарь, два защитника и три нападающих.Так как это стартовый состав, Евгения больше волнует, насколько красива будет команда на льду, чем способности игроков. А именно, Евгений хочет выбрать такой стартовый состав, чтобы номера любых двух игроков из стартового состава отличались не более, чем в два раза. Например, игроки с номерами 13, 14, 10, 18, 15 и 20 устроят Евгения, а если, например, на лед выйдут игроки с номерами 8 и 17, то это не устроит Евгения.Про каждого из игроков вам известно, на какой позиции он играет (вратарь, защитник или нападающий), а также его номер. В хоккее номера игроков не обязательно идут подряд. Посчитайте число различных стартовых составов из одного вратаря, двух защитников и трех нападающих, которые может выбрать Евгений, чтобы выполнялось его условие красоты.
Выведите одно целое число — количество возможных стартовых составов.
Первая строка содержит три целых числа g, d и f (1 ≤ g ≤ 1 000, 1 ≤ d ≤ 1 000, 1 ≤ f ≤ 1 000) — число вратарей, защитников и нападающих в команде Евгения. Вторая строка содержит g целых чисел, каждое в пределах от 1 до 100 000 — номера вратарей. Третья строка содержит d целых чисел, каждое в пределах от 1 до 100 000 — номера защитников. Четвертая строка содержит f целых чисел, каждое в пределах от 1 до 100 000 — номера нападающих. Гарантируется, что общее количество игроков не превосходит 1 000, т. е. g + d + f ≤ 1 000. Все g + d + f номеров игроков различны.
стандартный вывод
стандартный ввод
Python 3
Python
1,700
train_062.jsonl
2dbc5c24d5a709ce39e645505f0c4d83
256 мегабайт
["1 2 3\n15\n10 19\n20 11 13", "2 3 4\n16 40\n20 12 19\n13 21 11 10"]
PASSED
import sys import math import random import time def func_cnk(keepers, defenders, attackers, flag): if flag == 'kpr': kpr = 1 defs = math.factorial(defenders) // math.factorial(2) // math.factorial(defenders - 2) atts = math.factorial(attackers) // math.factorial(3) // math.factorial(attackers - 3) elif flag == 'def': kpr = keepers defs = defenders - 1 atts = math.factorial(attackers) // math.factorial(3) // math.factorial(attackers - 3) elif flag == 'att': kpr = keepers defs = math.factorial(defenders) // math.factorial(2) // math.factorial(defenders - 2) atts = math.factorial(attackers - 1) // math.factorial(2) // math.factorial(attackers - 3) return kpr * int(defs) * int(atts) g, d, f = list(map(int, input().split())) x = list(map(int, input().split())) y = list(map(int, input().split())) z = list(map(int, input().split())) #N = 100000 #x = random.sample(range(1, N), g) #y = random.sample(range(1, N), d) #z = random.sample(range(1, N), f) #print(x, y, z) if (d < 2) or (f < 3): print('0') sys.exit() t = time.time() res_ans = 0 dict_nums = {} for num in x: dict_nums[num] = 'kpr' for num in y: dict_nums[num] = 'def' for num in z: dict_nums[num] = 'att' all_nums = x + y + z all_nums.sort() for i in range(len(all_nums)): upper = all_nums[i] * 2 j = i keepers = 0 defenders = 0 attackers = 0 while (j < len(all_nums) and (all_nums[j] <= upper)): if dict_nums[all_nums[j]] == 'kpr': keepers = keepers + 1 if dict_nums[all_nums[j]] == 'def': defenders = defenders + 1 if dict_nums[all_nums[j]] == 'att': attackers = attackers + 1 j = j + 1 if (keepers > 0) and (defenders > 1) and (attackers > 2): #print(all_nums[i], func_cnk(keepers, defenders, attackers, dict_nums[all_nums[i]])) res_ans = res_ans + func_cnk(keepers, defenders, attackers, dict_nums[all_nums[i]]) print(res_ans)
1520004900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO"]
4f3bec9c36d0ac2fdb8041469133458c
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
standard output
standard input
Python 2
Python
1,500
train_024.jsonl
c43c5f8c4ba474f44e404563f71364e4
256 megabytes
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
PASSED
import sys def check(coor1, coor2): dx = coor1[0] - coor2[0] dy = coor1[1] - coor2[1] if dx % 2 != 0 or dy % 2 != 0 : return False if ((dx/2)-(dy/2) )% 2==0 and dx/2%2 == 0: return True return False def solve(data): horse = [] for y in xrange(8): for x in xrange(8): if data[y][x] == 'K': horse.append([x, y]) if not check(horse[0], horse[1]): return "NO" #for y in xrange(8): # for x in xrange(8): # if data[y][x] == ".": # if check(horse[0], [x,y]): # return "YES" return "YES" return "NO" try: d = sys.stdin.readline() t = int(d) except: print (d) for _ in xrange(t): data = [] for i in xrange(8): d = sys.stdin.readline() if len(d.split()) == 0: d = sys.stdin.readline() data.append(d) print solve(data)
1384443000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2", "Impossible", "3"]
12b64f77fc9dd44a7e0287ff0a716a6a
NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?
On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.
The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.
standard output
standard input
Python 2
Python
1,600
train_035.jsonl
475cd15ab57f6076fd4f6e6aa22ca057
256 megabytes
["25\nHello. I am a little walrus.", "2\nHow are you?", "19\nHello! Do you like fish? Why?"]
PASSED
n = int(raw_input()) a = map(len, (" " + raw_input()).replace('?', '.').replace('!', '.')[:-1].split('.')) res = 0 t = -1 for i in a: if i > n: print "Impossible" exit() if t + i + 1 <= n: t += i + 1 else: res += 1 t = i if t != 0: res += 1 print res
1301155200
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["3", "4"]
98348af1203460b3f69239d3e8f635b9
NoteIn the first sample, if we rearrange elements of the sequence as  - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
standard output
standard input
Python 3
Python
2,000
train_003.jsonl
11bb6e8a96c3a8748f736fe3943ef0a8
512 megabytes
["3\n1 2 -1", "5\n28 35 7 14 21"]
PASSED
#!/usr/bin/env python3 n = int(input()) a = [int(x) for x in input().split()] sorted_a = sorted(a) dict_a = {} for x in a: if not x in dict_a: dict_a[x] = 1 else: dict_a[x] += 1 sorted_uniq_a = sorted(dict_a.keys()) max_fib_prefix = [a[0], a[1]] for i in range(0, len(sorted_uniq_a)): for j in range(0, len(sorted_uniq_a)): if i != j or dict_a[sorted_uniq_a[i]] > 1: if sorted_uniq_a[i] + sorted_uniq_a[j] > sorted_uniq_a[-1]: break fib_prefix = [sorted_uniq_a[i], sorted_uniq_a[j]] dict_a[sorted_uniq_a[i]] -= 1 dict_a[sorted_uniq_a[j]] -= 1 while True: next_fib = fib_prefix[-1] + fib_prefix[-2] if not next_fib in dict_a or dict_a[next_fib] == 0: break fib_prefix.append(next_fib) dict_a[next_fib] -= 1 for x in fib_prefix: dict_a[x] += 1 if len(fib_prefix) > len(max_fib_prefix): max_fib_prefix = fib_prefix print(len(max_fib_prefix))
1456506900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2", "2"]
875e7048b7a254992b9f62b9365fcf9b
NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree.
standard output
standard input
PyPy 3
Python
1,500
train_000.jsonl
1f978826abaf13952a87551a910eda11
256 megabytes
["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"]
PASSED
import sys import time def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) mod = int(1e9)+7 n, m = rinput() a = get_list() g = [[] for _ in range(n)] v = [0]*n for _ in range(n-1): x, y = rinput() g[x-1].append(y-1) g[y-1].append(x-1) ans = i = 0 q = [(0, 0)] while i<len(q): x, N = q[i] v[x] = 1 if a[x]+N<=m: L = 1 for y in g[x]: if not v[y]: L = 0 q.append((y, a[x]*(a[x]+N))) if L: ans+=1 i+=1 print(ans)
1442939400
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["1 2 3", "6 1 3 4 2 5"]
13d7f6127a7fe945e19d461b584c6228
NoteThis is the picture with the polygonal line from the $$$1$$$ test: As we see, this polygonal line is non-self-intersecting and winding, because the turn in point $$$2$$$ is left.This is the picture with the polygonal line from the $$$2$$$ test:
Vasya has $$$n$$$ different points $$$A_1, A_2, \ldots A_n$$$ on the plane. No three of them lie on the same line He wants to place them in some order $$$A_{p_1}, A_{p_2}, \ldots, A_{p_n}$$$, where $$$p_1, p_2, \ldots, p_n$$$ — some permutation of integers from $$$1$$$ to $$$n$$$.After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all $$$1 \leq i \leq n-1$$$ he will draw oriented segment from point $$$A_{p_i}$$$ to point $$$A_{p_{i+1}}$$$. He wants to make this polygonal line satisfying $$$2$$$ conditions: it will be non-self-intersecting, so any $$$2$$$ segments which are not neighbors don't have common points. it will be winding. Vasya has a string $$$s$$$, consisting of $$$(n-2)$$$ symbols "L" or "R". Let's call an oriented polygonal line winding, if its $$$i$$$-th turn left, if $$$s_i = $$$ "L" and right, if $$$s_i = $$$ "R". More formally: $$$i$$$-th turn will be in point $$$A_{p_{i+1}}$$$, where oriented segment from point $$$A_{p_i}$$$ to point $$$A_{p_{i+1}}$$$ changes to oriented segment from point $$$A_{p_{i+1}}$$$ to point $$$A_{p_{i+2}}$$$. Let's define vectors $$$\overrightarrow{v_1} = \overrightarrow{A_{p_i} A_{p_{i+1}}}$$$ and $$$\overrightarrow{v_2} = \overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}$$$. Then if in order to rotate the vector $$$\overrightarrow{v_1}$$$ by the smallest possible angle, so that its direction coincides with the direction of the vector $$$\overrightarrow{v_2}$$$ we need to make a turn counterclockwise, then we say that $$$i$$$-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns: There are left turns on this picture There are right turns on this picture You are given coordinates of the points $$$A_1, A_2, \ldots A_n$$$ on the plane and string $$$s$$$. Find a permutation $$$p_1, p_2, \ldots, p_n$$$ of the integers from $$$1$$$ to $$$n$$$, such that the polygonal line, drawn by Vasya satisfy two necessary conditions.
If the satisfying permutation doesn't exists, print $$$-1$$$. In the other case, print $$$n$$$ numbers $$$p_1, p_2, \ldots, p_n$$$ — the permutation which was found ($$$1 \leq p_i \leq n$$$ and all $$$p_1, p_2, \ldots, p_n$$$ are different). If there exists more than one solution, you can find any.
The first line contains one integer $$$n$$$ — the number of points ($$$3 \leq n \leq 2000$$$). Next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$, divided by space — coordinates of the point $$$A_i$$$ on the plane ($$$-10^9 \leq x_i, y_i \leq 10^9$$$). The last line contains a string $$$s$$$ consisting of symbols "L" and "R" with length $$$(n-2)$$$. It is guaranteed that all points are different and no three points lie at the same line.
standard output
standard input
PyPy 2
Python
2,600
train_079.jsonl
5d228bc096bb83158df9825d92839c0f
256 megabytes
["3\n1 1\n3 1\n1 3\nL", "6\n1 0\n0 1\n0 2\n-1 0\n-1 -1\n2 1\nRLLR"]
PASSED
n = int(raw_input()) pts = [map(int, raw_input().split()) for __ in xrange(n)] s = raw_input().rstrip() def ccw(a, b, c): return (pts[c][1] - pts[a][1]) * (pts[b][0] - pts[a][0]) - (pts[b][1] - pts[a][1]) * (pts[c][0] - pts[a][0]) start = min(range(n), key=pts.__getitem__) unused = set(range(n)) unused.remove(start) ret = [start] cur = start for c in s: nxt = -1 for t in unused: if nxt == -1 or ccw(cur, nxt, t) * (-1 if c == 'L' else 1) > 0: nxt = t unused.remove(nxt) cur = nxt ret.append(nxt) ret.append(unused.pop()) for i in xrange(len(ret)): ret[i] += 1 print " ".join(map(str, ret))
1557671700
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["16", "1", "2", "2", "1"]
6156ef296f6d512887d10a0624ad4a7b
null
You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index $$$1$$$; if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way: if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$; otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).
Print one integer — the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.
standard output
standard input
PyPy 3-64
Python
2,100
train_087.jsonl
68547facb61a95a56f008088a07eb26c
512 megabytes
["4\nBAAAAAAAABBABAB", "2\nBAA", "2\nABA", "2\nAAB", "2\nAAA"]
PASSED
from collections import deque import sys from sys import stdin, stdout import math import random sys.setrecursionlimit(10**5) answer_li = [] INF = float("inf") mod = 998244353 read = stdin.readline def ir(): return int(read()) def mir(): return map(int, read().strip().split()) def lmir(): return list(map(int, read().strip().split())) def power(bottom, up): # print(bottom, up) if up == 1: return bottom elif up == 0: return 1 tmp = power(bottom, int(up // 2)) if up % 2 == 0: return (tmp * tmp) else: return (tmp * tmp * bottom) def dfs(root): if root * 2 >= len(li): return {"ans" : 1 , "before": li[root]} left = dfs(root * 2) right = dfs(root * 2 + 1) tmp = {"ans": 0, "before" : ""} tmp["ans"] = left["ans"] * right["ans"] left["before"] = li[root * 2] + left["before"] right["before"] = li[root * 2 + 1] + right["before"] if left["before"] != right["before"]: tmp["ans"] *= 2 tmp["ans"] %= mod if left["before"] <= right["before"]: tmp["before"] = left["before"] + right["before"] else: tmp["before"] = right["before"] + left["before"] # print(root , tmp) return tmp num = ir() li = ["0"] + list(read().strip()) print(dfs(1)["ans"])
1650638100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["YES\n001\n001\n110", "NO"]
8adebeaed713b7e90c68553127d17b19
null
Given three numbers $$$n, a, b$$$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $$$a$$$, and the number of components in its complement is $$$b$$$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.The adjacency matrix of an undirected graph is a square matrix of size $$$n$$$ consisting only of "0" and "1", where $$$n$$$ is the number of vertices of the graph and the $$$i$$$-th row and the $$$i$$$-th column correspond to the $$$i$$$-th vertex of the graph. The cell $$$(i,j)$$$ of the adjacency matrix contains $$$1$$$ if and only if the $$$i$$$-th and $$$j$$$-th vertices in the graph are connected by an edge.A connected component is a set of vertices $$$X$$$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $$$X$$$ violates this rule.The complement or inverse of a graph $$$G$$$ is a graph $$$H$$$ on the same vertices such that two distinct vertices of $$$H$$$ are adjacent if and only if they are not adjacent in $$$G$$$.
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes). Otherwise, on the first line, print "YES"(without quotes). In each of the next $$$n$$$ lines, output $$$n$$$ digits such that $$$j$$$-th digit of $$$i$$$-th line must be $$$1$$$ if and only if there is an edge between vertices $$$i$$$ and $$$j$$$ in $$$G$$$ (and $$$0$$$ otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes. If there are several matrices that satisfy the conditions — output any of them.
In a single line, three numbers are given $$$n, a, b \,(1 \le n \le 1000, 1 \le a, b \le n)$$$: is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
standard output
standard input
Python 3
Python
1,700
train_029.jsonl
a55ece13fa24b0b2162e5bcbaa81ab1d
256 megabytes
["3 1 2", "3 3 3"]
PASSED
from collections import defaultdict n,a,b = map(int,input().split()) hash = defaultdict(list) # debug # def dfs(n): # # # bool[n] = True # for i in hash[n]: # if bool[i] == False: # dfs(i) if a == 1 and b == 1: if n == 2 or n == 3: print('NO') exit() if a == 1 or b == 1: bool = [False]*(n+1) if a>n or b>n: print('NO') exit() print('YES') l = [] for i in range(n): z = ['0']*(n) l.append(z) ans = [] for i in range(n): z = ['0']*(n) ans.append(z) if b == 1: for i in range(a-1,n-1): # hash[i].add(i+1) # hash[i+1].add(i) l[i][i+1] = '1' l[i+1][i] = '1' # hash[i+1].append(i) # hash[i].append(i+1) # count = 0 # for i in range(n): # if bool[i] == False: # # dfs(i) # count+=1 # if a == 1 and b == 1: for i in l: print(''.join(i)) else: ans = [] for i in range(n): z = ['0']*(n) ans.append(z) for i in range(b-1,n-1): # hash[i].add(i+1) # hash[i+1].add(i) l[i][i+1] = '1' l[i+1][i] = '1' # hash[i+1].append(i) # hash[i].append(i+1) # for i in l: # print(*i) for i in range(n): for j in range(n): if i!=j: if l[i][j] == '1': ans[i][j] = '0' if l[i][j] == '0': ans[i][j] = '1' # hash[i+1].append(j+1) # count = 0 # for i in range(n): # if bool[i] == False: # # dfs(i) # count+=1 for i in ans: print(''.join(i)) else: print('NO')
1528625100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["YES\nYES\nNO\nNO\nYES\nNO"]
a6c6b2a66ba51249fdc5d4188ca09e3b
NoteIn the first test case, the permutation $$$[1]$$$ satisfies the array $$$c$$$.In the second test case, the permutation $$$[2,1]$$$ satisfies the array $$$c$$$.In the fifth test case, the permutation $$$[5, 1, 2, 4, 6, 3]$$$ satisfies the array $$$c$$$. Let's see why this is true. The zeroth cyclic shift of $$$p$$$ is $$$[5, 1, 2, 4, 6, 3]$$$. Its power is $$$2$$$ since $$$b = [5, 5, 5, 5, 6, 6]$$$ and there are $$$2$$$ distinct elements — $$$5$$$ and $$$6$$$. The first cyclic shift of $$$p$$$ is $$$[3, 5, 1, 2, 4, 6]$$$. Its power is $$$3$$$ since $$$b=[3,5,5,5,5,6]$$$. The second cyclic shift of $$$p$$$ is $$$[6, 3, 5, 1, 2, 4]$$$. Its power is $$$1$$$ since $$$b=[6,6,6,6,6,6]$$$. The third cyclic shift of $$$p$$$ is $$$[4, 6, 3, 5, 1, 2]$$$. Its power is $$$2$$$ since $$$b=[4,6,6,6,6,6]$$$. The fourth cyclic shift of $$$p$$$ is $$$[2, 4, 6, 3, 5, 1]$$$. Its power is $$$3$$$ since $$$b = [2, 4, 6, 6, 6, 6]$$$. The fifth cyclic shift of $$$p$$$ is $$$[1, 2, 4, 6, 3, 5]$$$. Its power is $$$4$$$ since $$$b = [1, 2, 4, 6, 6, 6]$$$. Therefore, $$$c = [2, 3, 1, 2, 3, 4]$$$.In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array $$$c$$$.
Shinju loves permutations very much! Today, she has borrowed a permutation $$$p$$$ from Juju to play with.The $$$i$$$-th cyclic shift of a permutation $$$p$$$ is a transformation on the permutation such that $$$p = [p_1, p_2, \ldots, p_n] $$$ will now become $$$ p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}]$$$.Let's define the power of permutation $$$p$$$ as the number of distinct elements in the prefix maximums array $$$b$$$ of the permutation. The prefix maximums array $$$b$$$ is the array of length $$$n$$$ such that $$$b_i = \max(p_1, p_2, \ldots, p_i)$$$. For example, the power of $$$[1, 2, 5, 4, 6, 3]$$$ is $$$4$$$ since $$$b=[1,2,5,5,6,6]$$$ and there are $$$4$$$ distinct elements in $$$b$$$.Unfortunately, Shinju has lost the permutation $$$p$$$! The only information she remembers is an array $$$c$$$, where $$$c_i$$$ is the power of the $$$(i-1)$$$-th cyclic shift of the permutation $$$p$$$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array $$$c$$$, determine if there exists a permutation $$$p$$$ that is consistent with $$$c$$$. You do not have to construct the permutation $$$p$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).
For each test case, print "YES" if there is a permutation $$$p$$$ exists that satisfies the array $$$c$$$, and "NO" otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1,c_2,\ldots,c_n$$$ ($$$1 \leq c_i \leq n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
standard output
standard input
Python 3
Python
1,700
train_095.jsonl
eff6df552aeb789ea076eecdb4f05fe8
256 megabytes
["6\n\n1\n\n1\n\n2\n\n1 2\n\n2\n\n2 2\n\n6\n\n1 2 4 6 3 5\n\n6\n\n2 3 1 2 3 4\n\n3\n\n3 2 1"]
PASSED
a,b,c=input,int,range for _ in c(b(a())):n=b(a());m=list(map(b,a().split()));print("YNEOS"[m.count(1)!= 1 or m[0]>m[-1]+1 or any(m[i+1]-m[i]>1 for i in range(n-1))::2])
1648391700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nYES\nNO"]
48151011c3d380ab303ae38d0804176a
NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ "threetwoone" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ "n", $$$s_2$$$ is empty and $$$p'=$$$ "one" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password.
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$); generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty); the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ "abacaba". Then $$$p'$$$ can be equal to "aabcaab". Random strings $$$s1 =$$$ "zyx" and $$$s2 =$$$ "kjh". Then $$$h =$$$ "zyxaabcaabkjh".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.
For each test case print the answer to it — "YES" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or "NO" otherwise.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.
standard output
standard input
PyPy 2
Python
1,000
train_009.jsonl
c6f603b595ff5f95fc7f9f71cf147aaf
256 megabytes
["5\nabacaba\nzyxaabcaabkjh\nonetwothree\nthreetwoone\none\nzzonneyy\none\nnone\ntwenty\nten"]
PASSED
t = input() for _ in xrange(t): p = raw_input() h = raw_input() n = len(p) m = len(h) ans = False low = 0 p = ''.join(sorted(p)) while low+n<=m: temp = h[low:low+n] temp = ''.join(sorted(temp)) if p == temp: ans = True break low += 1 if ans: print 'YES' else: print 'NO'
1576766100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["4\n3", "8\n9\n7\n6\n9"]
740d2aba32f69b8cfe8f7cb624621a63
NoteIn the first example:In the first query there are $$$4$$$ arrays that are $$$5$$$-similar to $$$[2,4]$$$: $$$[1,4],[3,4],[2,3],[2,5]$$$.In the second query there are $$$3$$$ arrays that are $$$5$$$-similar to $$$[4,5]$$$: $$$[1,5],[2,5],[3,5]$$$.
Given a positive integer $$$k$$$, two arrays are called $$$k$$$-similar if: they are strictly increasing; they have the same length; all their elements are positive integers between $$$1$$$ and $$$k$$$ (inclusive); they differ in exactly one position. You are given an integer $$$k$$$, a strictly increasing array $$$a$$$ and $$$q$$$ queries. For each query, you are given two integers $$$l_i \leq r_i$$$. Your task is to find how many arrays $$$b$$$ exist, such that $$$b$$$ is $$$k$$$-similar to array $$$[a_{l_i},a_{l_i+1}\ldots,a_{r_i}]$$$.
Print $$$q$$$ lines. The $$$i$$$-th of them should contain the answer to the $$$i$$$-th query.
The first line contains three integers $$$n$$$, $$$q$$$ and $$$k$$$ ($$$1\leq n, q \leq 10^5$$$, $$$n\leq k \leq 10^9$$$) — the length of array $$$a$$$, the number of queries and number $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots,a_n$$$ ($$$1 \leq a_i \leq k$$$). This array is strictly increasing  — $$$a_1 &lt; a_2 &lt; \ldots &lt; a_n$$$. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$).
standard output
standard input
PyPy 3-64
Python
1,200
train_092.jsonl
4f7ad7291bece73019a6d44146bd4ca4
256 megabytes
["4 2 5\n1 2 4 5\n2 3\n3 4", "6 5 10\n2 4 6 7 8 9\n1 4\n1 2\n3 5\n1 6\n5 5"]
PASSED
import sys import math def prime_generator(nr_elemente_prime): #print("pornire") vector_prime=[-1]*nr_elemente_prime vector_rasp=[0]*nr_elemente_prime vector_prime[1]=1 vector_rasp[1]=1 #primes sieve contor=2 for i in range(2,nr_elemente_prime): if vector_prime[i]==-1: vector_prime[i]=1 vector_rasp[contor]=i contor=contor+1 for j in range(i+i,nr_elemente_prime,i): if vector_prime[j]==-1: vector_prime[j]=i #print(i,j) my_set=set(vector_rasp) my_set.remove(0) my_set.remove(1) lista_prime=list(my_set) lista_prime.sort() return lista_prime vector_prime= prime_generator(1000000) #print(vector_prime) set_prime=set(vector_prime) def functie_divizori(numar): radical=int(numar**(1/2)) set_divizori=set() if numar==1: set_divizori.add(1) elif numar in set_prime: set_divizori.add(numar) else: for x in vector_prime: if x>radical: break else: if numar%x==0: set_divizori.add(x) set_divizori.add(numar//x) set_divizori.add(numar) return set_divizori #print(functie_divizori(6)) def printare_matrice(mat): for i in mat: for j in i: print(j,end=' ') print() def transformare_baza(numar,baza): transformare="" while numar>=baza: rest=numar%baza numar=numar//baza transformare+=str(rest) transformare+=str(numar) noua_baza=transformare[::-1] return noua_baza def cautare_binara(pozitie,vector): #print("aici") pornire=0 oprire=pozitie-1 noua_pozitie=(pornire+oprire)//2 diferenta=vector[pozitie][0]-vector[pozitie][1] #print("dif=",diferenta) #print(pozitie,pornire,oprire,noua_pozitie) while pornire+1<oprire: # print(noua_pozitie,vector[noua_pozitie][0]) while pornire+1<oprire and diferenta<=vector[noua_pozitie][0]: # print("aici?",noua_pozitie,vector[noua_pozitie][0]) oprire=noua_pozitie noua_pozitie=(pornire+oprire)//2 while pornire+1<oprire and diferenta>vector[noua_pozitie][0]: #print(noua_pozitie,vector[noua_pozitie][0]) pornire=noua_pozitie noua_pozitie=(pornire+oprire)//2 # print("p=",pornire,"d=",diferenta) while vector[pornire][0]<diferenta: pornire+=1 while pornire-1>=0 and vector[pornire-1][0]>=diferenta: pornire-=1 return (pozitie-pornire) #vector = sorted(vector, key=lambda x: x[0]) #lista=list(map(int,input().split())) #alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26} #alfabet_2={'1':"a", '2':"b", '3':"c", '4':"d", '5':"e", '6':"f", '7':"g", '8':"h", '9':"i", '10':"j", '11':"k", '12':"l", '13':"m", '14':"n", '15':"o", '16':"p", '17':"q", '18':"r", '19':"s", '20':"t", '21':"u", '22':"v", '23':"w", '24':"x", '25':"y", '26':"z"} #print(vector[0:10]) #print(lista[0:10]) #z=int(input()) for contorr in range(1): n,q,k= list(map(int, sys.stdin.readline().split())) vector=list(map(int, sys.stdin.readline().split())) # val=list(map(int, sys.stdin.readline().split())) # blocari.append(n) if n==1: for jj in range(q): print(k-1) else: left=[] left.append(vector[1]-2) # left=[0]*n # left[0]=vector[1]-2 right=[] right.append(k-1) #print(right[n-1]) intre=[] intre.append(0) startare=[] startare.append(0) for i in range(1,n-1): left.append(vector[i+1]-2) right.append(k-vector[i-1]-1) intre.append(vector[i+1]-vector[i-1]-2) startare.append(startare[i-1]+intre[i]) intre.append(0) left.append(k-vector[n-1]) right.append(k-vector[n-2]-1) startare.append(0) # print(intre,left,right,startare) #print(intre,left,right) for x in range(q): l,r= map(int, sys.stdin.readline().split()) l-=1 r-=1 #print(x) if l==r: print(k-1) else: print(int(left[l]+right[r]+startare[r-1]-startare[l]))
1613141400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n2\n9\n10\n26"]
ea011f93837fdf985f7eaa7a43e22cc8
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
standard output
standard input
Python 3
Python
null
train_020.jsonl
b1705e42199181a59f2604e7ee326801
256 megabytes
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
PASSED
from sys import stdin, stdout readline, writeline = stdin.readline, stdout.write def iint(): return int(readline().strip()) for _ in range(iint()): n = readline().strip() writeline("{}\n".format(len(n)))
1606746900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
6.5 seconds
["0\n0\n1\n2\n5\n1\n5"]
a4f03259518029b38d71ed4c41209677
null
A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i &lt; j &lt; k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
For each query, print one integer — the number of beautiful triples after processing the respective query.
The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) — the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
standard output
standard input
PyPy 3-64
Python
2,500
train_098.jsonl
4cee4a89a61a89075d2bcf77539ddcc8
512 megabytes
["7 5\n8 5 3 2 1 5 6"]
PASSED
############################### class lazy_segtree(): def update(self,k):self.d[k]=self.op(self.d[2*k],self.d[2*k+1]) def all_apply(self,k,f): self.d[k]=self.mapping(f,self.d[k]) if (k<self.size):self.lz[k]=self.composition(f,self.lz[k]) def push(self,k): self.all_apply(2*k,self.lz[k]) self.all_apply(2*k+1,self.lz[k]) self.lz[k]=self.identity def __init__(self,V,OP,E,MAPPING,COMPOSITION,ID): self.n=len(V) self.log=(self.n-1).bit_length() self.size=1<<self.log self.d=[E for i in range(2*self.size)] self.lz=[ID for i in range(self.size)] self.e=E self.op=OP self.mapping=MAPPING self.composition=COMPOSITION self.identity=ID for i in range(self.n):self.d[self.size+i]=V[i] for i in range(self.size-1,0,-1):self.update(i) def set(self,p,x): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) self.d[p]=x for i in range(1,self.log+1):self.update(p>>i) def get(self,p): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) return self.d[p] def prod(self,l,r): assert 0<=l and l<=r and r<=self.n if l==r:return self.e l+=self.size r+=self.size for i in range(self.log,0,-1): if (((l>>i)<<i)!=l):self.push(l>>i) if (((r>>i)<<i)!=r):self.push(r>>i) sml,smr=self.e,self.e while(l<r): if l&1: sml=self.op(sml,self.d[l]) l+=1 if r&1: r-=1 smr=self.op(self.d[r],smr) l>>=1 r>>=1 return self.op(sml,smr) def all_prod(self):return self.d[1] def apply_point(self,p,f): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) self.d[p]=self.mapping(f,self.d[p]) for i in range(1,self.log+1):self.update(p>>i) def apply(self,l,r,f): assert 0<=l and l<=r and r<=self.n if l==r:return l+=self.size r+=self.size for i in range(self.log,0,-1): if (((l>>i)<<i)!=l):self.push(l>>i) if (((r>>i)<<i)!=r):self.push((r-1)>>i) l2,r2=l,r while(l<r): if (l&1): self.all_apply(l,f) l+=1 if (r&1): r-=1 self.all_apply(r,f) l>>=1 r>>=1 l,r=l2,r2 for i in range(1,self.log+1): if (((l>>i)<<i)!=l):self.update(l>>i) if (((r>>i)<<i)!=r):self.update((r-1)>>i) def max_right(self,l,g): assert 0<=l and l<=self.n assert g(self.e) if l==self.n:return self.n l+=self.size for i in range(self.log,0,-1):self.push(l>>i) sm=self.e while(1): while(i%2==0):l>>=1 if not(g(self.op(sm,self.d[l]))): while(l<self.size): self.push(l) l=(2*l) if (g(self.op(sm,self.d[l]))): sm=self.op(sm,self.d[l]) l+=1 return l-self.size sm=self.op(sm,self.d[l]) l+=1 if (l&-l)==l:break return self.n def min_left(self,r,g): assert (0<=r and r<=self.n) assert g(self.e) if r==0:return 0 r+=self.size for i in range(self.log,0,-1):self.push((r-1)>>i) sm=self.e while(1): r-=1 while(r>1 and (r%2)):r>>=1 if not(g(self.op(self.d[r],sm))): while(r<self.size): self.push(r) r=(2*r+1) if g(self.op(self.d[r],sm)): sm=self.op(self.d[r],sm) r-=1 return r+1-self.size sm=self.op(self.d[r],sm) if (r&-r)==r:break return 0 ########################### M=2*10**5+10 def to(x): num2,num,cnt1=x return [num2,num*M+cnt1] def inv(x): num2=x[0] y=x[1] cnt1=y%M num=y//M return [num2,num,cnt1] def op(a,b): a=inv(a) b=inv(b) res=[0,0,0] res[0]=a[0]+b[0] res[1]=a[1]+b[1] res[2]=a[2]+b[2] return to(res) def mapping(f,x): x=inv(x) num2,num,cnt1=x res2,res,rescnt1=0,0,0 res2=num2+2*f*num+f**2*cnt1 res=num+f*cnt1 rescnt1=cnt1 return to([res2,res,rescnt1]) def compose(f,g): return f+g #################################### class BIT: #https://atcoder.jp/contests/abc233/submissions/28159326 def __init__(self,arg): if isinstance(arg,int): self.N=arg self.dat=[0]*(self.N+1) else: self.N=len(arg) self.dat=[0]+list(arg) for i in range(self.N.bit_length()-1): for j in range(self.N>>(i+1)): idx=(j<<1|1)<<i nidx=idx+(idx&-idx) if nidx<self.N+1: self.dat[nidx]+=self.dat[idx] def add(self,idx,x): idx+=1 while idx<self.N+1: self.dat[idx]+=x idx+=idx&-idx def sum(self,idx): if idx<0:return 0 idx+=1 sum_=0 while idx>0: sum_+=self.dat[idx] idx-=idx&-idx return sum_ def query(self,l,r): if l>=r:return 0 return self.sum(r-1)-self.sum(l-1) def get(self,k): return self.query(k,k+1) def update(self,k,x): self.add(k,-self.get(k)) self.add(k,x) def lower_bound(self,x): sum_=0 idx=1<<(self.N.bit_length()-1) while True: if idx<self.N+1 and sum_+self.dat[idx]<x: sum_+=self.dat[idx] if idx&-idx==1: break idx+=(idx&-idx)>>1 else: if idx&-idx==1: idx-=1 break idx-=(idx&-idx)>>1 return idx,sum_ ################################### q,d=map(int,input().split()) x=[0]*(4*10**5+10) wa=BIT(4*10**5+10) seg=lazy_segtree([to([0,0,0]) for i in range(2*10**5+10)],op,to([0,0,0]),mapping,compose,0) a=list(map(int,input().split())) for i in a: if x[i]==1: x[i]=0 wa.add(i,-1) seg.set(i,to([0,0,0])) left=max(0,i-d) right=i seg.apply(left,right,-1) else: x[i]=1 wa.add(i,1) num=wa.query(i+1,i+d+1) seg.set(i,to([num**2,num,1])) left = max(0, i - d) right = i seg.apply(left, right, 1) ans=inv(seg.prod(1,2*10**5+1)) num2,num,_=ans print((num2-num)//2)
1657290900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["-100 1\n1 1 1 -1"]
d5e09a8fb7eeeba9a41daa2b565866ba
NoteFor the first door Naruto can use energies $$$[-100, 1]$$$. The required equality does indeed hold: $$$1 \cdot (-100) + 100 \cdot 1 = 0$$$.For the second door Naruto can use, for example, energies $$$[1, 1, 1, -1]$$$. The required equality also holds: $$$1 \cdot 1 + 2 \cdot 1 + 3 \cdot 1 + 6 \cdot (-1) = 0$$$.
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $$$T$$$ rooms there. Every room has a door into it, each door can be described by the number $$$n$$$ of seals on it and their integer energies $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. All energies $$$a_i$$$ are nonzero and do not exceed $$$100$$$ by absolute value. Also, $$$n$$$ is even.In order to open a door, Naruto must find such $$$n$$$ seals with integer energies $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ that the following equality holds: $$$a_{1} \cdot b_{1} + a_{2} \cdot b_{2} + ... + a_{n} \cdot b_{n} = 0$$$. All $$$b_i$$$ must be nonzero as well as $$$a_i$$$ are, and also must not exceed $$$100$$$ by absolute value. Please find required seals for every room there.
For each door print a space separated sequence of nonzero integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$|b_{i}| \leq 100$$$, $$$b_{i} \neq 0$$$) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.
The first line contains the only integer $$$T$$$ ($$$1 \leq T \leq 1000$$$) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors. Each description starts with the line containing the only even integer $$$n$$$ ($$$2 \leq n \leq 100$$$) denoting the number of seals. The following line contains the space separated sequence of nonzero integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$|a_{i}| \leq 100$$$, $$$a_{i} \neq 0$$$) denoting the energies of seals.
standard output
standard input
PyPy 3
Python
800
train_007.jsonl
bc963f8d964bd813df4b93b899aabd32
256 megabytes
["2\n2\n1 100\n4\n1 2 3 6"]
PASSED
import os import heapq import sys,threading import math import bisect import operator from collections import defaultdict sys.setrecursionlimit(10**5) from io import BytesIO, IOBase def gcd(a,b): if b==0: return a else: return gcd(b,a%b) def power(x, p,m): res = 1 while p: if p & 1: res = (res * x) % m x = (x * x) % m p >>= 1 return res def inar(): return [int(k) for k in input().split()] def lcm(num1,num2): return (num1*num2)//gcd(num1,num2) def main(): t=int(input()) for _ in range(t): n=int(input()) arr=inar() ans=[] for i in range(0,n,2): two=arr[i+1] one=arr[i] if (one>0 and two>0) or (one<0 and two<0): two=-1*(abs(two)) ans.append(two) ans.append(abs(one)) else: ans.append(abs(two)) ans.append(abs(one)) print(*ans) 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() #threadin.Thread(target=main).start()
1603623900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["aa.b\nc.hg", "a!aa", "aa|a"]
0f04f757dc734208d803ee0f6be5d1f0
null
BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol d is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the n / 2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line.Help BerOilGasDiamondBank and construct the required calendar.
Print n / 2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "&lt;" operator in the modern programming languages.
The first line contains an integer n (1 ≤ n ≤ 104, n is even) which is the number of branches. Then follow n lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol d (d has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.
standard output
standard input
Python 3
Python
2,000
train_011.jsonl
6cb1e2e7ed501c72f2001529ed268681
256 megabytes
["4\nb\naa\nhg\nc\n.", "2\naa\na\n!", "2\naa\na\n|"]
PASSED
n = int(input()) a = [] for i in range(10): a.append([]) res = 0 for i in range(n): s = input() a[len(s)-1].append(s) res += len(s) res //= (n // 2) c = input() b = [] for i in range(10): a[i].sort() b.append(0) for i in range(n // 2): cur = 'zzzzzzzzzzzzz' s = '' for j in range(10): if b[j] < len(a[j]): if (cur + c) > (a[j][b[j]] + c): cur = a[j][b[j]] t = len(cur) #print(cur) if t == res / 2: s += cur + c + a[res-t-1][b[res-t-1]+1] else: s += cur + c + a[res-t-1][b[res-t-1]] b[t-1] += 1 b[res-t-1] += 1 #print(b, a) print(s) #print(a, res)
1296489600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
5 seconds
["2\n1110\n1011", "1\n101001", "2\n111100\n110110"]
a8cc83b982c1d017b68a61adcb38d1a7
null
There are $$$n$$$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $$$1$$$ to $$$n$$$.It is known that, from the capital (the city with the number $$$1$$$), you can reach any other city by moving along the roads.The President of Berland plans to improve the country's road network. The budget is enough to repair exactly $$$n-1$$$ roads. The President plans to choose a set of $$$n-1$$$ roads such that: it is possible to travel from the capital to any other city along the $$$n-1$$$ chosen roads, if $$$d_i$$$ is the number of roads needed to travel from the capital to city $$$i$$$, moving only along the $$$n-1$$$ chosen roads, then $$$d_1 + d_2 + \dots + d_n$$$ is minimized (i.e. as minimal as possible). In other words, the set of $$$n-1$$$ roads should preserve the connectivity of the country, and the sum of distances from city $$$1$$$ to all cities should be minimized (where you can only use the $$$n-1$$$ chosen roads).The president instructed the ministry to prepare $$$k$$$ possible options to choose $$$n-1$$$ roads so that both conditions above are met.Write a program that will find $$$k$$$ possible ways to choose roads for repair. If there are fewer than $$$k$$$ ways, then the program should output all possible valid ways to choose roads.
Print $$$t$$$ ($$$1 \le t \le k$$$) — the number of ways to choose a set of roads for repair. Recall that you need to find $$$k$$$ different options; if there are fewer than $$$k$$$ of them, then you need to find all possible different valid options. In the following $$$t$$$ lines, print the options, one per line. Print an option as a string of $$$m$$$ characters where the $$$j$$$-th character is equal to '1' if the $$$j$$$-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the $$$t$$$ lines should be different. Since it is guaranteed that $$$m \cdot k \le 10^6$$$, the total length of all the $$$t$$$ lines will not exceed $$$10^6$$$. If there are several answers, output any of them.
The first line of the input contains integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2\cdot10^5, n-1 \le m \le 2\cdot10^5, 1 \le k \le 2\cdot10^5$$$), where $$$n$$$ is the number of cities in the country, $$$m$$$ is the number of roads and $$$k$$$ is the number of options to choose a set of roads for repair. It is guaranteed that $$$m \cdot k \le 10^6$$$. The following $$$m$$$ lines describe the roads, one road per line. Each line contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \ne b_i$$$) — the numbers of the cities that the $$$i$$$-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
standard output
standard input
Python 3
Python
2,100
train_040.jsonl
f918aa05780ba54adf1cd0f00e401c08
256 megabytes
["4 4 3\n1 2\n2 3\n1 4\n4 3", "4 6 3\n1 2\n2 3\n1 4\n4 3\n2 4\n1 3", "5 6 2\n1 2\n1 3\n2 4\n2 5\n3 4\n3 5"]
PASSED
from math import inf nmk = list(map(int, input().split(' '))) n = nmk[0] m = nmk[1] k = nmk[2] a = [] for i in range(m): a.append(list(map(int, input().split(' ')))) smej = [[] for j in range(n)] nums = {} t = 0 for i in a: nums.update({(i[0], i[1]):t}) t += 1 smej[i[0]-1].append(i[1]-1) smej[i[1]-1].append(i[0]-1) dists = [inf for i in range(n)] dists[0] = 0 q = [0] while len(q) > 0: u = q.pop(0) for i in smej[u]: if (dists[i] == inf): q.append(i) dists[i] = dists[u] + 1 p = [[] for i in range(n)] for i in range(1, n): for j in smej[i]: if(dists[j] == dists[i]-1): try: p[i].append(nums[(j+1,i+1)]) except: p[i].append(nums[(i+1,j+1)]) am = 1 p.pop(0) for i in range(len(p)): am *= len(p[i]) if(am < k): print(am) else: print(k) f = [0 for i in range(len(p))] ans = [] for i in range(k): s = ['0'for i in range(m)] for j in range(len(p)): s[p[j][f[j]]] = '1' s = ''.join(s) ans.append(s) ok = False first = True for j in range(len(p)-1, -1, -1): if first: first = False if(f[j]+1 == len(p[j])): if(j == 0): ok = True break f[j] = 0 f[j-1]+= 1 else: f[j]+= 1 break else: if(f[j] == len(p[j])): if(j == 0): ok = True break else: f[j] = 0 f[j-1] += 1 if ok: break for j in range(len(ans)): print(ans[j])
1531150500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]