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
["6", "0", "1"]
47bc3dac92621d2c7ea7d7d6036c2652
NoteIn first sample test case the good paths are: 2 → 1 → 3 → 1 → 4 → 1 → 5, 2 → 1 → 3 → 1 → 5 → 1 → 4, 2 → 1 → 4 → 1 → 5 → 1 → 3, 3 → 1 → 2 → 1 → 4 → 1 → 5, 3 → 1 → 2 → 1 → 5 → 1 → 4, 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: 2 → 1 → 4 → 1 → 3 → 1 → 5, 2 → 1 → 5 → 1 → 3 → 1 → 4, 2 → 1 → 5 → 1 → 4 → 1 → 3, 3 → 1 → 4 → 1 → 2 → 1 → 5, 3 → 1 → 5 → 1 → 2 → 1 → 4, 4 → 1 → 3 → 1 → 2 → 1 → 5, and all the paths in the other direction. Thus, the answer is 6.In the second test case, Igor simply can not walk by all the roads.In the third case, Igor walks once over every road.
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherlandΒ β€” Uzhlyandia.It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia.Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help IgorΒ β€” calculate the number of good paths.
Print out the only integerΒ β€” the number of good paths in Uzhlyandia.
The first line contains two integers n, m (1 ≀ n, m ≀ 106)Β β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself.
standard output
standard input
PyPy 2
Python
2,100
train_005.jsonl
939959d878d12df5441a1b144a2f225d
256 megabytes
["5 4\n1 2\n1 3\n1 4\n1 5", "5 3\n1 2\n2 3\n4 5", "2 2\n1 1\n1 2"]
PASSED
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 m = inp[ii]; ii += 1 special = 0 found = [1]*n coupl = [[] for _ in range(n)] for _ in range(m): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 found[u] = 0 found[v] = 0 if u != v: coupl[u].append(v) coupl[v].append(u) else: special += 1 root = 0 while found[root]: root += 1 found[root] = 1 bfs = [root] for node in bfs: for nei in coupl[node]: if not found[nei]: found[nei] = 1 bfs.append(nei) if all(found): print sum(len(c)*(len(c) - 1) for c in coupl)//2 + \ special * (special - 1)//2 + \ special * (m - special) else: print 0
1490803500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["3 6\n5 1\n2 4", "4 5\n1 6\n2 7\n3 8"]
47a9d72651f1407de89e28fb4b142367
NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $$$z = 0$$$ plane). Note that order of removing matters: for example, points $$$5$$$ and $$$1$$$ don't form a perfectly balanced pair initially, but they do after point $$$3$$$ is removed.
This is an easier version of the problem. In this version, $$$n \le 2000$$$.There are $$$n$$$ distinct points in three-dimensional space numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th point has coordinates $$$(x_i, y_i, z_i)$$$. The number of points $$$n$$$ is even.You'd like to remove all $$$n$$$ points using a sequence of $$$\frac{n}{2}$$$ snaps. In one snap, you can remove any two points $$$a$$$ and $$$b$$$ that have not been removed yet and form a perfectly balanced pair. A pair of points $$$a$$$ and $$$b$$$ is perfectly balanced if no other point $$$c$$$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$.Formally, point $$$c$$$ lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$ if and only if $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$, and $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Note that the bounding box might be degenerate. Find a way to remove all points in $$$\frac{n}{2}$$$ snaps.
Output $$$\frac{n}{2}$$$ pairs of integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting the indices of points removed on snap $$$i$$$. Every integer between $$$1$$$ and $$$n$$$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ is even), denoting the number of points. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$), denoting the coordinates of the $$$i$$$-th point. No two points coincide.
standard output
standard input
PyPy 3
Python
1,700
train_015.jsonl
a907bbeaa23cc60df6412d4fc2407035
512 megabytes
["6\n3 1 0\n0 3 0\n2 2 0\n1 0 0\n1 3 0\n0 1 0", "8\n0 1 1\n1 0 1\n1 1 0\n1 1 1\n2 2 2\n3 2 2\n2 3 2\n2 2 3"]
PASSED
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element) #from bisect import bisect_right as br #c++ upperbound br(array,element) #from __future__ import print_function, division #while using python2 import math def modinv(n,p): return pow(n,p-2,p) def dist(x1, y1, z1, x2, y2, z2): # return math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2) return abs(x2 - x1) + abs(y2 - y1) + abs(z2 - z1) def main(): #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') n = int(input()) points = [] for i in range(n): pts = [int(x) for x in input().split()] pts.append(i) points.append(pts) answers = [] visited = [0] * (n+1) # print(points) for i in range(n): if visited[i] == 1: continue min_d = 1e18 min_j = -1 x1, y1, z1, temp = points[i] for j in range(i+1,n): if visited[j] == 1: continue x2, y2, z2, temp2 = points[j] if dist(x1, y1, z1, x2, y2, z2) < min_d: min_d = dist(x1, y1, z1, x2, y2, z2) min_j = j if min_j != -1: answers.append([points[i][-1], points[min_j][-1]]) visited[points[i][-1]] = 1 visited[points[min_j][-1]] = 1 # print(answers) for p in answers: print(p[0] + 1, p[1] + 1) #------------------ Python 2 and 3 footer by Pajenegod and c1729----------------------------------------- py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') if __name__ == '__main__': main()
1571236500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["36", "1000000006"]
cf210ef68d0525dcb1574f450773da39
NoteIn the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.In the second test case, the numbers written on the first row are 3, 7, 5 and 2.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
Karen has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.
Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.
The first line of input contains a single integer n (1 ≀ n ≀ 200000), the number of numbers written on the first row. The next line contains n integers. Specifically, the i-th one among these is ai (1 ≀ ai ≀ 109), the i-th number on the first row.
standard output
standard input
PyPy 3
Python
2,200
train_005.jsonl
8abdcb045e21c37463a7cb2a9ef1d377
512 megabytes
["5\n3 6 9 12 15", "4\n3 7 5 2"]
PASSED
from sys import exit, stdin, stdout n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] if n == 1: print(a[0]) exit(0) mod = 1000000007 f = [0] * (n + 1) f[0] = 1 for i in range(1, n + 1): f[i] = (f[i-1] * i) % mod def f_pow(a, k): if k == 0: return 1 if k % 2 == 1: return f_pow(a, k - 1) * a % mod else: return f_pow(a * a % mod, k // 2) % mod def c(n, k): d = f[k] * f[n - k] % mod return f[n] * f_pow(d, mod - 2) % mod oper = 1 while not (oper and n % 2 == 0): for i in range(n - 1): a[i] = a[i] + oper * a[i + 1] oper *= -1 n -= 1 oper *= 1 if (n//2 % 2) != 0 else -1 sm1 = 0 sm2 = 0 for i in range(n): if i % 2 == 0: sm1 = (sm1 + c(n // 2 - 1, i // 2) * a[i]) % mod else: sm2 = (sm2 + c(n // 2 - 1, i // 2) * a[i]) % mod stdout.write(str((sm1 + oper * sm2) % mod))
1497710100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n1 3 10", "0", "2\n1 2 60\n3 4 50"]
e83a8bfabd7ea096fae66dcc8c243be7
null
The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
Print integer t in the first line β€” the number of tank-tap pairs of houses. For the next t lines, print 3 integers per line, separated by spaces: tanki, tapi, and diameteri, where tanki ≠ tapi (1 ≀ i ≀ t). Here tanki and tapi are indexes of tank and tap houses respectively, and diameteri is the maximum amount of water that can be conveyed. All the t lines should be ordered (increasingly) by tanki.
The first line contains two space-separated integers n and p (1 ≀ n ≀ 1000, 0 ≀ p ≀ n) β€” the number of houses and the number of pipes correspondingly. Then p lines follow β€” the description of p pipes. The i-th line contains three integers ai bi di, indicating a pipe of diameter di going from house ai to house bi (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ di ≀ 106). It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.
standard output
standard input
Python 3
Python
1,400
train_011.jsonl
f94278a7d072af5b5edefbaf175bea40
256 megabytes
["3 2\n1 2 10\n2 3 20", "3 3\n1 2 20\n2 3 10\n3 1 5", "4 2\n1 2 60\n3 4 50"]
PASSED
houses, pipes = [int(x) for x in input().strip().split()] houseToHouseDict = {} pipeDict = {} outgoingList = [] incomingList = [] maxFlow = 0 def DFSmaxPipe(origin): end = [] lowestDiam = maxFlow while (origin in houseToHouseDict): diam = pipeDict[origin] if diam < lowestDiam: lowestDiam = diam origin = houseToHouseDict[origin] end.append(origin) end.append(lowestDiam) return end for x in range(pipes): ahouse, bhouse, diameter = [int(x) for x in input().strip().split()] pipeDict[ahouse] = diameter houseToHouseDict[ahouse] = bhouse outgoingList.append(ahouse) incomingList.append(bhouse) if diameter > maxFlow: maxFlow = diameter for pipe in incomingList: try: outgoingList.remove(pipe) except ValueError: pass outgoingList.sort() print(len(outgoingList)) for origin in outgoingList: outString = str(origin) endPipe = DFSmaxPipe(origin) outString += " " + str(endPipe[0]) + " " + str(endPipe[1]) print(outString)
1314111600
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["-1\nabaacba\nxdd"]
b9f0c38c6066bdafa2e4c6daf7f46816
NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.
You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.
Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).
standard output
standard input
PyPy 3
Python
900
train_039.jsonl
2eb95efda9fb78315571a2fc6ecfcec6
256 megabytes
["3\naa\nabacaba\nxdd"]
PASSED
for i in range(int(input())): k=input() if len(set(k))==1: print("-1") continue else: r = ''.join(sorted(k)) print(str(r))
1544884500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\nR 2\nR 5", "2\nL 4\nL 2", "0"]
6ca35987757bf64860eb08f98a9e6d90
NoteFor the first example the following operations are performed:abac $$$\to$$$ abacab $$$\to$$$ abacabaThe second sample performs the following operations: acccc $$$\to$$$ cccacccc $$$\to$$$ ccccaccccThe third example is already a palindrome so no operations are required.
Ringo found a string $$$s$$$ of length $$$n$$$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $$$s$$$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_2s_3 \ldots s_i$$$ ($$$i - 1$$$ characters) reversed to the front of $$$s$$$.The second operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_i s_{i + 1}\ldots s_{n - 1}$$$ ($$$n - i$$$ characters) reversed to the end of $$$s$$$.Note that characters in the string in this problem are indexed from $$$1$$$.For example suppose $$$s=$$$abcdef. If he performs the first operation with $$$i=3$$$ then he appends cb to the front of $$$s$$$ and the result will be cbabcdef. Performing the second operation on the resulted string with $$$i=5$$$ will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $$$30$$$ times. The length of the resulting palindrome must not exceed $$$10^6$$$It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.
The first line should contain $$$k$$$ ($$$0\le k \le 30$$$) Β β€” the number of operations performed. Each of the following $$$k$$$ lines should describe an operation in form L i or R i. $$$L$$$ represents the first operation, $$$R$$$ represents the second operation, $$$i$$$ represents the index chosen. The length of the resulting palindrome must not exceed $$$10^6$$$.
The only line contains the string $$$S$$$ ($$$3 \le |s| \le 10^5$$$) of lowercase letters from the English alphabet.
standard output
standard input
PyPy 2
Python
1,400
train_018.jsonl
5b623f52412e85a676279fbbc2ced8a3
256 megabytes
["abac", "acccc", "hannah"]
PASSED
from __future__ import division, print_function # import threading # threading.stack_size(2**27) import sys sys.setrecursionlimit(10**4) # sys.stdin = open('inpy.txt', 'r') # sys.stdout = open('outpy.txt', 'w') from sys import stdin, stdout import bisect #c++ upperbound import math import heapq i_m=9223372036854775807 def modinv(n,p): return pow(n,p-2,p) def cin(): return map(int,sin().split()) def ain(): #takes array as input return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) import math def GCD(x, y): x=abs(x) y=abs(y) if(min(x,y)==0): return max(x,y) while(y): x, y = y, x % y return x def Divisors(n) : l = [] for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : if (n // i == i) : l.append(i) else : l.append(i) l.append(n//i) return l prime=[] def SieveOfEratosthenes(n): global prime prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 f=[] for p in range(2, n): if prime[p]: f.append(p) return f def primeFactors(n): a=[] # Print the number of two's that divide n while n % 2 == 0: a.append(2) n = n // 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): # while i divides n , print i ad divide n while n % i== 0: a.append(i) n = n // i # Condition if n is a prime # number greater than 2 if n > 2: a.append(n) return a """*******************************************************""" def main(): s=sin() n=len(s) print(3) print("R",n-1) print("L",n) print("L",2) ######## 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 yferent 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'R' [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'R' [0]: A.append(sign*numb) return A # threading.Thread(target=main).start() if __name__== "__main__": main()
1603011900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["0111010\n1001\n0001111\n0"]
ff66c68e8f53b0c051efe5db9428e91d
Note The corresponding graph of the first test case is: $$$c_1 + c_2 = 1 + 2 = 3$$$ The corresponding graph of the second test case is: $$$c_1 + c_2 = 2 + 2 = 4$$$
You are given a connected, undirected and unweighted graph with $$$n$$$ vertices and $$$m$$$ edges. Notice the limit on the number of edges: $$$m \le n + 2$$$.Let's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. Let this value be $$$c_1$$$. Similarly, consider only the blue edges and count the number of connected components in the graph. Let this value be $$$c_2$$$.Find an assignment of colors to the edges such that the quantity $$$c_1+c_2$$$ is minimised.
For each test case, output a binary string of length $$$m$$$. The $$$i$$$-th character of the string should be 1 if the $$$i$$$-th edge should be colored red, and 0 if it should be colored blue. If there are multiple ways to assign colors to edges that give the minimum answer, you may output any.
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$n-1 \leq m \leq \min{\left(n+2,\frac{n \cdot (n-1)}{2}\right)}$$$)Β β€” the number of vertices and the number of edges respectively. $$$m$$$ lines follow. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i,v_i \le n$$$, $$$u_i \ne v_i$$$) denoting that the $$$i$$$-th edge goes between vertices $$$u_i$$$ and $$$v_i$$$. The input is guaranteed to have no multiple edges or self loops. The graph is also guaranteed to be connected. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^6$$$.
standard output
standard input
PyPy 3-64
Python
2,000
train_106.jsonl
bf4d729b549b5c82799ee5e20b7011f1
256 megabytes
["4\n\n5 7\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n5 1\n\n1 3\n\n3 5\n\n4 4\n\n1 2\n\n2 3\n\n1 4\n\n3 4\n\n6 7\n\n1 2\n\n1 3\n\n3 4\n\n4 5\n\n1 4\n\n5 6\n\n6 2\n\n2 1\n\n1 2"]
PASSED
import random import sys input = sys.stdin.readline class DSU: def __init__(self, n): self.p = [i for i in range(n)] self.size = [1]*n def find(self, x): root = x while root != self.p[root]: root = self.p[root] while x != self.p[x]: tmp = x self.p[tmp] = root x = self.p[x] return root def union(self, x, y): if self.size[x] < self.size[y]: x, y = y, x pa, pb = self.find(x), self.find(y) if pa == pb: return False self.p[pb] = pa self.size[pa] += self.size[pb] return True def solve(): n, m = map(int, input().split()) dsu = DSU(n+1) re, be = [], [] rs = set() ans = ["0"]*m for i in range(m): u, v = map(int, input().split()) if dsu.union(u, v): be.append((i, u, v)) else: re.append((i, u, v)) rs.add(u) rs.add(v) ans[i] = "1" if len(rs) == 3: idx, i, j = re[0] ans[idx] = "0" be.append((idx, i, j)) m = len(be) dsu = DSU(n+1) for i in range(m-1, -1, -1): idx, u, v = be[i] if dsu.union(u, v): continue ans[idx] = "1" return "".join(ans) for _ in range(int(input())): print(solve())
1662474900
[ "probabilities", "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 1, 0, 1 ]
2 seconds
["0", "1", "6"]
686b6ff777d8047cdf98813fcd5192c5
NoteIn the first sample, there are $$$4$$$ contestants, arranged as follows. There is only one way to choose four contestants, with one pole held by contestants aged $$$1$$$ and $$$2$$$ and the other one by contestants aged $$$3$$$ and $$$4$$$. But then, as we can see in the picture, the poles cross. Since there is no valid way to choose four contestants, the answer is $$$0$$$.In the second sample, the $$$4$$$ contestants are arranged as follows. Once again, there is only one way to choose four contestants, but this time the poles don't cross. Therefore, the answer is $$$1$$$.In the third sample, the $$$9$$$ contestants are arranged as follows. There are $$$6$$$ ways of choosing four contestants so that the poles don't cross, as shown in the following pictures.
Today, like every year at SWERC, the $$$n^2$$$ contestants have gathered outside the venue to take a drone photo. Jennifer, the social media manager for the event, has arranged them into an $$$n\times n$$$ square. Being very good at her job, she knows that the contestant standing on the intersection of the $$$i$$$-th row with the $$$j$$$-th column is $$$a_{i,j}$$$ years old. Coincidentally, she notices that no two contestants have the same age, and that everyone is between $$$1$$$ and $$$n^2$$$ years old.Jennifer is planning to have some contestants hold a banner with the ICPC logo parallel to the ground, so that it is clearly visible in the aerial picture. Here are the steps that she is going to follow in order to take the perfect SWERC drone photo. First of all, Jennifer is going to select four contestants standing on the vertices of an axis-aligned rectangle. Then, she will have the two younger contestants hold one of the poles, while the two older contestants will hold the other pole. Finally, she will unfold the banner, using the poles to support its two ends. Obviously, this can only be done if the two poles are parallel and do not cross, as shown in the pictures below. Being very indecisive, Jennifer would like to try out all possible arrangements for the banner, but she is worried that this may cause the contestants to be late for the competition. How many different ways are there to choose the four contestants holding the poles in order to take a perfect photo? Two choices are considered different if at least one contestant is included in one but not the other.
Print the number of ways for Jennifer to choose the four contestants holding the poles.
The first line contains a single integer $$$n$$$ ($$$2\le n \le 1500$$$). The next $$$n$$$ lines describe the ages of the contestants. Specifically, the $$$i$$$-th line contains the integers $$$a_{i,1},a_{i,2},\ldots,a_{i,n}$$$ ($$$1\le a_{i,j}\le n^2$$$). It is guaranteed that $$$a_{i,j}\neq a_{k,l}$$$ if $$$i\neq k$$$ or $$$j\neq l$$$.
standard output
standard input
PyPy 3-64
Python
-1
train_085.jsonl
0f4996c2c0af3250841c889a5da84383
512 megabytes
["2\n1 3\n4 2", "2\n3 2\n4 1", "3\n9 2 4\n1 5 3\n7 8 6"]
PASSED
# ''' # FASTIO BEGINS --------------------> import atexit,io,os,sys ss=io.BytesIO() _write=ss.write ss.write=lambda sett:_write(sett.encode()) atexit.register(lambda:os.write(1,ss.getvalue())) y_in=open(0).read().split("\n") def y_inf(): for y_id in range(len(y_in)): yield y_id y_ino=y_inf() input=lambda:y_in[next(y_ino)] # FASTIO ENDS <------------------------ ''' n = int(input()) order = [(0,0)] * (n * n) for i in range(n): curr = (list(map(int, input().split()))) for j in range(n): order[curr[j] - 1] = (i, j) row_count = [0] * n col_count = [0] * n ct = 0 for i, j in order: ct += row_count[i] * col_count[j] row_count[i] += 1 col_count[j] += 1 n2 = (n * n - n)//2 ct -= n2 * n2 print(n2 * n2 - ct)
1650798300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n4\n0\n0"]
c05426881a7dccc1aa79608b612290a7
NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"! In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$.
There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.
For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.
The first line of the input contains one integer $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) β€” the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\cdot{10}^{5}$$$.
standard output
standard input
PyPy 3-64
Python
800
train_086.jsonl
76b972cb9757b51f0edb356d0a04c722
256 megabytes
["4\n3\n000\n111\n4\n1111\n1111\n3\n010\n010\n5\n11001\n00000"]
PASSED
def solve(): n = int(input()) e = list(input()) g = list(input()) e.insert(0,"0") e.insert(n+1,"0") # print(e) c = 0 for i in range(0,n): if g[i] == "1": if e[i+1] == "0": c+=1 elif e[i] =="1": c+=1 e[i] = "2" elif e[i+2] =="1": c+=1 e[i+2] = "2" print(c) case = int(input()) for _ in range(case): solve()
1627828500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["3.4142135624 -1.4142135624\n2.0000000000 0.0000000000\n0.5857864376 -1.4142135624", "1.0000000000 -1.0000000000"]
3d8aa764053d3cf14f34f11de61d1816
NoteIn the first test note the initial and the final state of the wooden polygon. Red Triangle is the initial state and the green one is the triangle after rotation around $$$(2,0)$$$.In the second sample note that the polygon rotates $$$180$$$ degrees counter-clockwise or clockwise direction (it does not matter), because Hag's father makes sure that the polygon is stable and his son does not trick him.
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with $$$n$$$ vertices.Hag brought two pins and pinned the polygon with them in the $$$1$$$-st and $$$2$$$-nd vertices to the wall. His dad has $$$q$$$ queries to Hag of two types. $$$1$$$ $$$f$$$ $$$t$$$: pull a pin from the vertex $$$f$$$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $$$t$$$. $$$2$$$ $$$v$$$: answer what are the coordinates of the vertex $$$v$$$. Please help Hag to answer his father's queries.You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.
The output should contain the answer to each query of second typeΒ β€” two numbers in a separate line. Your answer is considered correct, if its absolute or relative error does not exceed $$$10^{-4}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}$$$
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$3\leq n \leq 10\,000$$$, $$$1 \leq q \leq 200000$$$)Β β€” the number of vertices in the polygon and the number of queries. The next $$$n$$$ lines describe the wooden polygon, the $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$|x_i|, |y_i|\leq 10^8$$$)Β β€” the coordinates of the $$$i$$$-th vertex of the polygon. It is guaranteed that polygon is strictly convex and the vertices are given in the counter-clockwise order and all vertices are distinct. The next $$$q$$$ lines describe the queries, one per line. Each query starts with its type $$$1$$$ or $$$2$$$. Each query of the first type continues with two integers $$$f$$$ and $$$t$$$ ($$$1 \le f, t \le n$$$)Β β€” the vertex the pin is taken from, and the vertex the pin is put to and the polygon finishes rotating. It is guaranteed that the vertex $$$f$$$ contains a pin. Each query of the second type continues with a single integer $$$v$$$ ($$$1 \le v \le n$$$)Β β€” the vertex the coordinates of which Hag should tell his father. It is guaranteed that there is at least one query of the second type.
standard output
standard input
Python 3
Python
2,600
train_070.jsonl
121272df9e79adc0a8835b8b1cb2b6d3
256 megabytes
["3 4\n0 0\n2 0\n2 2\n1 1 2\n2 1\n2 2\n2 3", "3 2\n-1 1\n0 0\n1 1\n1 1 2\n2 1"]
PASSED
import math; #ВычислСниС ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ Ρ‚ΠΎΡ‡ΠΊΠΈ ΠΏΠΎ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Π°ΠΌ Ρ†Π΅Π½Ρ‚Ρ€Π°, ΡƒΠ³Π»Ρƒ, ΠΈ Π½Π°Ρ‡Π°Π»ΡŒΠ½Ρ‹ΠΌ ΠΎΡ‚Π½ΠΎΡΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎ Ρ†Π΅Π½Ρ‚Ρ€Π° def getCoordinate(gx, gy, alpha, x, y): x1=gx+x*math.cos(alpha)-y*math.sin(alpha); y1=gy+x*math.sin(alpha)+y*math.cos(alpha); return x1, y1 #ВычислСниС ΡƒΠ³Π»Π°, Π½Π° ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π½Π°Π΄ΠΎ ΠΏΠΎΠ²Π΅Ρ€Π½ΡƒΡ‚ΡŒ Ρ‚ΠΎΡ‡ΠΊΡƒ с ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Π°ΠΌΠΈ x, y, #Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΎΠ½Π° оказалась прямо Π½Π°Π΄ gx, gy def getAngle(gx, gy, x, y): x=x-gx; y=y-gy; cos=x/math.sqrt(x**2+y**2); alpha=math.acos(cos); if y<0: alpha=-alpha; return math.pi/2-alpha; n, q = map(int, input().split(' ')); x=[0]*n; y=[0]*n; for i in range(n): x[i], y[i]=map(int, input().split(' ')); r=[0]*q; f=[0]*q; t=[0]*q; v=[0]*q; for i in range(q): l=list(map(int, input().split(' '))); r[i]=l[0]; if r[i]==1: f[i]=l[1]-1; t[i]=l[2]-1; else: v[i]=l[1]-1; gx=0; gy=0; s=0; for i in range(n): ip=i+1; if ip==n: ip=0; ds=x[i]*y[ip]-x[ip]*y[i]; s+=ds; gx+=(x[i]+x[ip])*ds; gy+=(y[i]+y[ip])*ds; s/=2; gx/=6*s; gy/=6*s; angles=[0]*n; for i in range(n): angles[i]=getAngle(gx, gy, x[i], y[i]); for i in range(n): x[i]-=gx; y[i]-=gy; alpha=0; #print('pos',gx, gy, alpha); #Π’ΠΎΡΡΡ‚Π°Π½Π°Π²Π»ΠΈΠ²Π°Ρ‚ΡŒ ΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ Ρ‚ΠΎΡ‡Π΅ΠΊ Π±ΡƒΠ΄Π΅ΠΌ ΠΏΠΎ Ρ†Π΅Π½Ρ‚Ρ€Ρƒ масс ΠΈ ΡƒΠ³Π»Ρƒ #Π£Π³ΠΎΠ» - ΠΏΠΎΠ²ΠΎΡ€ΠΎΡ‚ ΠΏΡ€ΠΎΡ‚ΠΈΠ² часовой Π²ΠΎΠΊΡ€ΡƒΠ³ Ρ†Π΅Π½Ρ‚Ρ€Π° масс fix={0, 1} for i in range(q): if r[i]==2: currX, currY = getCoordinate(gx, gy, alpha, x[v[i]], y[v[i]]); print("%.6f %.6f"%(currX, currY)) else: if len(fix)==2: fix.remove(f[i]); #print('remove',f[i]) #j - СдинствСнный элСмСнт Π² мноТСствС for j in fix: #print(j); currX, currY = getCoordinate(gx, gy, alpha, x[j], y[j]); #print('fix:', currX, currY) #dalpha=getAngle(gx, gy, currX, currY); #alpha+=dalpha; alpha=angles[j]; #Π§Ρ‚ΠΎΠ±Ρ‹ Π²Ρ‹Ρ‡ΠΈΡΠ»ΠΈΡ‚ΡŒ Π½ΠΎΠ²Ρ‹Π΅ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ g, Π½ΡƒΠ½ΠΎ ΠΏΠΎΠ²Π΅Ρ€Π½ΡƒΡ‚ΡŒ Π΅Π΅ Π½Π° ΡƒΠ³ΠΎΠ» #dalpha ΠΎΡ‚Π½ΠΎΡΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎ currX, currY gx, gy=currX, currY-math.sqrt(x[j]**2+y[j]**2); #print('pos',gx, gy, alpha/math.pi) fix.add(t[i]);
1525183500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["YES\n2", "YES\n2", "NO"]
aaca5d07795a42ecab210327c1cf6be9
null
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
The first line contains single integer n (2 ≀ n ≀ 105)Β β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices.
standard output
standard input
Python 3
Python
1,600
train_012.jsonl
0ab933a56c183a04ae5ccbef481e8ff0
256 megabytes
["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"]
PASSED
import sys n = int(sys.stdin.readline()) edges = [[int(x) for x in sys.stdin.readline().split()] for _ in range(n - 1)] colors = sys.stdin.readline().split() res = None for edge in edges: if colors[edge[0]-1] != colors[edge[1]-1]: if res is None: res = list(edge) else: res = [x for x in res if x in edge] if len(res) == 0: break if res is None: print('YES\n1') else: print('NO' if len(res) == 0 else 'YES\n' + str(res[0]))
1486042500
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
3 seconds
["40", "1", "172"]
e6e760164882b9e194a17663625be27d
null
Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.One problem with prime numbers is that there are too many of them. Let's introduce the following notation: Ο€(n)Β β€” the number of primes no larger than n, rub(n)Β β€” the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that Ο€(n) ≀ AΒ·rub(n).
If such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes).
The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of AΒ (,Β ).
standard output
standard input
Python 2
Python
1,600
train_000.jsonl
08043780201f473922d92660b64e19d0
256 megabytes
["1 1", "1 42", "6 4"]
PASSED
#!/usr/bin/env python import math def is_pal(n): if str(n) == str(n)[::-1]: return True else: return False def sieve(n, a): primos = [True]*(n+1) primos[0] = False primos[1] = False # m = int(math.sqrt(n)) c = 0 pl= 1 r = 1 for i in range(2, n): if primos[i]: c += 1 for k in range(i*i,n+1,i): primos[k] = False if is_pal(i): pl += 1 if c<=a*pl: r = i return r def pald(n): c = 0 for i in xrange(0,n + 1): if str(i) == str(i)[::-1]: c += 1 return c p,q = [int(x) for x in raw_input().split(" ")] A = p/float(q) print sieve(2000000,A) # i = 1 # c = 0 # pl = 0 # z = -1 # for i in xrange(1,len(primos)): # if primos[i]: # c += 1 # if is_pal(i): # pl += 1 # if c <= A*pl: # z = i # break # else: # print c, A, pl,i # break # print z # print i # print i # p = 0 # pl = 0 # for i in xrange(2,3000000): # if primos[i]: # p += 1 # if is_pal(primos[i]): # pl += 1 # if p > A*pl: # print i # break # i = 1 # while True: # p = sieve(i) # c = 0 # for i in xrange(len(p)): # if p[i]: # c += 1 # pl = pald(i) # if c <= A*pl: # i += 1 # else: # # i -= 1 # break # # print i # print i
1439224200
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3\n7\n2"]
a688369a2b95a8e32d00541d54f3bec6
NoteTree and best path for the first test case: $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$ Tree and best path for the second test case: $$$3 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5$$$ Tree and best path for the third test case: $$$3 \rightarrow 5 \rightarrow 2$$$
Vlad and Nastya live in a city consisting of $$$n$$$ houses and $$$n-1$$$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.Vlad lives in a house with index $$$x$$$, and Nastya lives in a house with index $$$y$$$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $$$k$$$ things that he has to do before coming to Nastya. To do the $$$i$$$-th thing, he needs to come to the $$$a_i$$$-th house, things can be done in any order. In $$$1$$$ minute, he can walk from one house to another if they are connected by a road.Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $$$a_1, a_2, \dots, a_k$$$ he can visit in any order. He can visit any house multiple times (if he wants).
Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integerΒ β€” the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.
The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of input test cases. There is an empty line before each test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) β€” the number of houses and things, respectively. The second line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) β€” indices of the houses where Vlad and Nastya live, respectively. The third line of each test case contains $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ ($$$1 \le a_i \le n$$$) β€” indices of houses Vlad need to come to do things. The following $$$n-1$$$ lines contain description of city, each line contains two integers $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) β€” indices of houses connected by road $$$j$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,800
train_092.jsonl
509b9122e18c03a856bad9279640f582
256 megabytes
["3\n\n\n\n\n3 1\n\n1 3\n\n2\n\n1 3\n\n1 2\n\n\n\n\n6 4\n\n3 5\n\n1 6 2 1\n\n1 3\n\n3 4\n\n3 5\n\n5 6\n\n5 2\n\n\n\n\n6 2\n\n3 2\n\n5 3\n\n1 3\n\n3 4\n\n3 5\n\n5 6\n\n5 2"]
PASSED
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") flag = False def go(n, x, y, G, A): A.add(y - 1) V = [False] * (n + 1) r = 0 for leaf in A: e = leaf + 1 while not V[e]: r += 1 V[e] = True e = M[e] r -= 1 d = 0 while y != x: d += 1 y = M[y] return 2*r - d T = int(input()) for _ in range(T): input() n, k = map(int, input().split()) x, y = map(int, input().split()) A = {int(e) - 1 for e in input().split()} G = [[] for _ in range(n + 1)] for _ in range(n - 1): s, e = map(int, input().split(' ')) G[s].append(e) G[e].append(s) M = [None] * (n + 1) M[x] = x Q = [x] while Q: s = Q.pop() for e in G[s]: if M[e] is None: M[e] = s Q.append(e) print(go(n, x, y, M, A))
1651761300
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["-1", "2 1", "2 1 4 3"]
204ba74195a384c59fb1357bdd71e16c
null
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≀ i ≀ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β€” permutation p, that is perfect. Separate printed numbers by whitespaces.
A single line contains a single integer n (1 ≀ n ≀ 100) β€” the permutation size.
standard output
standard input
PyPy 2
Python
800
train_005.jsonl
740a2db6ab0dc489cc5f948c06921542
256 megabytes
["1", "2", "4"]
PASSED
import bisect from collections import defaultdict from collections import deque import math import re import sys import itertools def ni(): return int(raw_input()) def nis(): return map(int, raw_input().split()) def si(): return raw_input() def sis(): return raw_input().split() def spaced(a): return ' '.join(map(str, a)) n = ni() if n % 2: print -1 else: a = range(1, n + 1) for i in range(0, n - 1, 2): a[i], a[i + 1] = a[i + 1], a[i] print spaced(a)
1349969400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3\n1\n2\n0"]
0816295355375a2d3f1cd45852b86360
NoteIn the first query there are only three appropriate character builds: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ and $$$(9, 3)$$$. All other builds are either too smart or don't use all free points.In the second query there is only one possible build: $$$(2, 1)$$$.In the third query there are two appropriate builds: $$$(7, 6)$$$, $$$(8, 5)$$$.In the fourth query all builds have too much brains.
You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.
Print $$$T$$$ integers β€” one per query. For each query print the number of different character builds you can create.
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of queries. Next $$$T$$$ lines contain descriptions of queries β€” one per line. This line contains three integers $$$str$$$, $$$int$$$ and $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) β€” the initial strength and intelligence of the character and the number of free points, respectively.
standard output
standard input
Python 3
Python
1,300
train_000.jsonl
7ad112370a4a1cf9b8833f29951d15d3
256 megabytes
["4\n5 3 4\n2 1 0\n3 5 5\n4 10 6"]
PASSED
n = int(input()) i = 0 while i < n: ar = list(map(int, input().split())) if ar[0] < ar[1]: diff = ar[1] - ar[0] if diff >= ar[2]: print(0) else: print(int((ar[2] - diff + 1) / 2)) else: diff = ar[0] - ar[1] if diff > ar[2]: print(ar[2] + 1) else: print(ar[2] - int((ar[2] - diff) / 2)) i += 1
1567694100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["5\n2\n2\n0\n4\n4\n1000000000\n0"]
0a05b11307fbb2536f868acf4e81c1e2
NotePossible arrays for the first three test cases (in each array the median is underlined): In the first test case $$$[\underline{5}]$$$ In the second test case $$$[\underline{2}, 3]$$$ In the third test case $$$[1, \underline{2}, 2]$$$
You are given two positive integers $$$n$$$ and $$$s$$$. Find the maximum possible median of an array of $$$n$$$ non-negative integers (not necessarily distinct), such that the sum of its elements is equal to $$$s$$$.A median of an array of integers of length $$$m$$$ is the number standing on the $$$\lceil {\frac{m}{2}} \rceil$$$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $$$1$$$. For example, a median of the array $$$[20,40,20,50,50,30]$$$ is the $$$\lceil \frac{m}{2} \rceil$$$-th element of $$$[20,20,30,40,50,50]$$$, so it is $$$30$$$. There exist other definitions of the median, but in this problem we use the described definition.
For each test case print a single integerΒ β€” the maximum possible median.
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€” the number of test cases. Description of the test cases follows. Each test case contains a single line with two integers $$$n$$$ and $$$s$$$ ($$$1 \le n, s \le 10^9$$$)Β β€” the length of the array and the required sum of the elements.
standard output
standard input
PyPy 3-64
Python
800
train_091.jsonl
cd318d7b099065409e578b7411364314
256 megabytes
["8\n1 5\n2 5\n3 5\n2 1\n7 17\n4 14\n1 1000000000\n1000000000 1"]
PASSED
t = int(input()) for _ in range(t): n,s = map(int,input().split()) if n%2 != 0: res = s//(n-(n//2)) else: res = s//(n//2+1) print(res)
1631457300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["0 0", "0 1", "2 1"]
01adc5002997b7f5c79eeb6d9b3dc60b
NoteIn the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
Some time ago Mister B detected a strange signal from the space, which he started to study.After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.Let's define the deviation of a permutation p as .Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.Let's denote id k (0 ≀ k &lt; n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: k = 0: shift p1, p2, ... pn, k = 1: shift pn, p1, ... pn - 1, ..., k = n - 1: shift p2, p3, ... pn, p1.
Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.
First line contains single integer n (2 ≀ n ≀ 106) β€” the length of the permutation. The second line contains n space-separated integers p1, p2, ..., pn (1 ≀ pi ≀ n)Β β€” the elements of the permutation. It is guaranteed that all elements are distinct.
standard output
standard input
PyPy 2
Python
1,900
train_023.jsonl
df92ab11bbf0d6b260f4ffb691521c1e
256 megabytes
["3\n1 2 3", "3\n2 3 1", "3\n3 2 1"]
PASSED
def main(): n=input() A=list(map(int,raw_input().strip().split(' '))) #for i in range(len(A)): # A[i]-=1 ans=0 pos=0 neg=0 change=[0 for i in range(len(A))] for i in range(len(A)): ans+=abs(A[i]-i-1) if A[i]-1-i>0: pos+=1 else: neg+=1 if A[i]-i-1>0: change[i]=A[i]-i-1 elif A[i]==i+1: change[i]=0 else: if A[i]!=1: change[i]=A[i]+n-i-1 else: change[i]=0 MIN=ans index=0 #print(ans) collect=[0 for i in range(n)] for x in range(len(change)): collect[change[x]]+=1 #print(collect) #print(ans,pos,neg) for s in range(1,n): ans-=abs(A[n-s]-n+1-1) ans+=abs(A[n-s]-0-1) neg-=1 ans-=pos ans+=neg if A[n-s]>1: pos+=1 else: neg+=1 pos-=(collect[s]) neg+=(collect[s]) #print(ans,pos,neg) if ans<MIN: MIN=ans index=s print MIN,index #brutal(A) main()
1498574100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n1 \n4\n1 4 3 2"]
61ba68bdc7a1e3c60135cbae30d9e088
NoteIn the first example, we get sum is $$$a_1 = 0$$$.In the second example, we get sum is $$$a_1 + a_4 + a_3 + a_2 = 0$$$.
You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, such that for each $$$1\le i \le n$$$ holds $$$i-n\le a_i\le i-1$$$.Find some nonempty subset of these integers, whose sum is equal to $$$0$$$. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.
For each test case, output two lines. In the first line, output $$$s$$$ ($$$1\le s \le n$$$)Β β€” the number of elements in your subset. In the second line, output $$$s$$$ integers $$$i_1, i_2, \dots, i_s$$$ ($$$1\le i_k \le n$$$). All integers have to be pairwise different, and $$$a_{i_1} + a_{i_2} + \dots + a_{i_s}$$$ has to be equal to $$$0$$$. If there are several possible subsets with zero-sum, you can find any of them.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^6$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n \le 10^6$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$i-n \le a_i \le i-1$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
PyPy 2
Python
2,700
train_013.jsonl
d135a5c8f908de090baae828a5b46319
256 megabytes
["2\n5\n0 1 2 3 4\n4\n-3 1 1 1"]
PASSED
from sys import stdin, stdout t = input() inp = stdin.readlines() out = [] for itr in xrange(t): n = int(inp[itr << 1].strip()) a = map(int, inp[itr << 1 | 1].strip().split()) found = -1 for i in xrange(n): if a[i] == 0: found = i break else: a[i] = i + 1 - a[i] if found != -1: out.append("1") out.append(str(found + 1)) continue vis = [0] * n i = 0 idxlist = [] start = 0 while vis[i] == 0: vis[i] = 1 i = a[i] - 1 if vis[i] == 1: start = i idxlist.append(str(start + 1)) i = a[start] - 1 while i != start: idxlist.append(str(i + 1)) i = a[i] - 1 out.append(str(len(idxlist))) out.append(" ".join(idxlist)) stdout.write("\n".join(out))
1577628300
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
1 second
["0\n1\n0\n4\n0\n36\n665702330"]
0b718a81787c3c5c1aa5b92834ee8bf5
NoteIn first test case, we only have one permutation which is $$$[1]$$$ but it is not beautiful because $$$\gcd(1 \cdot 1) = 1$$$.In second test case, we only have one beautiful permutation which is $$$[2, 1]$$$ because $$$\gcd(1 \cdot 2, 2 \cdot 1) = 2$$$.
Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $$$n$$$ is a permutation that has the following property: $$$$$$ \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) &gt; 1, $$$$$$ where $$$\gcd$$$ is the greatest common divisor.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 one integer β€” number of beautiful permutations. Because the answer can be very big, please print the answer modulo $$$998\,244\,353$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) β€” the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^3$$$).
standard output
standard input
Python 3
Python
800
train_095.jsonl
d010c0b118b5b7a671b840b994bef607
256 megabytes
["7\n1\n2\n3\n4\n5\n6\n1000"]
PASSED
import sys import math import bisect import heapq input = sys.stdin.readline print = sys.stdout.write t = int(input()) def solve(): # input init. # input() # num n=int(input()) # x,d=map(int, input().split()) # string # s=input().rstrip('\n') # c=input().rstrip('\n') # list # l=list(map(int,input().split())) # l=input().split() # matrix # matrix=[list(map(int,input().split())) for _ in range(n)] # matrix=[list(map(int,list(input().rstrip('\n')))) for _ in range(n)] # solve. mod=998244353 if n%2==1: return 0 else: res=1 for i in range(1,n//2+1): res*=i res%=mod # return. return (res**2)%mod # solve() # print(str(solve())) for _ in range(t): print(str(solve())+'\n') # solve()
1648391700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["1\n2\n3\n4\n5\n18"]
ac7d117d58046872e9d665c9f99e5bff
null
Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.
For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).
standard output
standard input
Python 3
Python
800
train_083.jsonl
f3ad96a0228b5c8e2d623c7a502d6ee5
256 megabytes
["6\n1\n2\n3\n4\n5\n100"]
PASSED
for t in range(int(input())): n=input() print(9*(len(n)-1)+int(n)//int("1"*len(n)))
1620225300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
5 seconds
["63", "136"]
b54a045ad7beed08b94f5d31700a2d77
NoteIn the first sample:$$$\text{exlog}_f(1) = 0$$$$$$\text{exlog}_f(2) = 2$$$$$$\text{exlog}_f(3) = 3$$$$$$\text{exlog}_f(4) = 2 + 2 = 4$$$$$$\text{exlog}_f(5) = 5$$$$$$\text{exlog}_f(6) = 2 + 3 = 5$$$$$$\text{exlog}_f(7) = 7$$$$$$\text{exlog}_f(8) = 2 + 2 + 2 = 6$$$$$$\text{exlog}_f(9) = 3 + 3 = 6$$$$$$\text{exlog}_f(10) = 2 + 5 = 7$$$$$$\text{exlog}_f(11) = 11$$$$$$\text{exlog}_f(12) = 2 + 2 + 3 = 7$$$$$$ \sum_{i=1}^{12} \text{exlog}_f(i)=63 $$$In the second sample:$$$\text{exlog}_f(1) = 0$$$$$$\text{exlog}_f(2) = (1 \times 2^3 + 2 \times 2^2 + 3 \times 2 + 4) = 26$$$$$$\text{exlog}_f(3) = (1 \times 3^3 + 2 \times 3^2 + 3 \times 3 + 4) = 58$$$$$$\text{exlog}_f(4) = 2 \times \text{exlog}_f(2) = 52$$$$$$ \sum_{i=1}^4 \text{exlog}_f(i)=0+26+58+52=136 $$$
Notice: unusual memory limit!After the war, destroyed cities in the neutral zone were restored. And children went back to school.The war changed the world, as well as education. In those hard days, a new math concept was created.As we all know, logarithm function can be described as: $$$$$$ \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k $$$$$$ Where $$$p_1^{a_1}p_2^{a_2}...p_k^{a_2}$$$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.So, the mathematicians from the neutral zone invented this: $$$$$$ \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$$$$$Notice that $$$\text{exlog}_f(1)$$$ is always equal to $$$0$$$.This concept for any function $$$f$$$ was too hard for children. So teachers told them that $$$f$$$ can only be a polynomial of degree no more than $$$3$$$ in daily uses (i.e., $$$f(x) = Ax^3+Bx^2+Cx+D$$$)."Class is over! Don't forget to do your homework!" Here it is: $$$$$$ \sum_{i=1}^n \text{exlog}_f(i) $$$$$$Help children to do their homework. Since the value can be very big, you need to find the answer modulo $$$2^{32}$$$.
Print the answer modulo $$$2^{32}$$$.
The only line contains five integers $$$n$$$, $$$A$$$, $$$B$$$, $$$C$$$, and $$$D$$$ ($$$1 \le n \le 3 \cdot 10^8$$$, $$$0 \le A,B,C,D \le 10^6$$$).
standard output
standard input
Python 2
Python
2,500
train_020.jsonl
5cc0c50418f83259f104c1ab14eee224
16 megabytes
["12 0 0 1 0", "4 1 2 3 4"]
PASSED
def p1(x): if x % 2 == 0: x, y = x / 2, x + 1 else: y = (x + 1) / 2 return x*y def p2(x): y, z = x + 1, 2*x + 1 if x % 2 == 0: x /= 2 else: y /= 2 if z % 3 == 0: z /= 3 elif x % 3 == 0: x /= 3 else: y /= 3 return x * y * z def is_prime(x): i = 2 while i*i <= x: if x % i == 0: return False i += 1 return True n, A, B, C, D = map(int, raw_input().split(' ')) f, g, o = [[0]*20000 for _ in xrange(4)], [[0]*20000 for _ in xrange(4)], [0]*4 m = 1 while m * m <= n: f[0][m] = n/m - 1 f[1][m] = (p1(n/m) - 1) * C f[2][m] = (p2(n/m) - 1) * B f[3][m] = (p1(n/m)*p1(n/m) - 1) * A m += 1 for i in xrange(1, m + 1): g[0][i] = (i - 1) g[1][i] = (p1(i) - 1) * C g[2][i] = (p2(i) - 1) * B g[3][i] = (p1(i)*p1(i) - 1) * A for i in xrange(2, m + 1): if g[0][i] == g[0][i-1]: continue o[0] = 1 for w in xrange(1, 4): o[w] = o[w - 1] * i j = 1 while j <= min(m - 1, n / i / i): for w in xrange(4): if i * j < m: f[w][j] -= o[w] * (f[w][i * j] - g[w][i - 1]) else: f[w][j] -= o[w] * (g[w][n / i / j] - g[w][i - 1]) j += 1 j = m while j >= i*i: for w in xrange(4): g[w][j] -= o[w] * (g[w][j / i] - g[w][i - 1]) j -= 1 for i in xrange(1, m + 2): f[0][i] *= D g[0][i] *= D ans = 0 i = 1 while n / i > m: for w in xrange(4): ans += f[w][i] - g[w][m] i += 1 for i in xrange(2, m + 1): if is_prime(i): tmp = n while tmp != 0: ans += (A*i*i*i + B*i*i + C*i + D) * (tmp / i) tmp /= i print ans % 4294967296
1533737100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["No", "Yes\n1 2\n2 1 3"]
bb7bace930d5c5f231bfc2061576ec45
NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\mathrm{gcd}(2, 4) = 2 &gt; 1$$$, hence that is one of the possible answers.
Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) &gt; 1$$$ Here $$$\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.
If such partition doesn't exist, print "No" (quotes for clarity). Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitionsΒ β€” print any of them.
The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 45\,000$$$)
standard output
standard input
PyPy 3
Python
1,100
train_003.jsonl
bdcddfeef444530e63ef7564ca2a3437
256 megabytes
["1", "3"]
PASSED
n = int(input()) if n <3: print ("No") elif n ==3: print ("Yes") print (1,2) print (2,1,3) else: print ("Yes") print(3,1,n,n-1) print(n-3,*range(2,n-1))
1536248100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n3\n2"]
ccfe798f5dc63c492ff54cf40bb40613
NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.
Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.
For each test case, output a single integerΒ β€” the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$)Β β€” the current volume and Bob's desired volume, respectively.
standard output
standard input
Python 3
Python
800
train_014.jsonl
6b6b6578126e19d1c9e1f39b079d3a6f
256 megabytes
["3\n4 0\n5 14\n3 9"]
PASSED
for _ in range(int(input())): s = list(map(int, input().split())) t = 0 k = abs(s[1] - s[0]) a = k / 5 b = k % 5 if a == 0: if b == 0: print(int(t)) continue elif 3 > b > 0: t += 1 elif 5 > b >= 3: t += 2 else: t += a if b == 0: print(int(t)) continue elif 3 > b > 0: t += 1 elif 5 > b >= 3: t += 2 print(int(t))
1574174100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2 3 \n1 1 1 \n1 2 2 3 \n-1"]
bb9f0e0431ef4db83190afd7b9ed4496
null
You are given a simple undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Edge $$$i$$$ is colored in the color $$$c_i$$$, which is either $$$1$$$, $$$2$$$, or $$$3$$$, or left uncolored (in this case, $$$c_i = -1$$$).You need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices $$$1 \leq a &lt; b &lt; c \leq n$$$, the colors of the edges $$$a \leftrightarrow b$$$, $$$b \leftrightarrow c$$$, and $$$a \leftrightarrow c$$$ are either pairwise different, or all equal. In case no such coloring exists, you need to determine that.
For each test case, print $$$m$$$ integers $$$d_1, d_2, \ldots, d_m$$$, where $$$d_i$$$ is the color of the $$$i$$$-th edge in your final coloring. If there is no valid way to finish the coloring, print $$$-1$$$.
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10$$$): the number of test cases. The following lines contain the description of the test cases. In the first line you are given two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 64$$$, $$$0 \leq m \leq \min(256, \frac{n(n-1)}{2})$$$): the number of vertices and edges in the graph. Each of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, and $$$c_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \ne b_i$$$, $$$c_i$$$ is either $$$-1$$$, $$$1$$$, $$$2$$$, or $$$3$$$), denoting an edge between $$$a_i$$$ and $$$b_i$$$ with color $$$c_i$$$. It is guaranteed that no two edges share the same endpoints.
standard output
standard input
PyPy 3-64
Python
2,900
train_101.jsonl
70b9a88fa703c29e6e351dd22b5d56dc
256 megabytes
["4\n3 3\n1 2 1\n2 3 2\n3 1 -1\n3 3\n1 2 1\n2 3 1\n3 1 -1\n4 4\n1 2 -1\n2 3 -1\n3 4 -1\n4 1 -1\n3 3\n1 2 1\n2 3 1\n3 1 2"]
PASSED
from itertools import combinations from collections import defaultdict import io, os, sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def F1(A, B, C, D): AD = A ^ D return (AD ^ B) | (A ^ C), AD & (B ^ C) def F2(A, B, C, D): AC = A ^ C return AC | (B ^ D), (AC ^ D) & (B ^ C) def flip_bit(a, i): a[i // l] ^= (1 << (i % l)) def Gauss(a, b, n, m): if n == 0: return 2, [0] * m where = [-1] * m row, col = 0, 0 while col < m and row < n: t1, t2 = divmod(col, l) for i in range(row, n): if a[i][t1] >> t2 & 1 or b[i][t1] >> t2 & 1: a[i], a[row] = a[row], a[i] b[i], b[row] = b[row], b[i] break if not a[row][t1] >> t2 & 1 and not b[row][t1] >> t2 & 1: col += 1 continue where[col] = row for i in range(n): if i == row: continue x1, x2 = a[i][t1] >> t2 & 1, b[i][t1] >> t2 & 1 y1, y2 = a[row][t1] >> t2 & 1, b[row][t1] >> t2 & 1 cc = ((x1 + x2) * (y1 + y2)) % 3 if cc == 0: continue F = F1 if cc == 2 else F2 for k in range(t1, U): a[i][k], b[i][k] = F(a[i][k], b[i][k], a[row][k], b[row][k]) col, row = col + 1, row + 1 ans = [0] * m t1, t2 = divmod(m, l) for i in range(m): W = where[i] if W != -1: t3, t4 = divmod(i, l) x1, x2 = a[W][t1] >> t2 & 1, b[W][t1] >> t2 & 1 y1, y2 = a[W][t3] >> t4 & 1, b[W][t3] >> t4 & 1 ans[i] = ((x1 + x2) * (y1 + y2)) % 3 for i in range(n): sm = 0 for j in range(m): t3, t4 = divmod(j, l) sm += ((a[i][t3] >> t4 & 1) + (b[i][t3] >> t4 & 1)) * ans[j] if (sm - (a[i][t1] >> t2 & 1) - (b[i][t1] >> t2 & 1)) % 3 != 0: return 0, [-1] * m if -1 in where: return 2, ans return 1, ans T = int(input()) for _ in range(T): n, m = [int(i) for i in input().split()] l, U = 63, m//63 + 1 G = defaultdict(list) edges_back = {} colors = [0] * m for k in range(m): a, b, c = [int(i) for i in input().split()] G[a] += [(b, c)] G[b] += [(a, c)] edges_back[(a, b)] = (k, c) edges_back[(b, a)] = (k, c) colors[k] = c ans = set() for n1 in range(1, n + 1): neibs = G[n1] for (n2, c12), (n3, c13) in combinations(neibs, 2): if (n2, n3) in edges_back: row = [[0] * U, [0] * U] k12, _ = edges_back[(n1, n2)] k13, _ = edges_back[(n1, n3)] k23, c23 = edges_back[(n2, n3)] last = 0 for k, c in (k12, c12), (k13, c13), (k23, c23): if c != -1: last -= c else: flip_bit(row[0], k) last %= 3 if last == 1: flip_bit(row[0], m) elif last == 2: flip_bit(row[0], m) flip_bit(row[1], m) ans.add(tuple(tuple(x) for x in row)) mat1, mat2 = [], [] for x, y in ans: mat1 += [list(x)] mat2 += [list(y)] ans = Gauss(mat1, mat2, len(mat1), m) if ans[0] == 0: out = [-1] else: out = [] for i in range(m): if colors[i] != -1: out += [colors[i]] elif ans[1][i] == 0: out += [3] else: out += [ans[1][i]] print(" ".join(str(x) for x in out))
1640792100
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
1 second
["NO\nYES\nYES\nYES\nYES\nYES\nNO\nYES"]
bd61ae3c19274f47b981b8bd5e786375
NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.
Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.
For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) β€” the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$) Β β€” the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,000
train_085.jsonl
103dc2df596e1d64bd0434997fc527c4
256 megabytes
["8\n1 0 0 0\nB\n0 0 1 0\nAB\n1 1 0 1\nABAB\n1 0 1 1\nABAAB\n1 1 2 2\nBAABBABBAA\n1 1 2 3\nABABABBAABAB\n2 3 5 4\nAABAABBABAAABABBABBBABB\n1 3 3 10\nBBABABABABBBABABABABABABAABABA"]
PASSED
# test.py # main.py # .---.---.---.---.---.---.---.---.---.---.---.---.---.-------. # |1/2| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | + | ' | <- | # |---'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-----| # | ->| | Q | W | E | R | T | Y | U | I | O | P | ] | ^ | | # |-----'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'| | # | Caps | A | S | D | F | G | H | J | K | L | \ | [ | * | | # |----.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'---'----| # | | < | Z | X | C | V | B | N | M | , | . | - | | # |----'-.-'.--'--.'---'---'---'---'---'---'--.'---'.--.------| # | ctrl | | alt | | alt | | ctrl | # '------' '-----'---------------------------'-----' '------' MOD_PRIME = 10**9 + 7 def inp(to: type = str): return to(input()) def inp_arr(to: type = str): return list( map(to, inp().split())) def print_gc(t, res): print(f"Case #{t}: {res}") def fs(*args): return frozenset(args) def solve(t): crr = inp_arr(int) s = inp(str) arr, brr = [], [0]*4 i = 0 while i < len(s): if i == len(s) - 1: arr.append(s[i]) if s[i] == "A": brr[0] += 1 else: brr[1] += 1 i += 1 else: if s[i:i+2] == "AA": arr.append("A") brr[0] += 1 i += 1 elif s[i:i+2] == "BB": arr.append("B") brr[1] += 1 i += 1 elif s[i:i+2] == "AB": arr.append("AB") brr[2] += 1 i += 2 elif s[i:i+2] == "BA": arr.append("BA") brr[3] += 1 i += 2 if brr[2] < crr[2] and brr[3] < crr[3]: res = "NO" else: res = "YES" if brr[2] > crr[2] and brr[3] < crr[3]: i = 0 while i+1 < len(arr) and brr[2] > crr[2] and brr[3] < crr[3]: if arr[i] == "AB" and arr[i+1] == "A": arr[i] = "A" arr[i+1] = "BA" brr[2] -= 1 brr[3] += 1 j = i while j > 0 and all([ brr[2] > crr[2], brr[3] < crr[3], arr[j-1] == "AB", arr[j] == "A" ]): arr[j-1] = "A" arr[j] = "BA" brr[2] -= 1 brr[3] += 1 j -= 1 elif arr[i] == "B" and arr[i+1] == "AB": arr[i] = "BA" arr[i+1] = "B" brr[2] -= 1 brr[3] += 1 else: i += 1 i = 0 err = [] while i+1 < len(arr): if arr[i] == "AB" and arr[i+1] == "AB": err.append([i, 2]) j = i+1 while j+1 < len(arr) and arr[j] == "AB" and arr[j+1] == "AB": err[-1][1] += 1 j += 1 i = j i += 1 err = sorted(err, key=lambda e: e[1], reverse=True) for i, _ in err: if not(brr[2] > crr[2] and brr[3] < crr[3]): break if arr[i] == "AB" and arr[i+1] == "AB": arr.insert(i, "A") for j in range(len(err)): if i < err[j][0]: err[j][0] += 1 arr[i+1] = "BA" arr[i+2] = "B" brr[0] += 1 brr[1] += 1 brr[2] -= 2 brr[3] += 1 j = i while j >= 1 and all([ brr[2] > crr[2], brr[3] < crr[3], arr[j-1] == "AB", arr[j] == "A" ]): arr[j-1] = "A" arr[j] = "BA" brr[2] -= 1 brr[3] += 1 j -= 1 j = i+2 while j+1 < len(arr) and all([ brr[2] > crr[2], brr[3] < crr[3], arr[j] == "B", arr[j+1] == "AB" ]): arr[j] = "BA" arr[j+1] = "B" brr[2] -= 1 brr[3] += 1 j += 1 i = j-1 else: i += 1 elif brr[3] > crr[3] and brr[2] < crr[2]: i = 0 while i+1 < len(arr) and brr[3] > crr[3] and brr[2] < crr[2]: if arr[i] == "BA" and arr[i+1] == "B": arr[i] = "B" arr[i+1] = "AB" brr[3] -= 1 brr[2] += 1 j = i while j >= 1 and all([ brr[3] > crr[3], brr[2] < crr[2], arr[j-1] == "BA", arr[j] == "B" ]): arr[j-1] = "B" arr[j] = "AB" brr[3] -= 1 brr[2] += 1 j -= 1 elif arr[i] == "A" and arr[i+1] == "BA": arr[i] = "AB" arr[i+1] = "A" brr[3] -= 1 brr[2] += 1 else: i += 1 i = 0 err = [] while i+1 < len(arr): if arr[i] == "BA" and arr[i+1] == "BA": err.append([i, 2]) j = i+1 while j+1 < len(arr) and arr[j] == "BA" and arr[j+1] == "BA": err[-1][1] += 1 j += 1 i = j i += 1 err = sorted(err, key=lambda e: e[1], reverse=True) for i, _ in err: if not(brr[3] > crr[3] and brr[2] < crr[2]): break if arr[i] == "BA" and arr[i+1] == "BA": for j in range(len(err)): if i < err[j][0]: err[j][0] += 1 arr.insert(i, "B") arr[i+1] = "AB" arr[i+2] = "A" brr[0] += 1 brr[1] += 1 brr[3] -= 2 brr[2] += 1 j = i while j > 0 and all([ brr[3] > crr[3], brr[2] < crr[2], arr[j-1] == "BA", arr[j] == "B" ]): arr[j-1] = "B" arr[j] = "AB" brr[3] -= 1 brr[2] += 1 j -= 1 j = i+2 while j+1 < len(arr) and all([ brr[3] > crr[3], brr[2] < crr[2], arr[j] == "A", arr[j+1] == "BA" ]): arr[j] = "AB" arr[j+1] = "A" brr[3] -= 1 brr[2] += 1 j += 1 else: i += 1 if brr[0] > crr[0] or brr[1] > crr[1]: res = "NO" elif brr[0] - crr[0] != brr[1] - crr[1]: res = "NO" elif brr[2] >= crr[2] and brr[3] >= crr[3]: res = "YES" elif all([ brr[0] == crr[0] and brr[1] == crr[1], brr[2] != crr[2] and brr[3] != crr[3], ]): res = "NO" else: res = "NO" print(res) """ 3 7 13 4 19 AAAAAABABABABBABABABBABABABABABBBBBBBAAABABABABABABABABABBBBBBABBA 22 13 9 21 BBABABAAABABABABABABBBABABAABABABBABAABAAABAAAAAAAAABAAAABABABABAABABABABABABABBBBBBABAAABABABB 6 8 2 39 BBBBBBABABABABABABABABABABABAABABBBABABABAAABBABABAAAAABABBABABABABABABABABABABABABABABABAABBABA """ def main(): T = 1 T = inp(int) for t in range(1, T+1): solve(t) return if __name__ == "__main__": main()
1653500100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["0.3535533906", "1.0000000000"]
495488223483401ff12ae9c456b4e5fe
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is β€‰β‰ˆβ€‰0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most β€‰β‰ˆβ€‰0.3535533906.
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
The first line has one integer n (4 ≀ n ≀ 1 000)Β β€” the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≀ xi, yi ≀ 109)Β β€” the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
standard output
standard input
Python 3
Python
1,800
train_017.jsonl
2fc51ed8930c7f1ba59fb174097e96f3
256 megabytes
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
PASSED
#!/usr/bin/env python3 from decimal import Decimal def dist(a, b): x1, y1 = a x2, y2 = b return Decimal((x1-x2)**2+(y1-y2)**2).sqrt() def minh(a, b, c): m = dist(a, b) n = dist(b, c) k = dist(a, c) p = Decimal(m + n + k)/2 sqp = (p*(p-m)*(p-n)*(p-k)).sqrt() hm = (Decimal(2)/m)*sqp hn = (Decimal(2)/n)*sqp hk = (Decimal(2)/k)*sqp return min([hm, hn, hk]) def solve(): n = int(input()) coords = [] for i in range(n): coords.append(tuple(map(int, input().split()))) coords += coords res = min( minh(coords[i], coords[i+1], coords[i+2]) for i in range(n)) print(res/2) if __name__ == '__main__': solve()
1492356900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
3 seconds
["15", "0", "6"]
a764aa5727b53a6be78b1e172f670c86
NoteThe following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges.
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.You are given an undirected complete graph with $$$n$$$ nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the XOR sum of all weights would be equal to $$$0$$$.Define the ugliness of a fully-assigned complete graph the weight of its minimum spanning tree, where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible.As a reminder, an undirected complete graph with $$$n$$$ nodes contains all edges $$$(u, v)$$$ with $$$1 \le u &lt; v \le n$$$; such a graph has $$$\frac{n(n-1)}{2}$$$ edges.She is not sure how to solve this problem, so she asks you to solve it for her.
Print on one line one integer Β β€” the minimum ugliness among all weight assignments with XOR sum equal to $$$0$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1)$$$) Β β€” the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The $$$i$$$-th of the following $$$m$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$, and $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u \ne v$$$, $$$1 \le w_i &lt; 2^{30}$$$), representing the edge from $$$u_i$$$ to $$$v_i$$$ has been pre-assigned with the weight $$$w_i$$$. No edge appears in the input more than once.
standard output
standard input
PyPy 3
Python
2,500
train_087.jsonl
0995594102b4cf3054878e98d778f319
256 megabytes
["4 4\n2 1 14\n1 4 14\n3 2 15\n4 3 8", "6 6\n3 6 4\n2 4 1\n4 5 7\n3 4 10\n3 5 1\n5 2 15", "5 6\n2 3 11\n5 3 7\n1 4 10\n2 4 14\n4 3 8\n2 5 6"]
PASSED
import sys, os if os.environ['USERNAME']=='kissz': inp=open('in3.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def getp(i): L=[] while parent[i]>=0: L+=[i] i=parent[i] for j in L: parent[j]=i return i n,m=map(int,inp().split()) neighbors=[set() for _ in range(n)] G=[[] for _ in range(n)] E=[] xors=0 for _ in range(m): u,v,w=map(int,inp().split()) neighbors[u-1].add(v-1) neighbors[v-1].add(u-1) E+=[(w,v-1,u-1)] xors^=w s=0 parent=[-1]*n k=(n*(n-1))//2-m nodes=set(range(n)) conn=0 for p in range(n): if p not in nodes: continue nodes.remove(p) Q=[p] while Q: i=Q.pop() new_nodes=set() for j in nodes: if j not in neighbors[i]: parent[j]=p G[i].append((j,True)) G[j].append((i,True)) new_nodes.add(j) conn+=1 debug(i,j,0) k-=1 Q.append(j) nodes-=new_nodes debug(parent) if conn<n-1 or k==0: E.sort() for w,u,v in E: pu=getp(u) pv=getp(v) if pu!=pv: s+=w parent[pu]=pv G[u].append((v,False)) G[v].append((u,False)) conn+=1 debug(u,v,w) elif k==0 and w<xors: Q=[(u,False)] seen=[False]*n seen[u]=True while Q: i,new=Q.pop() for j,new_edge in G[i]: if not seen[j]: seen[j]=True new_edge |= new if j==v: Q=[] break else: Q.append((j,new_edge)) if new_edge: s+=w debug('corr ',u,v,w) k+=1; if conn>=n-1 and (k>0 or w>xors): break if k==0: s+=xors debug('no corr ', xors) print(s)
1618583700
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1 second
["2.0000000000", "32.8333333333"]
ffdd1de4be537234e8a0e7127bec43a7
NoteIn the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value.
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used.Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)Β·(m - r + 1) possible positions, the average number of caught fishes is as high as possible.
Print a single numberΒ β€” the maximum possible expected number of caught fishes. You answer is considered correct, is its absolute or relative error does not exceed 10 - 9. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if .
The only line contains four integers n, m, r, k (1 ≀ n, m ≀ 105, 1 ≀ r ≀ min(n, m), 1 ≀ k ≀ min(nΒ·m, 105)).
standard output
standard input
Python 3
Python
2,100
train_041.jsonl
4e1a35169bfee117f31d02d155d42d6a
256 megabytes
["3 3 2 3", "12 17 9 40"]
PASSED
import heapq as hq from queue import PriorityQueue import math n,m,r, k= input().split() N = int(n) M = int(m) R = int(r) K = int(k) q = PriorityQueue() for i in range(1,math.floor((N+1)/2) + 1): maxi = min(min(i,N-i+1),min(R,N-R+1)) * min(min(R,M-R+1),math.ceil(M/2)) num = M - (2 * min(min(R,M-R+1),math.ceil(M/2))-2) mult = 2 if(i > math.floor(N/2)): mult = 1 q.put((-maxi,num * mult,i)) #print(str(maxi) + " " + str(num) + " " + str(mult)) ans = 0 while(K > 0): pop = q.get() #print(pop) a = -1 * pop[0] b = pop[1] c = pop[2] d = min(min(c,N-c+1),min(R,N-R+1)) if(d != a): # if(q.) # if(q.get(-(a - d)) != ) mult = 2 if (c > N / 2): mult = 1 q.put((-(a - d),2*mult,c)) ans += a * min(b,K) K -= b; tot = (N-R+1) * (M-R+1) #print("ANS = " + str(ans)) #print("FINANS = " + str(ans/tot)) print(str(ans/tot)) ''' d = [] for i in range(0,N): d.append([]) for j in range(0,M): d[i].append(0) tot = 0 for i in range(0,N-R+1): for j in range(0,M-R+1): for k in range(i,i+R): for l in range(j,j+R): d[k][l] += 1 tot += 1 print((N-R+1)*(M-R+1) * (R*R)) print(tot) print() for i in d: print(i) '''
1515162900
[ "probabilities", "graphs" ]
[ 0, 0, 1, 0, 0, 1, 0, 0 ]
1 second
["1\n2\n3"]
4d5457d9f053556c78c102f5c32f7542
NoteIn the first test case, the Agent can use the second weapon, making health value of the enemy equal to $$$4-7=-3$$$. $$$-3 \le 0$$$, so the enemy is dead, and using weapon $$$1$$$ time was enough.In the second test case, the Agent can use the first weapon first, and then the second one. After this, the health of enemy will drop to $$$6-4-2 = 0$$$, meaning he would be killed after using weapons $$$2$$$ times.In the third test case, the Agent can use the weapons in order (third, first, third), decreasing the health value of enemy to $$$11 - 7 - 2 - 7 = -5$$$ after using the weapons $$$3$$$ times. Note that we can't kill the enemy by using the third weapon twice, as even though $$$11-7-7&lt;0$$$, it's not allowed to use the same weapon twice in a row.
One day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has $$$n$$$ weapons. The $$$i$$$-th weapon has a damage value $$$a_i$$$, and the Agent will face an enemy whose health value is $$$H$$$.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to $$$0$$$. However, not everything is so easy: the Agent can't choose the same weapon for $$$2$$$ times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?
For each test case, print a single integer β€” the minimum number of times that the Agent will have to use the weapons to kill the enemy.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$H$$$ $$$(2 \leq n \leq 10^3, 1 \leq H \leq 10^9)$$$ β€” the number of available weapons and the initial health value of the enemy. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$ β€” the damage values of the weapons. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
800
train_106.jsonl
2da3086f112c21ce41e9c0d366c683e5
256 megabytes
["3\n2 4\n3 7\n2 6\n4 2\n3 11\n2 1 7"]
PASSED
import sys input = sys.stdin.buffer.readline n = int(input()) for i in range (0,n): w,h = map(int,input().split()) d = input() da = list(map(int,d.split())) da.sort() ans = 0 first = da[-1] sec = da[-2] combo = int(first)+int(sec) if h >= combo: ans += 2*int((h//combo)) if h%combo>int(first): ans +=2 elif h % combo > 0: ans +=1 else: ans +=0 print(ans)
1633271700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["20", "0", "6", "19200"]
dcde114e4769f659e5a80479e033e50f
null
$$$n$$$ fishermen have just returned from a fishing vacation. The $$$i$$$-th fisherman has caught a fish of weight $$$a_i$$$.Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from $$$1$$$ to $$$n$$$). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.Suppose a fisherman shows a fish of weight $$$x$$$, and the maximum weight of a previously shown fish is $$$y$$$ ($$$y = 0$$$ if that fisherman is the first to show his fish). Then: if $$$x \ge 2y$$$, the fisherman becomes happy; if $$$2x \le y$$$, the fisherman becomes sad; if none of these two conditions is met, the fisherman stays content. Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo $$$998244353$$$.
Print one integer β€” the number of emotional orders, taken modulo $$$998244353$$$.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$).
standard output
standard input
Python 2
Python
2,600
train_033.jsonl
665dbcc74496d40687fc51472396e195
1024 megabytes
["4\n1 1 4 9", "4\n4 3 2 1", "3\n4 2 1", "8\n42 1337 13 37 420 666 616 97"]
PASSED
n = int(raw_input()) a = map(int, raw_input().split()) a.sort() if a[-2] * 2 > a[-1]: print 0 quit() mod = 998244353 f = [1] * (n + 1) for i in xrange(1, n + 1): f[i] = f[i-1] * i % mod invf = [1] * (n + 1) invf[n] = pow(f[n], mod - 2, mod) for i in xrange(n - 1, 0, -1): invf[i] = invf[i+1] * (i + 1) % mod a.pop() dp = [0] * n dp[0] = 1 h = 0 for i, x in enumerate(a, 1): while a[h] * 2 <= x: h += 1 dp[i] = (dp[i-1] * (n - i) + dp[h] * f[n-h-2] * invf[n-i-1]) % mod print dp[-1]
1603809300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["9", "10"]
7dd891cef0aa40cc1522ca4b37963b92
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
Print a single integer – the largest number of enemy spaceships that can be destroyed.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
standard output
standard input
Python 3
Python
2,100
train_004.jsonl
03cfa6b1362dde3d071465da2638f5e0
256 megabytes
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
PASSED
from collections import Counter MV = 400020 a = [0] * MV for i in range(MV): a[i] = set() n ,m = list(map(int , input().split())) first = list(map(int , input().split())) second = list(map(int , input().split())) for fid, f in enumerate(first): for sid, s in enumerate(second): a[f+s].add(fid + MV) a[f+s].add(sid) a.sort(key = lambda x: -len(x)) b = [len(k) for k in a] # for k in range(MV): # if b[k]>0: # print(k, b[k], a[k]) best_res = b[0] for pos in range(MV): for pos2 in range(MV): if b[pos] + b [pos2] <= best_res: break cur = len(a[pos].union(a[pos2])) if cur > best_res : best_res = cur print(best_res)
1529166900
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
1 second
["81", "100"]
d3c10d1b1a17ad018359e2dab80d2b82
null
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Print the number of codes that match the given hint.
The first line contains string s β€” the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0. The input limits for scoring 30 points are (subproblem A1): 1 ≀ |s| ≀ 5. The input limits for scoring 100 points are (subproblems A1+A2): 1 ≀ |s| ≀ 105. Here |s| means the length of string s.
standard output
standard input
Python 2
Python
1,400
train_017.jsonl
333f971670b81459dff489cde0f78698
256 megabytes
["AJ", "1?AA"]
PASSED
from math import factorial as f r=raw_input() t=r.count('?') l=set('ABCDEFGHIJ') n=len(set(r)&l) R=1 c=10 if r[0] in l: R*=9 n-=1 c-=1 if r[0] == '?': R*=9 t-=1 R*=f(c)/f(c-n) print str(R)+ '0'*t
1371042000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3 0", "0 3", "3 4"]
96e2ba997eff50ffb805b6be62c56222
null
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message β€” string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Print two integers separated by a space: the first number is the number of times Tanya shouts "YAY!" while making the message, the second number is the number of times Tanya says "WHOOPS" while making the message.
The first line contains line s (1 ≀ |s| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text of Tanya's message. The second line contains line t (|s| ≀ |t| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text written in the newspaper. Here |a| means the length of the string a.
standard output
standard input
Python 3
Python
1,400
train_001.jsonl
6886ec51284d36ae8382646df871ff7b
256 megabytes
["AbC\nDCbA", "ABC\nabc", "abacaba\nAbaCaBA"]
PASSED
s = input() t = input() a, b = {}, [] for i in t: if i in a: a[i] += 1 else: a[i] = 1 for i in s: b.append(i) res1, res2 = 0, 0 for i in range(len(b)): if (b[i] in a) and (a[b[i]] > 0): res1 += 1 a[b[i]] -= 1 b[i] = '0' for i in b: t = i if i.islower(): t = i.upper() elif i.isupper(): t = i.lower() if (t in a) and (a[t] > 0): res2 += 1 a[t] -= 1 print(res1, res2)
1424795400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["6", "5"]
1c64defd239d785acc4e1b622289624d
NoteThese are the possible assignments for the first example: 1 5 3 7 1 2 3 7 5 2 3 7 1 5 7 3 1 2 7 3 5 2 7 3
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.
Print the number of possible assignments, modulo 1000000007 = 109 + 7.
Input will begin with a line containing N (1 ≀ N ≀ 100000), the number of engineers. N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2Β·N. It is guaranteed that no two engineers sit at the same desk.
standard output
standard input
Python 3
Python
2,100
train_008.jsonl
de19bb2ce6d7fe3a2509ab8fb0b4b575
256 megabytes
["4\n1 5\n5 2\n3 7\n7 3", "5\n1 10\n2 10\n3 10\n4 10\n5 5"]
PASSED
n = int(input()) m = 2 * n + 1 u = [[] for i in range(m)] v = [0] * m s = [0] * m d = 10 ** 9 + 7 y = 1 for j in range(n): a, b = map(int, input().split()) v[a] = b if a != b: s[b] += 1 u[b].append(a) for b in range(m): if not v[b]: x = 0 p = [b] while p: x += 1 a = p.pop() s[a] = -1 p += u[a] y = (x * y) % d for a in range(m): if s[a] == 0: b = v[a] while s[b] == 1: s[b] = -1 b = v[b] s[b] -= 1 for a in range(m): if s[a] == 1: y = (2 * y) % d while s[a]: s[a] = 0 a = v[a] print(y)
1505583300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["2\n4\n2", "10\n29\n9"]
6f6bb98cee5c9e646c72f3be8969c6df
NoteConsider the first test case. $$$b_1 = 1$$$: We need to convert $$$[3, 7] \rightarrow [1, 5]$$$. We can perform the following operations:$$$[3, 7]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 1}}$$$ $$$[2, 6]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 1}}$$$ $$$[1, 5]$$$Hence the answer is $$$2$$$. $$$b_1 = 4$$$: We need to convert $$$[3, 7] \rightarrow [4, 5]$$$. We can perform the following operations: $$$[3, 7]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 2}}$$$ $$$[3, 6]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 2}}$$$ $$$[3, 5]$$$ $$$\xrightarrow[\text{increase}]{\text{i = 1}}$$$ $$$[4, 6]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 2}}$$$ $$$[4, 5]$$$Hence the answer is $$$4$$$. $$$b_1 = 3$$$: We need to convert $$$[3, 7] \rightarrow [3, 5]$$$. We can perform the following operations:$$$[3, 7]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 2}}$$$ $$$[3, 6]$$$ $$$\xrightarrow[\text{decrease}]{\text{i = 2}}$$$ $$$[3, 5]$$$Hence the answer is $$$2$$$.
Jeevan has two arrays $$$a$$$ and $$$b$$$ of size $$$n$$$. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations: Choose any $$$i$$$ ($$$1 \le i \le n$$$) and increment $$$a_j$$$ by $$$1$$$ for every $$$j$$$ which is a multiple of $$$i$$$ and $$$1 \le j \le n$$$. Choose any $$$i$$$ ($$$1 \le i \le n$$$) and decrement $$$a_j$$$ by $$$1$$$ for every $$$j$$$ which is a multiple of $$$i$$$ and $$$1 \le j \le n$$$. He wants to convert array $$$a$$$ into an array $$$b$$$ using the minimum total number of operations. However, Jeevan seems to have forgotten the value of $$$b_1$$$. So he makes some guesses. He will ask you $$$q$$$ questions corresponding to his $$$q$$$ guesses, the $$$i$$$-th of which is of the form: If $$$b_1 = x_i$$$, what is the minimum number of operations required to convert $$$a$$$ to $$$b$$$? Help him by answering each question.
Output $$$q$$$ integers Β β€” the answers to each of his $$$q$$$ questions.
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ Β β€” the size of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \le a_i \le 10^6)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, ..., b_n$$$ $$$(1 \le b_i \le 10^6$$$ for $$$i \neq 1$$$; $$$b_1 = -1$$$, representing that the value of $$$b_1$$$ is unknown$$$)$$$. The fourth line contains a single integer $$$q$$$ $$$(1 \le q \le 2 \cdot 10^{5})$$$ Β β€” the number of questions. Each of the following $$$q$$$ lines contains a single integer $$$x_i$$$ $$$(1 \le x_i \le 10^6)$$$ Β β€” representing the $$$i$$$-th question.
standard output
standard input
PyPy 3-64
Python
2,400
train_097.jsonl
6958fd2d6b2dabe0049a9ec06d165f0d
256 megabytes
["2\n3 7\n-1 5\n3\n1\n4\n3", "6\n2 5 4 1 3 6\n-1 4 6 2 3 5\n3\n1\n8\n4"]
PASSED
# n = int(input()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # # q = int(input()) # # for i in range(q): # b[0] = int(input()) # c = [a.copy()[i] - b[i] for i in range(n)] # answer = 0 # k = 1 # while k <= n//2+1: # j = 1 # e = c.copy() # while k * j <= n: # c[k * j - 1] -= e[k - 1] # j += 1 # answer += abs(e[k - 1]) # k += 1 # # for i in range(n//2+1,n): # answer += abs(e[i]) # print(answer) import sys import bisect input = sys.stdin.readline n = int(input().rstrip()) a = [-1] + [int(w) for w in input().split()] b = [-1] + [int(w) for w in input().split()] def to_target(a, target): vector = [0, 0] for k in range(2, n + 1): d = a[k] - target[k] for t in range(k, n + 1, k): a[t] -= d vector.append(-d) return vector x = to_target(a, b) y = to_target(a, [aa + 1 for aa in a]) t = int(input().rstrip()) xy0 = [(abs(x[k]), abs(y[k])) for k in range(2, n + 1) if x[k] * y[k] == 0] s1 = sum(x for x, y in xy0) s2 = sum(y for x, y in xy0) xy1 = [(abs(x[k]), abs(y[k])) for k in range(2, n + 1) if x[k] * y[k] > 0] xy1 = [(-x / y, x, y) for x, y in xy1] xy1.sort() ratio1 = [r for r, _, __ in xy1] xy2 = [(abs(x[k]), abs(y[k])) for k in range(2, n + 1) if y[k] * x[k] < 0] xy2 = [(x / y, -x, y) for x, y in xy2] xy2.sort() ratio2 = [r for r, _, __ in xy2] def get_psum(xy): psums = [(0, 0)] for _, xk, yk in xy: px, py = psums[-1] psums.append((px + xk, py + yk)) return psums psums1 = get_psum(xy1) psums2 = get_psum(xy2) def d2s0(d): return s1 + s2 * abs(d) def d2s(d, ratio, psums): ind = bisect.bisect_left(ratio, d) return 2 * (psums[ind][0] + psums[ind][1] * d) - (psums[-1][0] + psums[-1][1] * d) for _ in range(t): q = int(input().rstrip()) d = a[1] - q print(abs(d) + d2s0(d) + d2s(d, ratio1, psums1) + d2s(d, ratio2, psums2))
1636727700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["3\n6\n3\n3\n10\n3\n2000000000000000000\n3\n4", "200\n300\n100\n100\n50"]
f32b9d3b5c93e566e16c1de963a159a8
NoteIn the first example:After the first and second queries, the set will contain elements $$$\{0, 1, 2\}$$$. The smallest non-negative number that is divisible by $$$1$$$ and is not in the set is $$$3$$$.After the fourth query, the set will contain the elements $$$\{0, 1, 2, 4\}$$$. The smallest non-negative number that is divisible by $$$2$$$ and is not in the set is $$$6$$$.In the second example: Initially, the set contains only the element $$$\{0\}$$$. After adding an integer $$$100$$$ the set contains elements $$$\{0, 100\}$$$. $$$100\text{-mex}$$$ of the set is $$$200$$$. After adding an integer $$$200$$$ the set contains elements $$$\{0, 100, 200\}$$$. $$$100\text{-mex}$$$ of the set $$$300$$$. After removing an integer $$$100$$$ the set contains elements $$$\{0, 200\}$$$. $$$100\text{-mex}$$$ of the set is $$$100$$$. After adding an integer $$$50$$$ the set contains elements $$$\{0, 50, 200\}$$$. $$$50\text{-mex}$$$ of the set is $$$100$$$. After removing an integer $$$50$$$ the set contains elements $$$\{0, 200\}$$$. $$$100\text{-mex}$$$ of the set is $$$50$$$.
This is the hard version of the problem. The only difference is that in this version there are remove queries.Initially you have a set containing one element β€” $$$0$$$. You need to handle $$$q$$$ queries of the following types:+ $$$x$$$ β€” add the integer $$$x$$$ to the set. It is guaranteed that this integer is not contained in the set; - $$$x$$$ β€” remove the integer $$$x$$$ from the set. It is guaranteed that this integer is contained in the set; ? $$$k$$$ β€” find the $$$k\text{-mex}$$$ of the set. In our problem, we define the $$$k\text{-mex}$$$ of a set of integers as the smallest non-negative integer $$$x$$$ that is divisible by $$$k$$$ and which is not contained in the set.
For each query of type ? output a single integer β€” the $$$k\text{-mex}$$$ of the set.
The first line contains an integer $$$q$$$ ($$$1 \leq q \leq 2 \cdot 10^5$$$) β€” the number of queries. The following $$$q$$$ lines describe the queries. An addition query of integer $$$x$$$ is given in the format + $$$x$$$ ($$$1 \leq x \leq 10^{18}$$$). It is guaranteed that $$$x$$$ is not contained in the set. A remove query of integer $$$x$$$ is given in the format - $$$x$$$ ($$$1 \leq x \leq 10^{18}$$$). It is guaranteed that $$$x$$$ is contained in the set. A search query of $$$k\text{-mex}$$$ is given in the format ? $$$k$$$ ($$$1 \leq k \leq 10^{18}$$$). It is guaranteed that there is at least one query of type ?.
standard output
standard input
PyPy 3-64
Python
2,400
train_097.jsonl
f47513b6b0669ed30cac2bec8fb23a1b
256 megabytes
["18\n\n+ 1\n\n+ 2\n\n? 1\n\n+ 4\n\n? 2\n\n+ 6\n\n? 3\n\n+ 7\n\n+ 8\n\n? 1\n\n? 2\n\n+ 5\n\n? 1\n\n+ 1000000000000000000\n\n? 1000000000000000000\n\n- 4\n\n? 1\n\n? 2", "10\n\n+ 100\n\n? 100\n\n+ 200\n\n? 100\n\n- 100\n\n? 100\n\n+ 50\n\n? 50\n\n- 50\n\n? 50"]
PASSED
from collections import defaultdict import math from sys import stdin input=lambda :stdin.readline()[:-1] n=int(input()) query=[] for i in range(n): x,y=input().split() y=int(y) if x=='+': query.append((0,y)) elif x=='-': query.append((1,y)) else: query.append((2,y)) D=max(1,int((n*math.log2(n))**0.5)) L=0 while L<n: R=min(n,L+D) s=set() for x,y in query[:L]: if x==0: s.add(y) if x==1: s.remove(y) removed=set() memo={} for x,y in query[L:R]: if x==0: s.add(y) if y in removed: removed.remove(y) if x==1: s.remove(y) removed.add(y) if x==2: if y in memo: tmp=memo[y] else: tmp=y while tmp in s: tmp+=y memo[y]=tmp ans=tmp for i in removed: if i%y==0: ans=min(ans,i) print(ans) L=R
1666519500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["2", "32"]
d46d5f130d8c443f28b52096c384fef3
NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.
Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2.
Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.
The first line contains a single integer n (1 ≀ n ≀ 1000)Β β€” the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≀ ai ≀ 106)Β β€” the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.
standard output
standard input
PyPy 3
Python
900
train_002.jsonl
09dee22b81a441873eb081c8708deafb
256 megabytes
["2\n4 2", "8\n1 2 4 8 16 32 64 576"]
PASSED
import math def is_sqrt(y): if y < 0: return False elif y == 0: return True x = int(math.sqrt(y)) return x * x == y m = -1000001 n = int(input()) ints = list(map(int, input().split())) for z in ints: if not is_sqrt(z) and z > m: m = z print(m)
1516462500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["7", "0"]
529aed80a647d181f08d2c26bb14d65d
null
You are given an array $$$a_1, a_2, \dots , a_n$$$ and two integers $$$m$$$ and $$$k$$$.You can choose some subarray $$$a_l, a_{l+1}, \dots, a_{r-1}, a_r$$$. The cost of subarray $$$a_l, a_{l+1}, \dots, a_{r-1}, a_r$$$ is equal to $$$\sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil$$$, where $$$\lceil x \rceil$$$ is the least integer greater than or equal to $$$x$$$. The cost of empty subarray is equal to zero.For example, if $$$m = 3$$$, $$$k = 10$$$ and $$$a = [2, -4, 15, -3, 4, 8, 3]$$$, then the cost of some subarrays are: $$$a_3 \dots a_3: 15 - k \lceil \frac{1}{3} \rceil = 15 - 10 = 5$$$; $$$a_3 \dots a_4: (15 - 3) - k \lceil \frac{2}{3} \rceil = 12 - 10 = 2$$$; $$$a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac{3}{3} \rceil = 16 - 10 = 6$$$; $$$a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac{4}{3} \rceil = 24 - 20 = 4$$$; $$$a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac{5}{3} \rceil = 27 - 20 = 7$$$. Your task is to find the maximum cost of some subarray (possibly empty) of array $$$a$$$.
Print the maximum cost of some subarray of array $$$a$$$.
The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 3 \cdot 10^5, 1 \le m \le 10, 1 \le k \le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).
standard output
standard input
Python 3
Python
1,900
train_011.jsonl
72d1b0fa5170a7ec78cc68d0ee4dd9ec
256 megabytes
["7 3 10\n2 -4 15 -3 4 8 3", "5 2 1000\n-13 -4 -9 -20 -11"]
PASSED
n, m, k = list(map(int, input().split())); a = list(map(int, input().split())); values = list() for j in range(n): result = a[j]; sum1 = 0; for i in range(m): if j-i>=0: sum1 = sum1 + a[j-i]; if sum1 > result: result = sum1; else: continue; if j-m>=0: result = max(result, sum1 + values[j-m]); values.append(max(0, result-k)); print(max(values));
1563806100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 0 0 1 1"]
02a0b3cb995f954b216130d703dfc856
NoteLet us calculate the answer for sample input with root node as 1 and as 2.Root node 1Alice always wins in this case. One possible gameplay between Alice and Bob is: Alice moves one present from node 4 to node 3. Bob moves four presents from node 5 to node 2. Alice moves four presents from node 2 to node 1. Bob moves three presents from node 2 to node 1. Alice moves three presents from node 3 to node 1. Bob moves three presents from node 4 to node 3. Alice moves three presents from node 3 to node 1. Bob is now unable to make a move and hence loses.Root node 2Bob always wins in this case. One such gameplay is: Alice moves four presents from node 4 to node 3. Bob moves four presents from node 5 to node 2. Alice moves six presents from node 3 to node 1. Bob moves six presents from node 1 to node 2. Alice is now unable to make a move and hence loses.
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has $$$n$$$ nodes (numbered $$$1$$$ to $$$n$$$, with some node $$$r$$$ as its root). There are $$$a_i$$$ presents are hanging from the $$$i$$$-th node.Before beginning the game, a special integer $$$k$$$ is chosen. The game proceeds as follows: Alice begins the game, with moves alternating each turn; in any move, the current player may choose some node (for example, $$$i$$$) which has depth at least $$$k$$$. Then, the player picks some positive number of presents hanging from that node, let's call it $$$m$$$ $$$(1 \le m \le a_i)$$$; the player then places these $$$m$$$ presents on the $$$k$$$-th ancestor (let's call it $$$j$$$) of the $$$i$$$-th node (the $$$k$$$-th ancestor of vertex $$$i$$$ is a vertex $$$j$$$ such that $$$i$$$ is a descendant of $$$j$$$, and the difference between the depth of $$$j$$$ and the depth of $$$i$$$ is exactly $$$k$$$). Now, the number of presents of the $$$i$$$-th node $$$(a_i)$$$ is decreased by $$$m$$$, and, correspondingly, $$$a_j$$$ is increased by $$$m$$$; Alice and Bob both play optimally. The player unable to make a move loses the game.For each possible root of the tree, find who among Alice or Bob wins the game.Note: The depth of a node $$$i$$$ in a tree with root $$$r$$$ is defined as the number of edges on the simple path from node $$$r$$$ to node $$$i$$$. The depth of root $$$r$$$ itself is zero.
Output $$$n$$$ integers, where the $$$i$$$-th integer is $$$1$$$ if Alice wins the game when the tree is rooted at node $$$i$$$, or $$$0$$$ otherwise.
The first line contains two space-separated integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 10^5, 1 \le k \le 20)$$$. The next $$$n-1$$$ lines each contain two integers $$$x$$$ and $$$y$$$ $$$(1 \le x, y \le n, x \neq y)$$$, denoting an undirected edge between the two nodes $$$x$$$ and $$$y$$$. These edges form a tree of $$$n$$$ nodes. The next line contains $$$n$$$ space-separated integers denoting the array $$$a$$$ $$$(0 \le a_i \le 10^9)$$$.
standard output
standard input
PyPy 3-64
Python
2,500
train_107.jsonl
0f9abcad7a7ac1299c59398463220677
256 megabytes
["5 1\n1 2\n1 3\n5 2\n4 3\n0 3 2 4 4"]
PASSED
''' Hala Madrid! https://www.zhihu.com/people/li-dong-hao-78-74 ''' import sys import os from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) #------------------------------FastIO--------------------------------- from bisect import * from heapq import * from collections import * from functools import * from itertools import * from time import * from random import * from math import log, gcd, sqrt, ceil class TopSort_Tree: def __init__(self, n) -> None: self.n = n self.graph = defaultdict(set) self.parent = [n + 1 for _ in range(self.n)] def add_edge(self, a, b): self.graph[a].add(b) self.graph[b].add(a) def sort(self, root): graphlist = [] q = deque() q.append((root, -1)) while q: cur, fa = q.popleft() graphlist.append(cur) for e in self.graph[cur]: if e == fa: continue else: self.parent[e] = cur q.append((e, cur)) return graphlist[::-1] def solve(): n, k = MI() gl = TopSort_Tree(n) xorsum = [[0 for _ in range(k << 1)] for _ in range(n)] win = [0 for _ in range(n)] for _ in range(n - 1): x, y = MI() x -= 1 y -= 1 gl.add_edge(x, y) nums = LII() graphlist = gl.sort(0) for node in graphlist: xorsum[node][0] ^= nums[node] if node == 0: break fa = gl.parent[node] for depth in range(k << 1): xorsum[fa][depth] ^= xorsum[node][depth - 1] #print(xorsum) q = deque() q.append((0, -1, [0 for _ in range(k << 1)])) while q: node, fa, prev_xors = q.popleft() final_xors = [x ^ y for x, y in zip(prev_xors, xorsum[node])] for e in gl.graph[node]: if e == fa: continue send_xors = final_xors[:] for i in range(k << 1): send_xors[i] ^= xorsum[e][i - 1] send_xors = [send_xors[-1]] + send_xors[:-1] q.append((e, node, send_xors)) odd_xors = 0 for i in range(k, k << 1): odd_xors ^= final_xors[i] win[node] = 1 if odd_xors else 0 print(*win) for _ in range(1):solve()
1617028500
[ "math", "games", "trees" ]
[ 1, 0, 0, 1, 0, 0, 0, 1 ]
1 second
["1", "0"]
04fd1a55027cce56a491b984ce3a1d6d
NoteIn the first example, the given graph is not harmonious (for instance, $$$1 &lt; 6 &lt; 7$$$, node $$$1$$$ can reach node $$$7$$$ through the path $$$1 \rightarrow 2 \rightarrow 7$$$, but node $$$1$$$ can't reach node $$$6$$$). However adding the edge $$$(2, 4)$$$ is sufficient to make it harmonious.In the second example, the given graph is already harmonious.
You're given an undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Nodes are numbered from $$$1$$$ to $$$n$$$.The graph is considered harmonious if and only if the following property holds: For every triple of integers $$$(l, m, r)$$$ such that $$$1 \le l &lt; m &lt; r \le n$$$, if there exists a path going from node $$$l$$$ to node $$$r$$$, then there exists a path going from node $$$l$$$ to node $$$m$$$. In other words, in a harmonious graph, if from a node $$$l$$$ we can reach a node $$$r$$$ through edges ($$$l &lt; r$$$), then we should able to reach nodes $$$(l+1), (l+2), \ldots, (r-1)$$$ too.What is the minimum number of edges we need to add to make the graph harmonious?
Print the minimum number of edges we have to add to the graph to make it harmonious.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 200\ 000$$$ and $$$1 \le m \le 200\ 000$$$). The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$), that mean that there's an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).
standard output
standard input
Python 2
Python
1,700
train_001.jsonl
7a5e92338dedb167a8d1de5e39808bb0
256 megabytes
["14 8\n1 2\n2 7\n3 4\n6 3\n5 7\n3 8\n6 8\n11 12", "200000 3\n7 9\n9 8\n4 5"]
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)) par = range(n + 1) st = [] pu = st.append for i in xrange(m): x, y = dat[i*2], dat[i*2+1] while x != par[x]: pu(x) x = par[x] pu(x) while y != par[y]: pu(y) y = par[y] for x in st: par[x] = y del st[:] l = range(n + 1) r = range(n + 1) c = [0] * (n + 1) s = set() for i in xrange(1, n + 1): x = i while x != par[x]: pu(x) x = par[x] for y in st: par[y] = x del st[:] if l[x] > i: l[x] = i if r[x] < i: r[x] = i c[x] += 1 if x == i: s.add(x) ans = 0 f = 1 while f: f = 0 t = s.copy() for i in s: if c[i] == r[i] - l[i] + 1 or i not in t: continue for j in xrange(l[i], r[i] + 1): x = j while x != par[x]: pu(x) x = par[x] if x != i: f = 1 if l[i] > l[x]: l[i] = l[x] if r[i] < r[x]: r[i] = r[x] c[i] += c[x] pu(x) ans += 1 t.remove(x) for y in st: par[y] = i del st[:] s = t print ans main()
1573914900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4\n5\n13\n3\n3\n3\n6"]
c783eaf1bf7e4e7321406431030d5aab
NoteOptimal arrays in the test cases of the example: $$$[1, 1, 1, 1]$$$, it has $$$4$$$ minimums and $$$4$$$ maximums; $$$[4, 4, 4, 4, 4]$$$, it has $$$5$$$ minimums and $$$5$$$ maximums; $$$[1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2]$$$, it has $$$3$$$ minimums and $$$10$$$ maximums; $$$[8, 8, 8]$$$, it has $$$3$$$ minimums and $$$3$$$ maximums; $$$[4, 6, 6]$$$, it has $$$1$$$ minimum and $$$2$$$ maximums; $$$[3, 4, 3]$$$, it has $$$2$$$ minimums and $$$1$$$ maximum; $$$[5, 5, 5, 5, 5, 5]$$$, it has $$$6$$$ minimums and $$$6$$$ maximums.
An array is beautiful if both of the following two conditions meet: there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum; there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.
For each test case, print one integerΒ β€” the minimum possible number of elements in a beautiful array.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$)Β β€” the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_1 \le r_1 \le 50$$$; $$$1 \le l_2 \le r_2 \le 50$$$).
standard output
standard input
Python 3
Python
800
train_083.jsonl
eb4447b3ec2ebfe8ff04ae16694dfc44
512 megabytes
["7\n\n3 5 4 6\n\n5 8 5 5\n\n3 3 10 12\n\n1 5 3 3\n\n1 1 2 2\n\n2 2 1 1\n\n6 6 6 6"]
PASSED
t = int(input()) for i in range(t): l1,r1,l2,r2 = map(int,input().split()) if r2 < l1 or r1 < l2: print(l1 + l2) else: print(max(l1,l2))
1652452500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\nNO\nYES\nNO"]
aae82b2687786818996e4e94c5505d8e
NoteIn the first example we have the list $$$\{4, 2, 2, 7\}$$$, and we have the target $$$k = 5$$$. One way to achieve it is the following: first we choose the third element, obtaining the list $$$\{2, 0, 5\}$$$. Next we choose the first element, obtaining the list $$$\{-2, 3\}$$$. Finally, we choose the first element, obtaining the list $$$\{5\}$$$.
You are given a list of $$$n$$$ integers. You can perform the following operation: you choose an element $$$x$$$ from the list, erase $$$x$$$ from the list, and subtract the value of $$$x$$$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $$$1$$$.Given an integer $$$k$$$ ($$$k&gt;0$$$), find if there is some sequence of $$$n-1$$$ operations such that, after applying the operations, the only remaining element of the list is equal to $$$k$$$.
For each test case, print YES if you can achieve $$$k$$$ with a sequence of $$$n-1$$$ operations. Otherwise, print NO. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$), the number of integers in the list, and the target value, respectively. The second line of each test case contains the $$$n$$$ integers of the list $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases is not greater that $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_091.jsonl
7917c677c2fe3ecc1852694601d789ce
256 megabytes
["4\n\n4 5\n\n4 2 2 7\n\n5 4\n\n1 9 1 3 4\n\n2 17\n\n17 0\n\n2 17\n\n18 18"]
PASSED
def merge(a,b): A=len(a) B=len(b) m=[] i,j=0,0 while i<A and j<B: ai,bj=a[i],b[j] if ai<=bj: m.append(ai) i+=1 else: m.append(b[j]) j+=1 m=m+a[i:A]+b[j:B] return m def mergesort(lst): llst=len(lst) if llst<=1: return lst return merge(mergesort(lst[0:llst//2]),mergesort(lst[llst//2:llst])) """def check(i,j,k,lst): if i>=j or j<=0 or i>=len(lst)-1: return False ab=lst[j]-lst[i] if ab==k: return True elif ab < k: return False else: return check(i+1,j,k,lst) or check(i,j-1,k,lst)""" t= int(input()) a=[] for f in range (t): n,k=tuple(map(int, input().split())) l=mergesort(list(map(int, input().split()))) """if(check(0,n-1,k,mergesort(l))): a.append('YES') else: a.append('NO')""" i,j=0,1 while i<n and j<n: if l[j]-l[i]==k: a.append('YES') break elif l[j]-l[i]<k: j+=1 else: i+=1 if(len(a)==f): a.append('NO') """def permutations(x): r,perm=[],[[]] for m in range (len(x)): for p in range (len(perm)): for q in range(len(perm[p])+1): z=perm[p].copy() z.insert(q,x[m]) r.append(z) perm = r r = [] return perm def summer(lst): ln=len(lst) s=lst[0] return s""" """t= int(input()) a=[] for i in range (t): n,k=tuple(map(int, input().split())) l=list(map(int, input().split())) s=sum(l) if k > max(l)-min(l): a.append('NO') continue flag=False for j in range (n): for m in range(j+1): if k==abs(l[j]-l[m]): a.append('YES') flag=True break if flag: break if not flag: a.append('NO')""" for i in range (t): print(a[i])
1648132500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1\n0\n1"]
178876bfe161ba9ccfd80c9310f75cbc
NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).
Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.
For each test case print one integer in single lineΒ β€” the minimum number of matches which you have to buy for assembling CME.
The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$)Β β€” the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$)Β β€” the number of matches.
standard output
standard input
Python 3
Python
800
train_007.jsonl
3a9035d41e6d91be346f38a4447ddad9
256 megabytes
["4\n2\n5\n8\n11"]
PASSED
import math q=int(input()) b=[] for i in range(q): a=int(input()) if a%2==0 and a!=2: b.append(0) elif a==2: b.append(2) else: b.append(math.ceil(a/2)*2 - a) for i in range(q): print(b[i])
1570374300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1", "2", "0"]
d9e9c53b391eb44f469cc92fdcf3ea0a
NoteIn the first sample one of the possible solutions is to change the first character to 'b'.In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
The first line of the input contains an integer n (1 ≀ n ≀ 100 000)Β β€” the length of the string s. The second line contains the string s of length n consisting of only lowercase English letters.
standard output
standard input
PyPy 3
Python
1,000
train_000.jsonl
401f9a27abacfb9ed44986432271fab7
256 megabytes
["2\naa", "4\nkoko", "5\nmurat"]
PASSED
n = int(input()) s = list(input()) f = set(s) if n > 26 : print('-1') exit(0) else: print(n - len(f))
1462984500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["2\n5\n3\n0\n1"]
a6b760941ab8be2c32c6dc66c623ea0e
NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.
This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met: each letter of the string is either painted in exactly one color (red or green) or isn't painted; each two letters which are painted in the same color are different; the number of letters painted in red is equal to the number of letters painted in green; the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string $$$s$$$ equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure. The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ β€” the number of red (or green, these numbers are equal) letters in a wonderful coloring.
For each test case, output a separate line containing one non-negative integer $$$k$$$ β€” the number of letters which will be painted in red in a wonderful coloring.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.
standard output
standard input
Python 3
Python
800
train_099.jsonl
8eb56552d7b27d596d1194f36a026e96
256 megabytes
["5\nkzaaa\ncodeforces\narchive\ny\nxxxxxx"]
PASSED
t = int(input()) for i in range(t): s = input() d = {} r, g = 0, 0 for i in s: if i not in d: d[i] = 0 d[i] += 1 c = 0 for key, value in d.items(): if value >= 2: c += 1 c += 1 print(c // 2)
1627050900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["odd\neven", "odd\nodd\nodd\neven"]
d20cc952cdf3a99e7d980a0270c49f78
NoteThe first example: after the first query a = [2, 1, 3], inversion: (2, 1); after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2). The second example: a = [1, 2, 4, 3], inversion: (4, 3); a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3); a = [1, 2, 4, 3], inversion: (4, 3); a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i &gt; j and ai &lt; aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].After each query you have to determine whether the number of inversions is odd or even.
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
The first line contains one integer n (1 ≀ n ≀ 1500) β€” the size of the permutation. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n) β€” the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1 ≀ m ≀ 2Β·105) β€” the number of queries to process. Then m lines follow, i-th line containing two integers li, ri (1 ≀ li ≀ ri ≀ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
standard output
standard input
Python 3
Python
1,800
train_014.jsonl
671cea094718fb26f8a5f182fd98655b
256 megabytes
["3\n1 2 3\n2\n1 2\n2 3", "4\n1 2 4 3\n4\n1 1\n1 4\n1 4\n2 3"]
PASSED
from sys import stdin, stdout input, print = stdin.readline, stdout.write n = int(input()) a = [int(i) for i in input().split()] c = 0 for i in range(n): for j in range(i + 1, n): c += int(a[i] > a[j]) c %= 2 q = int(input()) for i in range(q): l, r = [int(i) for i in input().split()] c ^= (r - l) * (r - l + 1) // 2 % 2 print("odd\n" if c else "even\n")
1514469900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3\n5 1 3 6\n4 2 7\n5\n1 2 8 11 4 13 9 15\n6 14 3 7 10 5 12"]
b75ec87dcc25fdd04c3388a0051b8719
NoteThe tree in the first test case with the weights of all nodes and edges is shown in the picture. The costs of all paths are: $$$3$$$; $$$3\oplus 7=4$$$; $$$3\oplus 7\oplus 6=2$$$; $$$3\oplus 2=1$$$; $$$3\oplus 2\oplus 1=0$$$; $$$3\oplus 2\oplus 1\oplus 4=4$$$; $$$3\oplus 2\oplus 1\oplus 4\oplus 5=1$$$. The maximum cost of all these paths is $$$4$$$. We can show that it is impossible to assign the values and choose the root differently to achieve a smaller maximum cost of all paths.The tree in the second test case:
After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team "Hemose 3al shagra" (Hemose on the tree).You are given a tree of $$$n$$$ vertices where $$$n$$$ is a power of $$$2$$$. You have to give each node and edge an integer value in the range $$$[1,2n -1]$$$ (inclusive), where all the values are distinct.After giving each node and edge a value, you should select some root for the tree such that the maximum cost of any simple path starting from the root and ending at any node or edge is minimized.The cost of the path between two nodes $$$u$$$ and $$$v$$$ or any node $$$u$$$ and edge $$$e$$$ is defined as the bitwise XOR of all the node's and edge's values between them, including the endpoints (note that in a tree there is only one simple path between two nodes or between a node and an edge).
For each test case on the first line print the chosen root. On the second line, print $$$n$$$ integers separated by spaces, where the $$$i$$$-th integer represents the chosen value for the $$$i$$$-th node. On the third line, print $$$n-1$$$ integers separated by spaces, where the $$$i$$$-th integer represents the chosen value for the $$$i$$$-th edge. The edges are numerated in the order of their appearance in the input data. If there are multiple solutions, you may output any.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5\cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$p$$$ ($$$1 \le p \le 17$$$), where $$$n$$$ (the number of vertices in the tree) is equal to $$$2^p$$$. Each of the next $$$nβˆ’1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) meaning that there is an edge between the vertices $$$u$$$ and $$$v$$$ in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3\cdot 10^5$$$.
standard output
standard input
Python 3
Python
2,200
train_100.jsonl
776793d15c708299bc8a2834604a72d4
256 megabytes
["2\n\n2\n\n1 2\n\n2 3\n\n3 4\n\n3\n\n1 2\n\n2 3\n\n3 4\n\n1 5\n\n1 6\n\n5 7\n\n5 8"]
PASSED
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(2**27) sys.setrecursionlimit(300000) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ def main(): for ik in range(int(input())): n = int(input()) graph = defaultdict(list) ind = defaultdict(int) n = 2 ** n node = [0] * n edge = [0] * (n - 1) for i in range(n - 1): a, b = map(int, input().split()) graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) ind[(a - 1, b - 1)] = i ind[(b - 1, a - 1)] = i t = [0] x = [n] def dfs(v, p, lev): if lev%2 == 1: edge[ind[(v, p)]] = x[0] + t[0] node[v] = t[0] else: node[v] = x[0] + t[0] if p != -1: edge[ind[(v, p)]] = t[0] t[0] += 1 for i in graph[v]: if i != p: dfs(i, v, lev + 1) dfs(0, -1, 0) print(1) print(*node) print(*edge) t = threading.Thread(target=main) t.start() t.join()
1651847700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["1", "6"]
0054f9e2549900487d78fae9aa4c2d65
NoteThe first sample corresponds to the picture: The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.
Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competitionΒ β€” determine the number of dangerous turns on the track.
Print a single integerΒ β€” the number of dangerous turns on the track.
The first line of the input contains an integer n (4 ≀ n ≀ 1000)Β β€” the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≀ xi, yi ≀ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that: the first straight section is directed to the north; the southernmost (and if there are several, then the most western of among them) point of the track is the first point; the last point coincides with the first one (i.e., the start position); any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); no pair of points (except for the first and last one) is the same; no two adjacent straight sections are directed in the same direction or in opposite directions.
standard output
standard input
Python 3
Python
1,500
train_004.jsonl
6adc96329128dd853938e428852948d1
256 megabytes
["6\n0 0\n0 1\n1 1\n1 2\n2 2\n2 0\n0 0", "16\n1 1\n1 5\n3 5\n3 7\n2 7\n2 9\n6 9\n6 7\n5 7\n5 3\n4 3\n4 4\n3 4\n3 2\n5 2\n5 1\n1 1"]
PASSED
print ((int(input()) - 4)//2)
1459353900
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["15", "91"]
51aa12a683a43f520667cb2f2f421bd8
NoteFor the first test, the optimal sizes of carrots are $$$\{1,1,1,2,2,2\}$$$. The time taken is $$$1^2+1^2+1^2+2^2+2^2+2^2=15$$$For the second test, the optimal sizes of carrots are $$$\{4,5,5,5\}$$$. The time taken is $$$4^2+5^2+5^2+5^2=91$$$.
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $$$n$$$ carrots with lengths $$$a_1, a_2, a_3, \ldots, a_n$$$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $$$k$$$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $$$k$$$ pieces. For some reason, all resulting carrot lengths must be positive integers.Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $$$x$$$ is $$$x^2$$$.Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.
Output one integer: the minimum sum of time taken for rabbits to eat carrots.
The first line contains two integers $$$n$$$ and $$$k$$$ $$$(1 \leq n \leq k \leq 10^5)$$$: the initial number of carrots and the number of rabbits. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \leq a_i \leq 10^6)$$$: lengths of carrots. It is guaranteed that the sum of $$$a_i$$$ is at least $$$k$$$.
standard output
standard input
PyPy 3
Python
2,200
train_016.jsonl
e5ed43ae25399781199169e264f86807
256 megabytes
["3 6\n5 3 1", "1 4\n19"]
PASSED
""" Author - Satwik Tiwari . 17th Oct , 2020 - Saturday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase # from itertools import * from heapq import * # from math import gcd, factorial,floor,ceil from copy import deepcopy from collections import deque # from collections import Counter as counter # Counter(list) return a dict with {key: count} # from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] # from itertools import permutations as permutate from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### # from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts mod = 10**9+7 def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True #=============================================================================================== # code here ;)) def help(val,part): temp = val//part rem = val%part return (temp*temp)*(part-rem) + ((temp+1)*(temp+1))*rem def solve(case): n,k = sep() a = lis() curr = 0 for i in range(n): curr+=a[i]*a[i] h = [] parts = [1]*n for i in range(n): heappush(h,(help(a[i],2) - help(a[i],1),i)) cnt = n while(cnt<k): temp = heappop(h) # print(temp) diff,ele = temp[0],temp[1] curr+=diff parts[ele]+=1 heappush(h,(help(a[ele],parts[ele]+1) - help(a[ele],parts[ele]),ele)) cnt+=1 print(curr) testcase(1) # testcase(int(inp()))
1602939900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES 0\nYES 1\nNO"]
1501b9f964f793c2746ff5977db4e607
NoteIn each of the illustrations, the pictures are shown in order in which Olya applied the operations. The recently-created squares are highlighted with red.In the first test, Olya can apply splitting operations in the following order: Olya applies one operation on the only existing square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is $$$1$$$. $$$log_2(1) = 0$$$.In the second test, Olya can apply splitting operations in the following order: Olya applies the first operation on the only existing square. She applies the second one on the right bottom square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one: The length of the sides of the squares on the path is $$$2$$$. $$$log_2(2) = 1$$$.In the third test, it takes $$$5$$$ operations for Olya to make the square look like this: Since it requires her to perform $$$7$$$ splitting operations, and it is impossible to perform them on squares with side equal to $$$1$$$, then Olya cannot do anything more and the answer is "NO".
Recently, Olya received a magical square with the size of $$$2^n\times 2^n$$$.It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly $$$k$$$ splitting operations.A Splitting operation is an operation during which Olya takes a square with side $$$a$$$ and cuts it into 4 equal squares with side $$$\dfrac{a}{2}$$$. If the side of the square is equal to $$$1$$$, then it is impossible to apply a splitting operation to it (see examples for better understanding).Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.The condition of Olya's happiness will be satisfied if the following statement is fulfilled:Let the length of the side of the lower left square be equal to $$$a$$$, then the length of the side of the right upper square should also be equal to $$$a$$$. There should also be a path between them that consists only of squares with the side of length $$$a$$$. All consecutive squares on a path should have a common side.Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $$$k$$$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.
Print $$$t$$$ lines, where in the $$$i$$$-th line you should output "YES" if it is possible to perform $$$k_i$$$ splitting operations in the $$$i$$$-th test in such a way that the condition of Olya's happiness is satisfied or print "NO" otherwise. If you printed "YES", then also print the $$$log_2$$$ of the length of the side of the squares through space, along which you can build a path from the lower left square to the upper right one. You can output each letter in any case (lower or upper). If there are multiple answers, print any.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$)Β β€” the number of tests. Each of the following $$$t$$$ lines contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \le n_i \le 10^9, 1 \le k_i \le 10^{18}$$$)Β β€” the description of the $$$i$$$-th test, which means that initially Olya's square has size of $$$2^{n_i}\times 2^{n_i}$$$ and Olya's sister asks her to do exactly $$$k_i$$$ splitting operations.
standard output
standard input
Python 3
Python
2,000
train_002.jsonl
a8aa12db461939822df52fc13fe5e1b0
256 megabytes
["3\n1 1\n2 2\n2 12"]
PASSED
def A(n): return (4**n-1)//3 L = 31 T = int(input()) for _ in range(T): n,k = [int(_) for _ in input().split()] if n > L: print("YES",n-1) continue if k > A(n): print("NO") continue E = 1 M = 0 R = 0 while n >= 0: M += E I = 2*E-1 E = 2*E+1 n -= 1 R += I*A(n) if M <= k and k <= M+R: break if n >= 0: print("YES",n) else: print("NO")
1543044900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["0\n2\n3"]
55a1e9236cac9a6044e74b1975331535
NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$.
You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays: choose one of the two arrays pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$ swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.
For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) β€” array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) β€” array $$$b$$$. 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_094.jsonl
0dcf69ba8089e25a71c821af0844c4e1
256 megabytes
["3\n2\n3 1\n4 2\n3\n5 3 1\n2 4 6\n5\n7 5 9 1 3\n2 4 6 10 8"]
PASSED
def get_input(): al = [] for c in range(int(input())): input() a = [int(i) for i in input().split(" ")] b = [int(i) for i in input().split(" ")] al.append([a,b]) return al def solve(a,b): j = 1 di = {} for i in range(len(a)): while j < b[i]: di[j] = i j+=2 ans = 2*len(a) + 1 for i in range(len(a)): ans = min(ans, i + di[a[i]]) return ans def main(): arr_list = get_input() for a,b in arr_list: r = solve(a,b) print(r) main()
1631975700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["40", "400", "160"]
2e6bf9154d9da6ac134b52144d5322ca
NoteOne of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Output the minimum total energy the child should spend to remove all n parts of the toy.
The first line contains two integers n and m (1 ≀ n ≀ 1000; 0 ≀ m ≀ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≀ vi ≀ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≀ xi, yi ≀ n;Β xi ≠ yi). Consider all the parts are numbered from 1 to n.
standard output
standard input
Python 3
Python
1,400
train_001.jsonl
b844a54d6f487f1eef372cc3c2fc9997
256 megabytes
["4 3\n10 20 30 40\n1 4\n1 2\n2 3", "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4", "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4"]
PASSED
''' Created on ٠ّ‏/٠ّ‏/Ω’Ω Ω‘Ω₯ @author: mohamed265 ''' t = input().split() n = int(t[0]) m = int(t[1]) slon = 0 num = [int(x) for x in input().split()] for i in range(m): t = input().split() slon += min(num[int(t[0])-1] , num[int(t[1])-1]) print(slon)
1401627600
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["-4\n499999998352516354"]
a3705f29b9a8be97a9e9e54b6eccba09
NoteThe answer for the first sample is explained in the statement.
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.
Print the requested sum for each of t integers n given in the input.
The first line of the input contains a single integer t (1 ≀ t ≀ 100) β€” the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≀ n ≀ 109).
standard output
standard input
Python 3
Python
900
train_017.jsonl
a19ba99e5f0466bd6ead271b91334e9e
256 megabytes
["2\n4\n1000000000"]
PASSED
t = int(input()) import math tests = [] for _ in range(t): tests.append(int(input())) def solve(n): i,t = int(1),0 while i <= n: t += i i *= 2 return t for n in tests: s = int((n*(n+1))//2) m = int(solve(n)*2) print(int(s-m))
1447426800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n2\n10\n12\n10\n15\n106"]
e7f84300e9480a94a2399fcd5f47ecec
NoteIn the first test case, the diverse substring is "7".In the second test case, the only diverse substring is "7", which appears twice, so the answer is $$$2$$$.In the third test case, the diverse substrings are "0" ($$$2$$$ times), "01", "010", "1" ($$$2$$$ times), "10" ($$$2$$$ times), "101" and "1010".In the fourth test case, the diverse substrings are "0" ($$$3$$$ times), "01", "011", "0110", "1" ($$$2$$$ times), "10", "100", "110" and "1100".In the fifth test case, the diverse substrings are "3", "39", "399", "6", "9" ($$$4$$$ times), "96" and "996".In the sixth test case, all $$$15$$$ non-empty substrings of "23456" are diverse.
A non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it.For example: string "7" is diverse because 7 appears in it $$$1$$$ time and the number of distinct characters in it is $$$1$$$; string "77" is not diverse because 7 appears in it $$$2$$$ times and the number of distinct characters in it is $$$1$$$; string "1010" is diverse because both 0 and 1 appear in it $$$2$$$ times and the number of distinct characters in it is $$$2$$$; string "6668" is not diverse because 6 appears in it $$$3$$$ times and the number of distinct characters in it is $$$2$$$. You are given a string $$$s$$$ of length $$$n$$$, consisting of only digits $$$0$$$ to $$$9$$$. Find how many of its $$$\frac{n(n+1)}{2}$$$ substrings are diverse.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Note that if the same diverse string appears in $$$s$$$ multiple times, each occurrence should be counted independently. For example, there are two diverse substrings in "77" both equal to "7", so the answer for the string "77" is $$$2$$$.
For each test case print one integerΒ β€” the number of diverse substrings of the given string $$$s$$$.
Each test contains multiple test cases. 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 length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. It is guaranteed that all characters of $$$s$$$ are digits from $$$0$$$ to $$$9$$$. 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
1,400
train_083.jsonl
abf0b20b85ed3e624ef58aedec0e8cdb
256 megabytes
["7\n\n1\n\n7\n\n2\n\n77\n\n4\n\n1010\n\n5\n\n01100\n\n6\n\n399996\n\n5\n\n23456\n\n18\n\n789987887987998798"]
PASSED
import sys input = sys.stdin.readline print = sys.stdout.write t = int(input().strip()) def solve(n, a): s = 0 for i in range(n): ds, m = {}, 0 for j in range(i, min(n, i+100)): if a[j] in ds: ds[a[j]] = ds[a[j]]+1 else: ds[a[j]] = 1 m = max(m, ds[a[j]]) if m<=len(ds): s = s+1 return str(s) for i in range(t): n = int(input().strip()) a = list(map(int, input().strip())) print(solve(n, a)+"\n")
1668263700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
4 seconds
["12 6 3 1 \n12 6 2 1 \n8 4 2 1", "14 7 3 1 \n14 6 3 1 \n14 6 2 1"]
d87bbd969c2fcc1541c5d6119e47efae
NoteFollowing are the images of the first 4 levels of the tree in the first test case:Original: After query 1 2 1: After query 2 4 -1:
You have a full binary tree having infinite levels.Each node has an initial value. If a node has value x, then its left child has value 2Β·x and its right child has value 2Β·x + 1. The value of the root is 1. You need to answer Q queries. There are 3 types of queries: Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected). Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them). Print the value of every node encountered on the simple path from the node with value X to the root.Positive K implies right cyclic shift and negative K implies left cyclic shift. It is guaranteed that atleast one type 3 query is present.
For each query of type 3, print the values of all nodes encountered in descending order.
The first line contains a single integer Q (1 ≀ Q ≀ 105). Then Q queries follow, one per line: Queries of type 1 and 2 have the following format: T X K (1 ≀ T ≀ 2; 1 ≀ X ≀ 1018; 0 ≀ |K| ≀ 1018), where T is type of the query. Queries of type 3 have the following format: 3 X (1 ≀ X ≀ 1018).
standard output
standard input
PyPy 2
Python
2,100
train_028.jsonl
65cf6f3508f13bf6ca6e240253f5433a
256 megabytes
["5\n3 12\n1 2 1\n3 12\n2 4 -1\n3 8", "5\n3 14\n1 5 -3\n3 14\n1 3 1\n3 14"]
PASSED
levels=[[0,0] for i in range(61)] levels[0][1]=1 for i in range(1,61): levels[i][1]=2*levels[i-1][1] import math q=int(raw_input()) for e in range(q): s=raw_input().split() if(s[0]=='3'): x=int(s[1]) high=int(math.log(x,2)) pos=(x-(levels[high][1]-levels[high][0]))%levels[high][1] #print(levels[high]) ans=[x,] for i in range(high-1,-1,-1): #print(x,pos,levels[i][0]) pos//=2 if(pos-levels[i][0]<0): ans.append(2*levels[i][1]-levels[i][0]+pos) else: ans.append(levels[i][1]-levels[i][0]+pos) for i in range(len(ans)): ans[i]=str(ans[i]) s=' '.join(ans) print(s) elif(s[0]=='1'): x=int(s[1]) k=int(s[2]) high=int(math.log(x,2)) levels[high][0]=(k+levels[high][0])%levels[high][1] else: x=int(s[1]) k=int(s[2]) high=int(math.log(x,2)) for i in range(high,61): levels[i][0]=(k+levels[i][0])%levels[i][1] k*=2
1523117100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["4500.0", "0.0"]
5aad0a82748d931338140ae81fed301d
NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0Β·s1 = 420, s1Β·s2 = 176576400, and s2Β·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2Β·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000 (1, 421, 420421): total is 0. (2, 420, 420420): total is 6000. (2, 420, 420421): total is 6000. (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product siΒ·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.
Print a single real number β€” the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
The first line of the input contains two space-separated integers n and p (3 ≀ n ≀ 100 000, 2 ≀ p ≀ 109)Β β€” the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th sharkΒ β€” two space-separated integers li and ri (1 ≀ li ≀ ri ≀ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.
standard output
standard input
Python 3
Python
1,700
train_002.jsonl
4c557b9b9216e632479ee8aa7aaf2275
256 megabytes
["3 2\n1 2\n420 421\n420420 420421", "3 5\n1 4\n2 3\n11 14"]
PASSED
f = lambda: list(map(int, input().split())) n, p = f() t = [(l - 1, r) for l, r in [f() for i in range(n)]] t = [(r // p - l // p) / (r - l) for l, r in t] print(2000 * sum(t[i] * (2 - t[i - 1]) for i in range(n)))
1454249100
[ "number theory", "math", "probabilities" ]
[ 0, 0, 0, 1, 1, 1, 0, 0 ]
3 seconds
["-1", "4"]
fbc119b603ca87787628a3f4b7db8c33
NoteAssume that Theseus starts at the block (xT, yT) at the moment 0.
Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n × m and consists of blocks of size 1 × 1.Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.Theseus found an entrance to labyrinth and is now located in block (xT, yT)Β β€” the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM, yM) and wants to know the minimum number of minutes required to get there.Theseus is a hero, not a programmer, so he asks you to help him.
If Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 1000)Β β€” the number of rows and the number of columns in labyrinth, respectively. Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are: Β«+Β» means this block has 4 doors (one door to each neighbouring block); Β«-Β» means this block has 2 doorsΒ β€” to the left and to the right neighbours; Β«|Β» means this block has 2 doorsΒ β€” to the top and to the bottom neighbours; Β«^Β» means this block has 1 doorΒ β€” to the top neighbour; Β«&gt;Β» means this block has 1 doorΒ β€” to the right neighbour; Β«&lt;Β» means this block has 1 doorΒ β€” to the left neighbour; Β«vΒ» means this block has 1 doorΒ β€” to the bottom neighbour; Β«LΒ» means this block has 3 doorsΒ β€” to all neighbours except left one; Β«RΒ» means this block has 3 doorsΒ β€” to all neighbours except right one; Β«UΒ» means this block has 3 doorsΒ β€” to all neighbours except top one; Β«DΒ» means this block has 3 doorsΒ β€” to all neighbours except bottom one; Β«*Β» means this block is a wall and has no doors. Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right. Next line contains two integersΒ β€” coordinates of the block (xT, yT) (1 ≀ xT ≀ n, 1 ≀ yT ≀ m), where Theseus is initially located. Last line contains two integersΒ β€” coordinates of the block (xM, yM) (1 ≀ xM ≀ n, 1 ≀ yM ≀ m), where Minotaur hides. It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.
standard output
standard input
PyPy 2
Python
2,000
train_074.jsonl
aaed44c70420c74314cb43c2e57d0899
256 megabytes
["2 2\n+*\n*U\n1 1\n2 2", "2 3\n&lt;&gt;&lt;\n&gt;&lt;&gt;\n1 1\n2 1"]
PASSED
from collections import deque import sys ROTATE = { "+": "+", "-": "|", "|": "-", "^": ">", ">": "v", "v": "<", "<": "^", "L": "U", "U": "R", "R": "D", "D": "L", "*": "*" } # l, r, u, d BINARY_MAP = { "+": (1, 1, 1, 1), "-": (1, 1, 0, 0), "|": (0, 0, 1, 1), "^": (0, 0, 1, 0), ">": (0, 1, 0, 0), "v": (0, 0, 0, 1), "<": (1, 0, 0, 0), "L": (0, 1, 1, 1), "U": (1, 1, 0, 1), "R": (1, 0, 1, 1), "D": (1, 1, 1, 0), "*": (0, 0, 0, 0) } MULT = 1002 * 1002 def get_neighbors(lab, point): k, j, i = point / (MULT), (point / 1002) % 1002, point % 1002 point_state = lab[k][i][j] yield (point + (MULT)) % (4 * MULT) b = BINARY_MAP if b[point_state][0] == 1 and b[lab[k][i][j-1]][1] == 1: yield point - 1002 if b[point_state][1] == 1 and b[lab[k][i][j+1]][0] == 1: yield point + 1002 if b[point_state][2] == 1 and b[lab[k][i-1][j]][3] == 1: yield point - 1 if b[point_state][3] == 1 and b[lab[k][i+1][j]][2] == 1: yield point + 1 def rotate_lab(lab): from cStringIO import StringIO new_lab = [] for line in lab: s = StringIO() for symbol in line: s.write(ROTATE[symbol]) new_lab.append(s.getvalue()) s.close() return new_lab # def v_hash(point): # return point[2]*MULT + point[1]*1002 + point[0] def bfs(labs, start_point, end_point): q = deque() #visited = {start_point} visited = [False] * (4*MULT) x = start_point[2] * MULT + start_point[1]*1002 + start_point[0] y = end_point[1] * 1002 + end_point[0] visited[x] = True q.append((x, 0)) g = get_neighbors while q: current_point, current_len = q.popleft() # print current_point, current_len if (current_point % MULT) == y: return current_len for point in g(labs, current_point): if not visited[point]: visited[point] = True q.append((point, current_len + 1)) return -1 if __name__ == "__main__": n, m = sys.stdin.readline().strip().split() n = int(n) m = int(m) labs = [None]*4 labs[0] = ["*" * (m + 2)] + ["*%s*" % sys.stdin.readline().strip() for i in xrange(n)] + ["*" * (m + 2)] xt, yt = sys.stdin.readline().strip().split() xm, ym = sys.stdin.readline().strip().split() # n = 3 # m = 3 # xt, yt = 1, 1 # xm, ym = n, m #labs = [None] * 4 #labs[0] = ["*" * (m + 2)] + ["*%s*" % ("+" * m) for i in xrange(n)] + ["*" * (m + 2)] start_point = (int(xt), int(yt), 0) end_point = (int(xm), int(ym)) labs[1] = rotate_lab(labs[0]) labs[2] = rotate_lab(labs[1]) labs[3] = rotate_lab(labs[2]) #print labs print bfs(labs, start_point, end_point)
1464188700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["1", "5", "36"]
1708818cf66de9fa03439f608c897a90
null
You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≀ a ≀ b &lt; x ≀ y ≀ |s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1 ≀ i ≀ j ≀ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".
Output a single number β€” the quantity of pairs of non-overlapping palindromic substrings of s. Please do not use the %lld format specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d format specifier.
The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.
standard output
standard input
Python 3
Python
1,500
train_022.jsonl
23cb2a798349c1b6bbdbdd89752a81b6
256 megabytes
["aa", "aaa", "abacaba"]
PASSED
t = input() n = len(t) a, b = [1] * n, [1] * n for x, y in [(i - 1, i + 1) for i in range(n // 2)]: while x >= 0 and t[x] == t[y]: a[y] += 1 b[x] += 1 x -= 1 y += 1 for x, y in [(i, i + 1) for i in range(n // 2)]: while x >= 0 and t[x] == t[y]: a[y] += 1 b[x] += 1 x -= 1 y += 1 for x, y in [(i - 1, i + 1) for i in range(n // 2, n)]: while y < n and t[x] == t[y]: a[y] += 1 b[x] += 1 x -= 1 y += 1 for x, y in [(i, i + 1) for i in range(n // 2, n)]: while y < n and t[x] == t[y]: a[y] += 1 b[x] += 1 x -= 1 y += 1 for i in range(1, n): a[i] += a[i - 1] print(sum(a[i - 1] * b[i] for i in range(1, n)))
1331280000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
4 seconds
["1 4 1 2 3 4 5\n1 4 2 3 4 5 1\n1 4 3 4 5 1 2\n1 4 4 5 1 2 3\n1 4 5 1 2 3 4\n-1 10\n1 1 1 2\n-1 99"]
20e2cf707d39c22eaf111f12b2ae6d30
NoteIn the first example, the first tree looks as follows: In the first question, we have $$$p = {1}$$$, and $$$q = {2, 3, 4, 5}$$$. The maximum distance between a node in $$$p$$$ and a node in $$$q$$$ is $$$9$$$ (the distance between nodes $$$1$$$ and $$$5$$$).The second tree is a tree with two nodes with an edge with weight $$$99$$$ between them.
There is a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are conveniently labeled from $$$1$$$ to $$$n$$$. The weights are positive integers at most $$$100$$$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes $$$p$$$ and $$$q$$$, and the judge will return the maximum distance between a node in $$$p$$$ and a node in $$$q$$$. In the words, maximum distance between $$$x$$$ and $$$y$$$, where $$$x \in p$$$ and $$$y \in q$$$. After asking not more than $$$9$$$ questions, you must report the maximum distance between any pair of nodes.
null
null
standard output
standard input
Python 3
Python
1,700
train_010.jsonl
b997eb7d0e97a25e7bb4be9c0a5be287
256 megabytes
["2\n5\n9\n6\n10\n9\n10\n2\n99"]
PASSED
import sys t=int(input()) for _ in range(t): n=int(input()) max_dist=0 for bit in range(7): a=[] b=[] for i in range(1,n+1): if (i>>bit)%2: a.append(i) else: b.append(i) if len(a)==0 or len(b)==0: continue l=[len(a),len(b)]+a+b out=" ".join(map(str,l)) print(out+"\n") #print(len(a), len(b), *(a+b)) sys.stdout.flush() d=int(input()) if d>max_dist: max_dist=d print("-1 "+str(max_dist))
1555783500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2\n2 2 1\n1 3", "3\n1 1 \n2 2 3 \n2 4 5"]
5acd7b95a44dcb8f72623b51fcf85f1b
NoteIn the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.
First print number kΒ β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them.
The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000)Β β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui ≠ vi).
standard output
standard input
Python 3
Python
1,800
train_052.jsonl
164ea0c815b3ca86a6bf30510a8df32d
256 megabytes
["4\n1 2\n3 4\n3 2", "6\n3 4\n5 4\n3 2\n1 3\n4 6"]
PASSED
import sys import threading from collections import defaultdict def put(): return map(int, input().split()) def dfs(i, p, m): cnt = 1 z = 0 for j in tree[i]: if j==p: continue if cnt==m: cnt+=1 index = edge_index[(i,j)] ans[cnt].append(index) z = max(dfs(j,i,cnt), z) cnt+=1 return max(z,cnt-1) def solve(): l = dfs(1,0,0) print(l) for i in range(1, l+1): print(len(ans[i]), *ans[i]) n = int(input()) edge_index = defaultdict() ans = [[] for i in range(n+1)] tree = [[] for i in range(n+1)] for i in range(n-1): x,y = put() edge_index[(x,y)]=i+1 edge_index[(y,x)]=i+1 tree[x].append(y) tree[y].append(x) max_recur_size = 10**5*2 + 1000 max_stack_size = max_recur_size*500 sys.setrecursionlimit(max_recur_size) threading.stack_size(max_stack_size) thread = threading.Thread(target=solve) thread.start()
1458475200
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["29 28 26 19 0 0 0 \n24907 20705 22805 9514 0 0 0 0 0 0 \n43 43 43 32 38 43 \n3083"]
437ab04bd029db32ceba31becbe06722
NoteIn the first testcase the teams from each university for each $$$k$$$ are: $$$k=1$$$: university $$$1$$$: $$$[6], [5], [5], [3]$$$; university $$$2$$$: $$$[8], [1], [1]$$$; $$$k=2$$$: university $$$1$$$: $$$[6, 5], [5, 3]$$$; university $$$2$$$: $$$[8, 1]$$$; $$$k=3$$$: university $$$1$$$: $$$[6, 5, 5]$$$; university $$$2$$$: $$$[8, 1, 1]$$$; $$$k=4$$$: university $$$1$$$: $$$[6, 5, 5, 3]$$$;
Polycarp is an organizer of a Berland ICPC regional event. There are $$$n$$$ universities in Berland numbered from $$$1$$$ to $$$n$$$. Polycarp knows all competitive programmers in the region. There are $$$n$$$ students: the $$$i$$$-th student is enrolled at a university $$$u_i$$$ and has a programming skill $$$s_i$$$.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer $$$k$$$, each university will send their $$$k$$$ strongest (with the highest programming skill $$$s$$$) students in the first team, the next $$$k$$$ strongest students in the second team and so on. If there are fewer than $$$k$$$ students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $$$0$$$.Help Polycarp to find the strength of the region for each choice of $$$k$$$ from $$$1$$$ to $$$n$$$.
For each testcase print $$$n$$$ integers: the strength of the regionΒ β€” the total skill of the members of the present teamsΒ β€” for each choice of team size $$$k$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$)Β β€” the number of universities and the number of students. The second line of each testcase contains $$$n$$$ integers $$$u_1, u_2, \dots, u_n$$$ ($$$1 \le u_i \le n$$$)Β β€” the university the $$$i$$$-th student is enrolled at. The third line of each testcase contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)Β β€” the programming skill of the $$$i$$$-th student. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,400
train_102.jsonl
e586acdff8ee903e48b7f86d5d56d8e9
256 megabytes
["4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083"]
PASSED
for _ in range(int(input())): n = int(input()) u = list(map(int,input().split())) s = list(map(int,input().split())) un = [[] for _ in range(n)] for i in range(n): un[u[i]-1].append(s[i]) for i in range(n): un[i].sort(reverse=True) ans = [0 for _ in range(n)] for u in range(n): l = len(un[u]) p = [0 for _ in range(l+1)] for i in range(l): p[i+1] = un[u][i]+p[i] for k in range(1,l+1): ans[k-1] += p[(l//k)*k] print(*ans)
1619706900
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
1 second
["1", "0", "0", "999999999999999999"]
b34846d90dc011f2ef37a8256202528a
NoteIn the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.
Print single integerΒ β€” the minimum possible number of meals which Vasiliy could have missed during his vacation.
The only line contains three integers b, d and s (0 ≀ b, d, s ≀ 1018,  b + d + s β‰₯ 1)Β β€” the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.
standard output
standard input
Python 2
Python
1,200
train_002.jsonl
b2b1b781e3731b44602a8a7c4b25bb8b
256 megabytes
["3 2 1", "1 0 0", "1 1 1", "1000000000000000000 0 1000000000000000000"]
PASSED
m = map(long, raw_input().split()) maxV = max(m) a = [maxV-1] * 3 idx = 0 for i in range(3): if maxV == m[i]: idx = i break a[idx] = maxV ret = 0 for i in range(3): if a[i] - m[i] > 0: ret += a[i] - m[i] print ret
1476714900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["33", "0", "-1"]
df9942d1eb66b1f3b5c6b665b446cd3e
NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Print one number β€” any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.
The first line of input contains n β€” a positive integer number without leading zeroes (1 ≀ n &lt; 10100000).
standard output
standard input
Python 3
Python
2,000
train_013.jsonl
00d9521369a4b3b82d0aaed9003e0722
256 megabytes
["1033", "10", "11"]
PASSED
def checkBeauty (digi): total = 0 for i in range(0,len(digi)): total += int(digi[i]) return total % 3 def modThree (digi): one = [] two = [] for i in range(0,len(digi)): if int(digi[i]) % 3 == 1: one.insert(0,i) elif int(digi[i]) % 3 == 2: two.insert(0,i) modResult = [] modResult.append(one) modResult.append(two) return modResult def checkHead (digi): if len(digi) == 0: return -1 while len(digi) > 1: if int(digi[0]) == 0: digi.pop(0) else: break return "".join(digi) x = list(input()) modResult = modThree(x) numToDel = checkBeauty(x) finalResult = -1 delOne = [] delTwo = [] if numToDel == 0: finalResult = checkHead(x) elif numToDel == 1: if len(modResult[0]) != 0: delOne = x[:] delOne.pop(modResult[0][0]) if len(modResult[1]) > 1: delTwo = x[:] delTwo.pop(modResult[1][0]) delTwo.pop(modResult[1][1]) else: if len(modResult[1]) != 0: delTwo = x[:] delTwo.pop(modResult[1][0]) if len(modResult[0]) > 1: delOne = x[:] delOne.pop(modResult[0][0]) delOne.pop(modResult[0][1]) resultOne = checkHead(delOne) resultTwo = checkHead(delTwo) if resultOne == -1 and resultTwo != -1: finalResult = resultTwo elif resultOne != -1 and resultTwo == -1: finalResult = resultOne elif resultOne != -1 and resultTwo != -1: finalResult = resultTwo if len(resultTwo) > len(resultOne) else resultOne print (finalResult)
1490625300
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["dbcadabcdbcadabc", "aaaaa"]
245371912e9828e763a49a85f4f6d2d9
NoteIn the first test, it is optimal to make one duplication: "dbcadabc" $$$\to$$$ "dbcadabcdbcadabc".In the second test it is optimal to delete the last $$$3$$$ characters, then duplicate the string $$$3$$$ times, then delete the last $$$3$$$ characters to make the string have length $$$k$$$."abcd" $$$\to$$$ "abc" $$$\to$$$ "ab" $$$\to$$$ "a" $$$\to$$$ "aa" $$$\to$$$ "aaaa" $$$\to$$$ "aaaaaaaa" $$$\to$$$ "aaaaaaa" $$$\to$$$ "aaaaaa" $$$\to$$$ "aaaaa".
This is the hard version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it: Delete the last character of the string. Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$; In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
Print the lexicographically smallest string of length $$$k$$$ that can be obtained by doing the operations on string $$$s$$$.
The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5\cdot 10^5$$$) β€” the length of the original string $$$s$$$ and the length of the desired string. The second line contains the string $$$s$$$, consisting of $$$n$$$ lowercase English letters.
standard output
standard input
PyPy 3-64
Python
2,200
train_084.jsonl
14c9673b25110d0177d42e6fcbb98af6
256 megabytes
["8 16\ndbcadabc", "4 5\nabcd"]
PASSED
import os import sys from collections import defaultdict,deque from io import BytesIO, IOBase import sys import threading # MOD = 998244353 # nmax = 5000 # fact = [1] * (nmax+1) # for i in range(2, nmax+1): # fact[i] = fact[i-1] * i % MOD # inv = [1] * (nmax+1) # for i in range(2, nmax+1): # inv[i] = pow(fact[i], MOD-2, MOD) # def C(n, m): # return fact[n] * inv[m] % MOD * inv[n-m] % MOD if 0 <= m <= n else 0 # from itertools import permutations # from bisect import bisect_left # d=[] # for i in range(1,7): # def solve(j,p): # if j==i: # return d.append(p) # for el in [0,1]: # solve(j+1,10*p+el) # solve(0,0) # from collections import Counter # from bisect import bisect_left def main(): n,p=map(int,input().split()) s=list(input()) j=n i=1 while i<n: if s[i]>s[0]: j=i break elif s[i]==s[0]: k=i l=0 while k<n and s[k]==s[l]: k+=1 l+=1 if k>=n or s[k]>s[l]: j=i break else : i=k else : i+=1 s="".join(s[:j]) l=len(s[:j]) t=p//l g=p%l print((s[:j]*t)+(s[:j])[:g]) #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main()
1624026900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1", "2", "3", "-1"]
22a43ccaa9e5579dd193bc941855b47d
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$)Β β€” the elements of the array $$$a$$$.
standard output
standard input
PyPy 3
Python
2,600
train_051.jsonl
385ba174208ad7084fa90b6154e03b3c
256 megabytes
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
PASSED
from sys import stdin from collections import deque, Counter, defaultdict N = int(input()) arr = list(map(int, stdin.readline().split())) MAX = 1_000_005 lp = [0] * MAX pr = [] pid = {1: 0} for i in range(2, MAX): if not lp[i]: lp[i] = i pr.append(i) pid[i] = len(pr) for p in pr: if p > lp[i] or i * p >= MAX: break lp[i * p] = p # lp is sieve, pr is a list of primes, pid is a dictionary keeping track of when the prime appears vertex = [[] for i in range(len(pid))] for n in arr: new = [] while n > 1: p, c = lp[n], 0 while lp[n] == p: n //= p c ^= 1 if c: new.append(p) if not new: print (1) exit() new += [1]*(2 - len(new)) u, v = pid[new[0]], pid[new[1]] vertex[u].append(v) vertex[v].append(u) def bfs_path(s): # s is the index for the prime number q = deque() v = [-1]*len(pid) v[s] = 0 q.append((s, -1)) while q: c, p = q.pop() for x in vertex[c]: if v[x] != -1: if x != p: return v[x] + v[c] + 1 else: v[x] = v[c] + 1 q.appendleft((x, c)) ''' q = deque() vertices = vertex.keys() vi = dict(zip(vertices, range(len(vertices)))) dist = [-1]*len(vertices) q.append(source) dist[vi[source]] = 0 far = 0 ans = float("inf") for v in vertex[source]: q = deque() q.append(v) dist = [-1]*len(vertices) dist[vi[source]] = 0 dist[vi[v]] = 1 while len(q): current = q.pop() for v in vertex[current]: # don't want to repeat an edge if dist[vi[v]] in (-1, 0): if v == end and dist[vi[current]] > 1: if dist[vi[current]] + 1 < ans: ans = dist[vi[current]] + 1 break elif v != end: dist[vi[v]] = dist[vi[current]] + 1 if dist[vi[v]] - 1 > far: far = dist[vi[v]] q.appendleft(v) if ans != float("inf"): return ans else: return 0 ''' ans = N + 1 for i in range(len(pid)): if i > 0 and pr[i - 1] > MAX**0.5: break ans = min(ans, bfs_path(i) or ans) print (ans if ans <= N else -1)
1584196500
[ "number theory", "graphs" ]
[ 0, 0, 1, 0, 1, 0, 0, 0 ]
1 second
["3\n2\n1\n1\n3\n1\n2\n1\n2\n3\n2"]
b8833a679d2bbad682cd7865aed9c08c
NoteOne of possible solutions to the example is shown below:
There are $$$n$$$ football teams in the world. The Main Football Organization (MFO) wants to host at most $$$m$$$ games. MFO wants the $$$i$$$-th game to be played between the teams $$$a_i$$$ and $$$b_i$$$ in one of the $$$k$$$ stadiums. Let $$$s_{ij}$$$ be the numbers of games the $$$i$$$-th team played in the $$$j$$$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $$$i$$$, the absolute difference between the maximum and minimum among $$$s_{i1}, s_{i2}, \ldots, s_{ik}$$$ should not exceed $$$2$$$.Each team has $$$w_i$$$Β β€” the amount of money MFO will earn for each game of the $$$i$$$-th team. If the $$$i$$$-th team plays $$$l$$$ games, MFO will earn $$$w_i \cdot l$$$.MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set.However, this problem is too complicated for MFO. Therefore, they are asking you to help them.
For each game in the same order, print $$$t_i$$$ ($$$1 \leq t_i \leq k$$$)Β β€” the number of the stadium, in which $$$a_i$$$ and $$$b_i$$$ will play the game. If the $$$i$$$-th game should not be played, $$$t_i$$$ should be equal to $$$0$$$. If there are multiple answers, print any.
The first line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$3 \leq n \leq 100$$$, $$$0 \leq m \leq 1\,000$$$, $$$1 \leq k \leq 1\,000$$$)Β β€” the number of teams, the number of games, and the number of stadiums. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1 \leq w_i \leq 1\,000$$$)Β β€” the amount of money MFO will earn for each game of the $$$i$$$-th game. Each of the following $$$m$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$)Β β€” the teams that can play the $$$i$$$-th game. It is guaranteed that each pair of teams can play at most one game.
standard output
standard input
PyPy 3
Python
3,100
train_043.jsonl
537f76cf99d41c936c9f12ba88893688
256 megabytes
["7 11 3\n4 7 8 10 10 9 3\n6 2\n6 1\n7 6\n4 3\n4 6\n3 1\n5 3\n7 5\n7 3\n4 2\n1 4"]
PASSED
import random import math def set_color(game, color): color_count[game[0]][game[2]] -= 1 color_count[game[1]][game[2]] -= 1 game[2] = color color_count[game[0]][game[2]] += 1 color_count[game[1]][game[2]] += 1 def fix(node): minimum = math.inf maximum = 0 for i in range(k): minimum = min(minimum, color_count[node][i]) maximum = max(maximum, color_count[node][i]) if maximum - minimum <= 2: return False rand = 0 for game in games: if (game[0] == node or game[1] == node) and color_count[node][game[2]] == maximum: rand = r(1,k) set_color(game, rand % k) return True return False n, m, k = map(int,input().split()) games = [[0 for _ in range(4)] for _ in range(m)] color_count = [[0 for _ in range(k)] for _ in range(n)] answers = [0 for _ in range(m)] _ = list(map(int,input().split())) color = 0 r = lambda x,y : random.randint(x,y) for i in range(m): a, b = map(int,input().split()) color = r(1,k) % k games[i] = [a-1,b-1,color,i] color_count[games[i][0]][color] += 1 color_count[games[i][1]][color] += 1 bad = True while bad: random.shuffle(games) bad = False for i in range(n): while(fix(i)): bad = True for game in games: answers[game[3]] = game[2] + 1 for i in range(m): print(answers[i])
1570374300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["1.0000000000", "2.0000000000"]
3edd332d8359ead21df4d822af6940c7
null
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path β€” a continuous curve, going through the shop, and having the cinema and the house as its ends.The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2.Find the maximum distance that Alan and Bob will cover together, discussing the film.
In the only line output one number β€” the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.
The first line contains two integers: t1, t2 (0 ≀ t1, t2 ≀ 100). The second line contains the cinema's coordinates, the third one β€” the house's, and the last line β€” the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.
standard output
standard input
Python 3
Python
2,600
train_041.jsonl
177bc4e058b7ada0ca9731369f3f034f
64 megabytes
["0 2\n0 0\n4 0\n-3 0", "0 0\n0 0\n2 0\n1 0"]
PASSED
__author__ = 'Darren' def solve(): t1, t2 = map(int, input().split()) cinema = complex(*map(int, input().split())) house = complex(*map(int, input().split())) shop = complex(*map(int, input().split())) cinema_to_house = abs(house - cinema) cinema_to_shop = abs(shop - cinema) shop_to_house = abs(house - shop) alice_max = cinema_to_shop + shop_to_house + t1 bob_max = cinema_to_house + t2 def check(d): c1, c2, c3 = (cinema, d), (house, bob_max-d), (shop, alice_max-d-shop_to_house) for i in range(3): status = intersect(c1, c2) if status == 0: return False if status == 1: return intersect(c1 if c1[1] < c2[1] else c2, c3) for intersection in status: if abs(intersection - c3[0]) - 1e-10 <= c3[1]: return True c1, c2, c3 = c2, c3, c1 if cinema_to_shop + shop_to_house <= bob_max: print(min(alice_max, bob_max)) else: lower, upper = 0, min(alice_max, bob_max) while upper - lower > 1e-10: mid = (lower + upper) * 0.5 if check(mid): lower = mid else: upper = mid print(lower) # See http://mathforum.org/library/drmath/view/51836.html def intersect(a, b): dif = b[0] - a[0] dist = abs(dif) if dist > a[1] + b[1] + 1e-10: # Conservative with this case return 0 if dist <= abs(a[1] - b[1]) - 1e-10: return 1 k = (dist * dist + a[1] * a[1] - b[1] * b[1]) / (2 * dist) u = dif * k / dist v = dif * 1j / dist * (a[1] * a[1] - k * k) ** 0.5 return [a[0]+u+v, a[0]+u-v] if __name__ == '__main__': solve()
1270741500
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["2\n1 2 1 2 2\n2\n2 1 2 1 2 1\n3\n2 3 2 3 1\n1\n1 1 1"]
1f4c3f5e7205fe556b50320cecf66c89
null
The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type β€” the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$. The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.
Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ β€” the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.
The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) β€” the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) β€” the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 2
Python
1,800
train_004.jsonl
40cabc85f756d727eeebc1ed81ae27b8
256 megabytes
["4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10"]
PASSED
from __future__ import division, print_function import sys # sys.setrecursionlimit(10**6) from sys import stdin, stdout import bisect #c++ upperbound import math import heapq def modinv(n,p): return pow(n,p-2,p) def cin(): return map(int,sin().split()) def ain(): #takes array as input return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) import math def Divisors(n) : l = [] for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : if (n // i == i) : l.append(i) else : l.append(i) l.append(n//i) return l """*******************************************************""" def main(): t=inin() for _ in range(t): x=0 n=inin() a=ain() d={} x=0 b=[] b.append(0) l=-1 f=1 for i in range(1,n): if(a[i]!=a[i-1]): x+=1 f=2 x=x%2 else: if(l==-1): l=i b.append(x) if(a[n-1]!=a[0]): if(b[n-1]==b[0]): # print(l) if(l==-1): b[n-1]=2 f=3 else: b[l]=(b[l]+1)%2 x=b[l] for j in range(l+1,n): # print(a[j],a[j-1],x) if(a[j]!=a[j-1]): x+=1 x=x%2 # print(x) b[j]=x for i in range(n): b[i]=b[i]+1 print(f) print(*b) ######## 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()
1585233300
[ "math", "graphs" ]
[ 0, 0, 1, 1, 0, 0, 0, 0 ]
2 seconds
["3\n7\n1\n13\n2"]
0657ce4ce00addefc8469381c57294fc
NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.
You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i&lt;j$$$ and $$$a_i &gt; a_j$$$.
For each test case, output a single integer Β β€” the maximum number of inversions the array can have after performing at most one operation.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)Β β€” 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 2\cdot10^5$$$)Β β€” the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$)Β β€” the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_101.jsonl
b6d2b2e944c334bff017206c3bf95be3
256 megabytes
["5\n\n4\n\n1 0 1 0\n\n6\n\n0 1 0 0 1 0\n\n2\n\n0 0\n\n8\n\n1 0 1 1 0 0 0 1\n\n3\n\n1 1 1"]
PASSED
for s in[*open(0)][2::2]: k=l=m=0;c=s.count('1');n=len(s)//2 for x in map(int,s[::2]):n-=1;k+=x;m=max(m,(n-c,c-n-1)[x]);l+=(x^1)*k print(l+m)
1669041300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2", "0", "1"]
07cbcf6e1f1e7f1a6ec45241cf9ac2a9
NoteFor the first example, the initial configuration of the grid is as follows. The only two possible final non-leaking pipe configurations are as follows: For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.
The first line will contain two single-space separated integers n and m (1 ≀ n, m, nΒ·m ≀ 5Β·105) β€” the number of rows and columns respectively. Then n lines follow, each contains exactly m characters β€” the description of the grid. Each character describes a cell and is either one of these: "1" - "4" β€” a pipe segment of one of four types as described above "." β€” an empty cell
standard output
standard input
Python 2
Python
2,200
train_052.jsonl
352a7b83d05f6f374d044b4a652ede9d
256 megabytes
["2 2\n13\n..", "3 1\n1\n4\n.", "2 2\n3.\n.1"]
PASSED
n,m = map(int, raw_input().split()) mp = [] def checkrow(row): ret = 0 beg = False ok = True for j in range(m): if(mp[row][j] != '.'): if not beg and (mp[row][j] != '1' and mp[row][j] != '2'): ok = False if beg and (mp[row][j] != '3' and mp[row][j] != '4'): ok = False beg = not beg if ok: ret += 1 beg = True ok = True for j in range(m): if(mp[row][j] != '.'): if not beg and (mp[row][j] != '1' and mp[row][j] != '2'): ok = False if beg and (mp[row][j] != '3' and mp[row][j] != '4'): ok = False beg = not beg if ok: ret += 1 return ret def checkcol(col): ret = 0 beg = False ok = True for i in range(n): if(mp[i][col] != '.'): if not beg and (mp[i][col] != '1' and mp[i][col] != '4'): ok = False if beg and (mp[i][col] != '2' and mp[i][col] != '3'): ok = False beg = not beg if ok: ret += 1 beg = True ok = True for i in range(n): if(mp[i][col] != '.'): if not beg and (mp[i][col] != '1' and mp[i][col] != '4'): ok = False if beg and (mp[i][col] != '2' and mp[i][col] != '3'): ok = False beg = not beg if ok: ret += 1 return ret for i in range(n): mp.append(raw_input()) ans = 1 MOD = 1000003 for i in range(n): ans *= checkrow(i) ans %= MOD for i in range(m): ans *= checkcol(i) ans %= MOD print ans
1316098800
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["32"]
9bd6fea892857d7c94ebce4d4cd46d30
null
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
The only line of output should contain the required sum of squares of distances between all pairs of points.
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
standard output
standard input
PyPy 3
Python
1,700
train_014.jsonl
e9d8c82acc841864f5c915598411a186
256 megabytes
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
PASSED
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading threading.stack_size(10**8) sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD #------------------------------------------------------------------------- mod=10**9+7 n=int(input()) a=list() x,y=0,0 r=0 for i in range (n): x1,y1=map(int,input().split()) a.append((x1,y1)) x+=x1 y+=y1 r+=(n-1)*(x1*x1+y1*y1) #print(r,x,y) for i in range (n): p,q=a[i] r-=(p*(x-p)+q*(y-q)) print(r)
1302609600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["code\naj\nabacaba\nll\ncodeforces\naaaak\naaaaj\naaaaa\nzf"]
43081557fe2fbac39dd9b72b137b8fb0
NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.
Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than $$$10$$$), then just writes it out; if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows: 'c'Β β€” is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o'Β β€” is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd'Β β€” is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e'Β β€” is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).
For each test case output the required string $$$s$$$ β€” the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.
The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) β€” the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ β€” the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.
standard output
standard input
PyPy 3-64
Python
800
train_110.jsonl
a73d134fd2ae61615d3be47d57d4c182
256 megabytes
["9\n\n6\n\n315045\n\n4\n\n1100\n\n7\n\n1213121\n\n6\n\n120120\n\n18\n\n315045615018035190\n\n7\n\n1111110\n\n7\n\n1111100\n\n5\n\n11111\n\n4\n\n2606"]
PASSED
import string q = int(input()) for i in range(q): n = int(input()) str = list(input()) def my_function(x): return x[::-1] str = my_function(str) ans = [] while(len(str)): if int(str[0]) == 0: ans.append(string.ascii_lowercase[int(str[2] + str[1])-1]) del str[0:3] else: ans.append(string.ascii_lowercase[int(str[0])-1]) del str[0] answer = "".join(ans) print(my_function(answer))
1662993300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["xab", "?", "cacb"]
a51d2e6e321d7db67687a594a2b85e47
NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?
In a single line print the answer to the problem β€” the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.
standard output
standard input
Python 3
Python
1,200
train_001.jsonl
3a41770ca9acb5ee9aa1c59b19383724
256 megabytes
["2\n?ab\n??b", "2\na\nb", "1\n?a?b"]
PASSED
import sys import itertools WILDCARD = '?' FILL = 'x' def main(): pattern_count = int(sys.stdin.readline()) patterns = itertools.islice(sys.stdin, pattern_count) result = intersect_patterns(p.strip() for p in patterns) print(result) def intersect_patterns(lines): return ''.join(_intersect_patterns(lines)) def _intersect_patterns(lines): first, *patterns = lines for position, char in enumerate(first): unique_chars = set(pattern[position] for pattern in patterns) unique_chars.add(char) unique_chars.discard(WILDCARD) if not unique_chars: yield FILL elif len(unique_chars) == 1: yield unique_chars.pop() else: yield WILDCARD if __name__ == '__main__': main()
1397837400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
3 seconds
["1\n2\n3\n3\n4\n4\n7", "0\n0\n0\n0"]
e25d4d7decfe6e0f5994f615a268b3aa
NoteIn the first example: After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$. After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$. After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$. After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations). After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations: $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$, $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$, $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$, $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$. The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$.
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array; for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array; for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \dots, y_j]$$$.
Print the answer to the initial problem after each query β€” for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.
The first line of the input contains two integers $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) β€” the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.
standard output
standard input
PyPy 2
Python
1,600
train_033.jsonl
06d7e84741d846d6968c4180d9bdf835
256 megabytes
["7 3\n0\n1\n2\n2\n0\n0\n10", "4 3\n1\n2\n1\n2"]
PASSED
#!/usr/bin/env pypy from __future__ import division, print_function from collections import defaultdict, Counter, deque from future_builtins import ascii, filter, hex, map, oct, zip from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement from __builtin__ import xrange as range from math import ceil, factorial from _continuation import continulet from cStringIO import StringIO from io import IOBase import __pypy__ from bisect import bisect, insort, bisect_left, bisect_right from fractions import Fraction from functools import reduce import sys import os import re inf = float('inf') mod_ = int(1e9) + 7 mod = 998244353 def main(): q, x = map(int, input().split()) cnt = [0]*x mex, pointer = 0, 0 for i in range(q): n = int(input())%x cnt[n] += 1 while cnt[pointer] > 0: cnt[pointer] -= 1 mex += 1 pointer = (pointer + 1) % x print(mex) BUFSIZE = 8192 class FastI(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = StringIO() self.newlines = 0 def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count("\n") + (not b) ptr = self._buffer.tell() self._buffer.seek(0, 2), self._buffer.write( b), self._buffer.seek(ptr) self.newlines -= 1 return self._buffer.readline() class FastO(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = __pypy__.builders.StringBuilder() self.write = lambda s: self._buffer.append(s) def flush(self): os.write(self._fd, self._buffer.build()) self._buffer = __pypy__.builders.StringBuilder() def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() def gcd(x, y): while y: x, y = y, x % y return x sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": def bootstrap(cont): call, arg = cont.switch() while True: call, arg = cont.switch(to=continulet( lambda _, f, args: f(*args), call, arg)) cont = continulet(bootstrap) cont.switch() main()
1579703700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["3", "4", "2"]
8cf5d08a319672d9b767d3523eca4df6
NoteIn the first example initially in the bus could be $$$0$$$, $$$1$$$ or $$$2$$$ passengers.In the second example initially in the bus could be $$$1$$$, $$$2$$$, $$$3$$$ or $$$4$$$ passengers.In the third example initially in the bus could be $$$0$$$ or $$$1$$$ passenger.
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If $$$x$$$ is the number of passengers in a bus just before the current bus stop and $$$y$$$ is the number of passengers in the bus just after current bus stop, the system records the number $$$y-x$$$. So the system records show how number of passengers changed.The test run was made for single bus and $$$n$$$ bus stops. Thus, the system recorded the sequence of integers $$$a_1, a_2, \dots, a_n$$$ (exactly one number for each bus stop), where $$$a_i$$$ is the record for the bus stop $$$i$$$. The bus stops are numbered from $$$1$$$ to $$$n$$$ in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$ (that is, at any time in the bus there should be from $$$0$$$ to $$$w$$$ passengers inclusive).
Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.
The first line contains two integers $$$n$$$ and $$$w$$$ $$$(1 \le n \le 1\,000, 1 \le w \le 10^{9})$$$ β€” the number of bus stops and the capacity of the bus. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{6} \le a_i \le 10^{6})$$$, where $$$a_i$$$ equals to the number, which has been recorded by the video system after the $$$i$$$-th bus stop.
standard output
standard input
Python 3
Python
1,400
train_019.jsonl
424f22d64e287927248f09ecc114588c
256 megabytes
["3 5\n2 1 -3", "2 4\n-1 1", "4 10\n2 4 1 2"]
PASSED
n,w=map(int,input().split()) a=list(map(int,input().split())) l=10e7 h=-10e7 s=0 for i in a: s+=i l=min(s,l) h=max(s,h) x=min(w,w-h)-max(0,-1*l)+1 print(max(0,x))
1582202100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["68.538461538\n44.538461538", "-93.666666667\n-74.666666667\n-15.666666667"]
2432a746446990ecc2926bf00807a5ee
null
On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored.The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds will be: .Your task is to find out, where each ball will be t seconds after.
Output n numbers β€” coordinates of the balls t seconds after. Output the numbers accurate to at least 4 digits after the decimal point.
The first line contains two integers n and t (1 ≀ n ≀ 10, 0 ≀ t ≀ 100) β€” amount of balls and duration of the process. Then follow n lines, each containing three integers: xi, vi, mi (1 ≀ |vi|, mi ≀ 100, |xi| ≀ 100) β€” coordinate, speed and weight of the ball with index i at time moment 0. It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;t]).
standard output
standard input
Python 3
Python
2,000
train_047.jsonl
ffeacc886ae41bce894da2615b06bdf7
256 megabytes
["2 9\n3 4 5\n0 7 8", "3 10\n1 2 3\n4 -5 6\n7 -8 9"]
PASSED
class Ball: def __init__(self, x, v, m): self.v = v self.x = x self.m = m def move(self, time): self.x += self.v * time def collisionTime(self, other): if self.v == other.v: return float("inf") t = - (self.x - other.x) / (self.v - other.v) if t < 1e-9: return float("inf") return t def __str__(self): return "Ball(x={:.2f} v={:.2f} m={:.2f})".format(self.x, self.v, self.m) def findFirst(): global nBalls, balls minTime = float("inf") minPairs = [] for i in range(nBalls): for j in range(i + 1, nBalls): time = balls[i].collisionTime(balls[j]) if time < minTime: minTime = time minPairs = [(i, j)] elif abs(time - minTime) < 1e-9: minPairs.append((i, j)) return minTime, minPairs def collidePair(i, j): global balls v1 = balls[i].v v2 = balls[j].v m1 = balls[i].m m2 = balls[j].m balls[i].v = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2) balls[j].v = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2) nBalls, maxTime = map(int, input().split()) balls = [] for i in range(nBalls): x, v, m = map(int, input().split()) balls.append(Ball(x, v, m)) while True: time, pairs = findFirst() if time > maxTime: break for i in range(nBalls): balls[i].move(time) # print(time, maxTime) for i, j in pairs: collidePair(i, j) # print(i, balls[i], j, balls[j]) # print() maxTime -= time for ball in balls: ball.move(maxTime) print("{:.6f}".format(ball.x))
1286802000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["9", "56", "30052700"]
9d4caff95ab182055f83c79dd88e599a
NoteIn the first sample, there are $$$16$$$ subarrays of length $$$3$$$. In order of appearance, they are:$$$[1, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 2]$$$, $$$[2, 2, 1]$$$, $$$[2, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[1, 2, 3]$$$, $$$[2, 3, 2]$$$, $$$[3, 2, 1]$$$. Their sums are $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$8$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$. As $$$\frac{n(n+1)}{2} = 6$$$, the answer is $$$9$$$.
Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \cdot n!$$$.Let $$$1 \leq i \leq j \leq n \cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number).
Output a single integerΒ β€” the number of subarrays of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.
The only line contains one integer $$$n$$$Β ($$$1 \leq n \leq 10^6$$$), as described in the problem statement.
standard output
standard input
PyPy 2
Python
1,700
train_021.jsonl
57d865d2b645d77c39457b58b89d5b4c
256 megabytes
["3", "4", "10"]
PASSED
n = int(raw_input()) MOD = 998244353 answer = 1 factorial = 1 for i in range(1, n + 1): factorial = (factorial * i) % MOD answer = (i * answer + factorial - i) % MOD print(answer)
1546180500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "2", "10"]
3858151e51f6c97abe8904628b70ad7f
NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.
You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.
Print a single integer β€” the answer to the problem.
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.
standard output
standard input
PyPy 3-64
Python
2,400
train_109.jsonl
a01d005189f62bb6e86b50f7ac01d984
256 megabytes
["1\n?W", "2\n??\nW?", "4\nBB\n??\nW?\n??"]
PASSED
MOD = 998244353 facts = [1] for i in range(1, 100001): facts.append(facts[-1] * i % MOD) def qpow(x, y): ret = 1 b = x while y > 0: if y & 1: ret = ret * b % MOD b = b * b % MOD y >>= 1 return ret def inv(x): return qpow(x, MOD - 2) def CC(n, m): return facts[n] * inv(facts[m]) % MOD * inv(facts[n - m]) % MOD n = int(input()) rec = {} WL, WR, BL, BR = 0, 0, 0, 0 for i in range(n): d = input().strip() if d[0] == 'W': WL += 1 if d[0] == 'B': BL += 1 if d[1] == 'W': WR += 1 if d[1] == 'B': BR += 1 rec[d] = rec.get(d, 0) + 1 QL = n - BL - WL QR = n - BR - WR ans = 0 for i in range(BL, n - WL + 1): j = n - i if BR + QR < j or BR > j: continue else: cnt = CC(QL, i - BL) % MOD * CC(QR, j - BR) % MOD ans = (ans + cnt) % MOD if rec.get('BB', 0) == 0 and rec.get('WW', 0) == 0: ans += (MOD - qpow(2, rec.get('??', 0))) % MOD if BL == 0 and WR == 0 or WL == 0 and BR == 0: if BL > 0 or BR > 0 or WL > 0 or WR > 0: ans += 1 else: ans += 2 print(ans % MOD)
1639217100
[ "number theory", "math", "graphs" ]
[ 0, 0, 1, 1, 1, 0, 0, 0 ]
2 seconds
["1 10 0 102 100\n-1\n0 3 100 1 1 2 4\n6 5 10 0 2 3"]
4b512c39e71e34064c820958dde9f4a1
NoteThe first set of input data of the example is analyzed in the main part of the statement.In the second set of input data of the example, it is impossible to assign the positive weights to obtain a given permutation of vertices.
You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of ancestors $$$b$$$ containing $$$n$$$ numbers: $$$b_i$$$ is an ancestor of the vertex with the number $$$i$$$. The ancestor of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the ancestor of $$$5$$$ is $$$1$$$.The root has no ancestor, so for it, the value of $$$b_i$$$ is $$$i$$$ (the root is the only vertex for which $$$b_i=i$$$).For example, if $$$n=5$$$ and $$$b=[3, 1, 3, 3, 1]$$$, then the tree looks like this. An example of a rooted tree for $$$n=5$$$, the root of the tree is a vertex number $$$3$$$. You are given an array $$$p$$$Β β€” a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $$$p$$$.In other words, for a given permutation of vertices $$$p$$$, it is necessary to choose such edge weights so that the condition $$$dist[p_i]&lt;dist[p_{i+1}]$$$ is true for each $$$i$$$ from $$$1$$$ to $$$n-1$$$. $$$dist[u]$$$ is a sum of the weights of the edges on the path from the root to $$$u$$$. In particular, $$$dist[u]=0$$$ if the vertex $$$u$$$ is the root of the tree.For example, assume that $$$p=[3, 1, 2, 5, 4]$$$. In this case, the following edge weights satisfy this permutation: the edge ($$$3, 4$$$) has a weight of $$$102$$$; the edge ($$$3, 1$$$) has weight of $$$1$$$; the edge ($$$1, 2$$$) has a weight of $$$10$$$; the edge ($$$1, 5$$$) has a weight of $$$100$$$. The array of distances from the root looks like: $$$dist=[1,11,0,102,101]$$$. The vertices sorted by increasing the distance from the root form the given permutation $$$p$$$.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.
For each set of input data print the answer on a separate line. If the solution exists, print an array of $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$, where $$$w_i$$$ is the weight of the edge that leads from $$$b_i$$$ to $$$i$$$. For the root there is no such edge, so use the value $$$w_i=0$$$. For all other vertices, the values of $$$w_i$$$ must satisfy the inequality $$$1 \le w_i \le 10^9$$$. There can be equal numbers among $$$w_i$$$ values, but all sums of weights of edges from the root to vertices must be different and satisfy the given permutation. If there are several solutions, output any of them. If no solution exists, output -1.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of input data sets in the test. Each test case consists of three lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that the $$$b$$$ array encodes some rooted tree. The third line contains the given permutation $$$p$$$: $$$n$$$ of different integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
1,500
train_093.jsonl
5e30834226d3c708ee6ab052fff93f7d
256 megabytes
["4\n5\n3 1 3 3 1\n3 1 2 5 4\n3\n1 1 2\n3 1 2\n7\n1 1 2 3 4 5 6\n1 2 3 4 5 6 7\n6\n4 4 4 4 1 1\n4 2 1 5 6 3"]
PASSED
import io, os import sys from sys import stdin from bisect import bisect_left, bisect_right from collections import defaultdict, deque, namedtuple from math import gcd, ceil, floor, factorial from itertools import combinations, permutations input = sys.stdin.buffer.readline # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # input = sys.stdin.readline def main(): test = int(input()) imp = -1 for _ in range(test): n = int(input()) # a = list(map(int, input().split())) # fas = [0] * n # for i in range(n): # fas[i] = a[i] - 1 dist = list(range(n)) # a = list(map(int, input().split())) # for i in range(n): # dist[a[i] - 1] = i es = [0] * n # for i in range(n): # es[i] = dist[i] - dist[fas[i]] b = list(map(int, input().split())) p = list(map(int, input().split())) for i in range(n): dist[p[i] - 1] = i for i in range(n): fa = b[p[i] - 1] es[p[i] - 1] = dist[p[i] - 1] - dist[fa - 1] # print("es", es) if min(es) < 0: print(imp) else: for i in es: print(i, end=" ") print() return main()
1637850900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["0\n2\n0\n3\n0"]
6aca8c549822adbe96a58aee4b0d4b3f
NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is $$$[1, 1, \underline{1}, \underline{1}]$$$ (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is $$$[\underline{-2.5}, -2, \underline{-1.5}, -1, \underline{-0.5}, 0]$$$.
An array $$$a_1, a_2, \ldots, a_n$$$ is good if and only if for every subsegment $$$1 \leq l \leq r \leq n$$$, the following holds: $$$a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.
For each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. Each of the next $$$t$$$ lines contains the description of a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 70$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$): the initial array.
standard output
standard input
PyPy 3-64
Python
1,500
train_101.jsonl
5a93e5ab76d0219b38187402fe3c0ab5
256 megabytes
["5\n4\n1 2 3 4\n4\n1 1 2 2\n2\n0 -1\n6\n3 -2 4 -1 -4 0\n1\n-100"]
PASSED
import sys input = sys.stdin.buffer.readline def gcd(a, b): if a > b: a, b = b, a if b % a==0: return a return gcd(b % a, a) def process(A): n = len(A) if n==1: sys.stdout.write('0\n') return d = {} check = [None for i in range(72**2)] for i in range(72): i2 = i*(i-1)//2 check[i2] = i for i in range(n): for j in range(i): num = A[i]-A[j] den = (i-j) if num==0: den = 1 sign = 1 g = 1 start = A[i] else: if num > 0: sign = 1 else: sign = -1 start = den*A[i]-num*i g = gcd(abs(num), den) num = num//g den = den//g start = den*A[i]-num*i # print(i, j, A[j], A[i], start, num, den) if (start, num, den) not in d: d[(start, num, den)] = 0 d[(start, num, den)]+=1 answer = 0 for x in d: if check[d[x]] is not None: answer = max(answer, check[d[x]]) sys.stdout.write(f'{n-answer}\n') t = int(input()) for i in range(t): n = int(input()) A = [int(x) for x in input().split()] process(A)
1640792100
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
3 seconds
["NO", "YES"]
732b5f6aeec05b721122e36116c7ab0c
NoteIn the first case, Sam removes all the stones and Jon loses.In second case, the following moves are possible by Sam: In each of these cases, last move can be made by Jon to win the game as follows:
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones. The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move. The player who is unable to make a move loses.Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again.Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.
Print a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes)
First line consists of a single integer n (1 ≀ n ≀ 106) β€” the number of piles. Each of next n lines contains an integer si (1 ≀ si ≀ 60) β€” the number of stones in i-th pile.
standard output
standard input
Python 3
Python
2,100
train_017.jsonl
6f9f32231b090a5d134efff2cb3d6688
256 megabytes
["1\n5", "2\n1\n2"]
PASSED
ans=0 for _ in range(int(input())): ans^=int((8*int(input())+1)**0.5-1)//2 print(['YES', 'NO'][ans>0])
1487606700
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["1 1\n6 4"]
2fa3e88688b92c27ad26a23884e26009
NoteIn the first testcase of the sample, $$$GCD(1,1)+LCM(1,1)=1+1=2$$$.In the second testcase of the sample, $$$GCD(6,4)+LCM(6,4)=2+12=14$$$.
You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.
For each testcase, output a pair of positive integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9)$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$. It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ Β β€” the number of testcases. Each testcase consists of one line containing a single integer, $$$x$$$ $$$(2 \le x \le 10^9)$$$.
standard output
standard input
PyPy 2
Python
800
train_001.jsonl
0ea2cc4bd70562c153c5f7ceb84828e4
256 megabytes
["2\n2\n14"]
PASSED
T = input() for _ in xrange(T): x = input() if x % 2 == 0: print "%d %d" % (x//2, x//2) else: print "1 %d" % (x-1)
1584196500
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["0.400000000", "0.642857143"]
fb8fbcf3e38457e45a2552bca15a2cf5
NoteLet's assume that we are given string a = a1a2... a|a|, then let's denote the string's length as |a|, and its i-th character β€” as ai.A substring a[l... r] (1 ≀ l ≀ r ≀ |a|) of string a is string alal + 1... ar.String a is a substring of string b, if there exists such pair of integers l and r (1 ≀ l ≀ r ≀ |b|), that b[l... r] = a.Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value f(x, y) equals 1, for the rest it equals 0. The probability of choosing each pair equals , that's why the answer is Β· 0  +  Β· 1  +  Β· 1  +  Β· 0  +  Β· 0  =   =  0.4.
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β€” the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β€” as y. The Little Elephant gives string x to Furik and string y β€” to Rubik.Let's assume that f(x, y) is the number of such positions of i (1 ≀ i ≀ |x|), that xi = yi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x, y).
On a single line print a real number β€” the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the length of strings a and b. The second line contains string a, the third line contains string b. The strings consist of uppercase English letters only. The length of both strings equals n.
standard output
standard input
Python 2
Python
2,000
train_032.jsonl
85fee5083643132c8b1e894d082b6ab0
256 megabytes
["2\nAB\nBA", "3\nAAB\nCAA"]
PASSED
import sys import copy import os def main(cin): n = int(cin.readline().strip()) a = cin.readline().strip() b = cin.readline().strip() total = 0.0 for i in range(n): total+=(i+1)*(i+1) f = 0.0 s = [0 for i in range(30)] for i in range(n): s[ord(a[i])-ord('A')]+= i+1 f+= s[ord(b[i])-ord('A')] * (n-i) s = [0 for i in range(30)] for i in reversed(range(n)): f+= s[ord(b[i])-ord('A')] * (i+1) s[ord(a[i])-ord('A')]+= n-i print f/total if __name__ == "__main__": cin = sys.stdin if (os.path.exists('best.txt')): cin = open('best.txt') main(cin)
1342020600
[ "probabilities" ]
[ 0, 0, 0, 0, 0, 1, 0, 0 ]
2 seconds
["2", "IMPOSSIBLE"]
77b5bed410d621fb56c2eaebccff5108
NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≀ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≀ 1.
If the notes aren't contradictory, print a single integer β€” the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
The first line contains two space-separated numbers, n and m (1 ≀ n ≀ 108, 1 ≀ m ≀ 105)Β β€” the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≀ di ≀ n, 0 ≀ hdi ≀ 108)Β β€” the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di &lt; di + 1.
standard output
standard input
Python 3
Python
1,600
train_024.jsonl
32835c190c9d3f4511fc97bd989064f4
256 megabytes
["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"]
PASSED
def maxheight(start, end): start_day, start_height = start end_day, end_height = end ddays = end_day - start_day dheight = end_height - start_height xdays = ddays - abs(dheight) if xdays < 0: return -1 else: return xdays // 2 + max(start_height, end_height) import sys data = sys.stdin days = int(data.readline().split()[0]) entries = [] for l in data.read().splitlines(): entries.append(tuple(map(int, l.split(' ')))) entries.sort() maxheights = [] for e in entries: maxheights.append(e[1]) for i in range(len(entries) - 1): h = maxheight(entries[i], entries[i+1]) if h < 0: print("IMPOSSIBLE") break else: maxheights.append(h) else: first = entries[0] maxheights.append(first[0] - 1 + first[1]) last = entries[-1] maxheights.append(days - last[0] + last[1]) print(str(max(maxheights)))
1430064000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["cslnb", "cslnb", "sjfnb", "sjfnb"]
dc225c801f55b8d7b40ebcc71b417edb
NoteIn the first example, Tokitsukaze cannot take any stone, so CSL will win.In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.In the third example, Tokitsukaze will win. Here is one of the optimal ways: Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose. In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tokitsukaze and CSL are playing a little game of stones.In the beginning, there are $$$n$$$ piles of stones, the $$$i$$$-th pile of which has $$$a_i$$$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?Consider an example: $$$n=3$$$ and sizes of piles are $$$a_1=2$$$, $$$a_2=3$$$, $$$a_3=0$$$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $$$[1, 3, 0]$$$ and it is a good move. But if she chooses the second pile then the state will be $$$[2, 2, 0]$$$ and she immediately loses. So the only good move for her is to choose the first pile. Supposing that both players always take their best moves and never make mistakes, who will win the game?Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_1, a_2, \ldots, a_n \le 10^9$$$), which mean the $$$i$$$-th pile has $$$a_i$$$ stones.
standard output
standard input
PyPy 3
Python
1,800
train_001.jsonl
bc8d6485893bdcedcd427ef36d56197e
256 megabytes
["1\n0", "2\n1 0", "2\n2 2", "3\n2 3 1"]
PASSED
from collections import defaultdict FIRST = "sjfnb" SECOND = "cslnb" n = int(input()) arr = list(map(int, input().split())) m = len(set(arr)) if sum(arr) == 0 or arr.count(0) >= 2: print(SECOND) exit() elif m <= n - 2: print(SECOND) exit() elif m == n - 1: d = defaultdict(int) for i in arr: d[i] += 1 for i, j in d.items(): if j == 2: if i-1 in d: print(SECOND) exit() s = 0 for i, j in enumerate(sorted(arr)): s += j - i if s % 2 == 1: print(FIRST) exit() else: print(SECOND) exit()
1562942100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["0", "1", "2", "3", "3", "12345678901234567890", "GOTO Vasilisa."]
3060ecad253a2b4d4fac39e91fcd6c95
null
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part. If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part. If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?
If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).
The first line contains a single number to round up β€” the integer part (a non-empty set of decimal digits that do not start with 0 β€” with the exception of a case when the set consists of a single digit β€” in this case 0 can go first), then follows character Β«.Β» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.
standard output
standard input
PyPy 3
Python
800
train_003.jsonl
77591e8070f7dfe0343f22b3d30ba52e
256 megabytes
["0.0", "1.49", "1.50", "2.71828182845904523536", "3.14159265358979323846", "12345678901234567890.1", "123456789123456789.999"]
PASSED
import decimal D=decimal.Decimal s = input() place = s.index(".") last = s[place-1] next = s[place+1] #print(last,int(next)<5) if last == "9": #and int(next)>=5: print("GOTO Vasilisa.") #elif last=="9" and int(next)<5: #print("HI") #print(s[:place]) elif last!="9" and int(next)>=5: #print("HO") print(s[:place-1]+str((int(s[place-1])+1))) else: #print("NEATO") print(s[:place])
1311346800
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["3 6\n7 5", "2 9\n6 8", "10 6\n4 5", "9 11\n8 10"]
4cabc6c5dca6e67a355315040deb11a0
NoteThe picture corresponding to the first example: The intersection of two paths is $$$2$$$ (vertices $$$1$$$ and $$$4$$$) and the total length is $$$4 + 3 = 7$$$.The picture corresponding to the second example: The intersection of two paths is $$$2$$$ (vertices $$$3$$$ and $$$4$$$) and the total length is $$$5 + 3 = 8$$$.The picture corresponding to the third example: The intersection of two paths is $$$3$$$ (vertices $$$2$$$, $$$7$$$ and $$$8$$$) and the total length is $$$5 + 5 = 10$$$.The picture corresponding to the fourth example: The intersection of two paths is $$$5$$$ (vertices $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$) and the total length is $$$6 + 6 = 12$$$.
You are given an undirected unweighted tree consisting of $$$n$$$ vertices.An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ in such a way that neither $$$x_1$$$ nor $$$y_1$$$ belong to the simple path from $$$x_2$$$ to $$$y_2$$$ and vice versa (neither $$$x_2$$$ nor $$$y_2$$$ should not belong to the simple path from $$$x_1$$$ to $$$y_1$$$).It is guaranteed that it is possible to choose such pairs for the given tree.Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from $$$x_1$$$ to $$$y_1$$$ and from $$$x_2$$$ to $$$y_2$$$. And among all such pairs you have to choose one with the maximum total length of these two paths.It is guaranteed that the answer with at least two common vertices exists for the given tree.The length of the path is the number of edges in it.The simple path is the path that visits each vertex at most once.
Print any two pairs of vertices satisfying the conditions described in the problem statement. It is guaranteed that it is possible to choose such pairs for the given tree.
The first line contains an integer $$$n$$$ β€” the number of vertices in the tree ($$$6 \le n \le 2 \cdot 10^5$$$). Each of the next $$$n - 1$$$ lines describes the edges of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. It is guaranteed that the answer with at least two common vertices exists for the given tree.
standard output
standard input
Python 3
Python
2,500
train_057.jsonl
d7fc06c43f5ac0df38ca31d3ce142708
256 megabytes
["7\n1 4\n1 5\n1 6\n2 3\n2 4\n4 7", "9\n9 3\n3 5\n1 2\n4 3\n4 7\n1 7\n4 6\n3 8", "10\n6 8\n10 3\n3 7\n5 8\n1 7\n7 2\n2 9\n2 8\n1 4", "11\n1 2\n2 3\n3 4\n1 5\n1 6\n6 7\n5 8\n5 9\n4 10\n4 11"]
PASSED
import sys n = int(sys.stdin.readline()) edges = [[] for _ in range(n)] for _ in range(n - 1): i, j = tuple(int(k) for k in sys.stdin.readline().split()) i -= 1 j -= 1 edges[i].append(j) edges[j].append(i) # Prunes the graph starting from the vertices with # only 1 edge until we reach a vertex with 3+ edges. # Stores the distance from each non-pruned vertex # to each of the leaves it reaches. def prune(): pruned = [False for _ in range(n)] leaves = [[] for _ in range(n)] todo = [] for i in range(n): if len(edges[i]) == 1: todo.append((0, i, i)) while len(todo) > 0: d, i, j = todo.pop() pruned[j] = True for k in edges[j]: if not pruned[k]: if len(edges[k]) < 3: todo.append((d + 1, i, k)) else: leaves[k].append((d + 1, i)) return pruned, leaves pruned, leaves = prune() # Returns the furthest non-pruned vertices # from another non-pruned vertex. def furthest(i): assert not pruned[i] visited = list(pruned) top_distance = 0 top_vertices = [i] todo = [(0, i)] while len(todo) > 0: d, i = todo.pop() visited[i] = True if d > top_distance: top_distance = d top_vertices = [] if d == top_distance: top_vertices.append(i) for j in edges[i]: if not visited[j]: todo.append((d + 1, j)) return top_distance, top_vertices # Single center topology. # Only 1 vertex with 3+ edges. def solve_single_center(i): l = list(reversed(sorted(leaves[i])))[:4] return list(l[j][1] for j in range(4)) # Scores non-pruned vertices according to the sum # of the distances to their two furthest leaves. def vertices_score(v): scores = [] for i in v: assert not pruned[i] l = list(reversed(sorted(leaves[i])))[:2] score = (l[0][0] + l[1][0]), l[0][1], l[1][1] scores.append(score) return list(reversed(sorted(scores))) # Single cluster topology. # 1 cluster of vertices, all equally far away from each other. def solve_single_cluster(v): scores = vertices_score(v)[:2] return scores[0][1], scores[1][1], scores[0][2], scores[1][2] # Double cluster topology. # 2 clusters of vertices, pairwise equally far away from each other. def solve_double_cluster(v1, v2): scores1 = vertices_score(v1)[:1] scores2 = vertices_score(v2)[:1] return scores1[0][1], scores2[0][1], scores1[0][2], scores2[0][2] def solve(): def start_vertex(): for i in range(n): if not pruned[i]: return i i = start_vertex() distance, v1 = furthest(i) if distance == 0: return solve_single_center(v1[0]) else: distance, v1 = furthest(v1[0]) distance, v2 = furthest(v1[0]) v = list(set(v1) | set(v2)) if len(v) < len(v1) + len(v2): return solve_single_cluster(v) else: return solve_double_cluster(v1, v2) a, b, c, d = solve() print(a + 1, b + 1) print(c + 1, d + 1)
1540478100
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["113337\n1337"]
9aabacc9817722dc11335eccac5d65ac
null
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given an integer $$$n$$$. You have to find a sequence $$$s$$$ consisting of digits $$$\{1, 3, 7\}$$$ such that it has exactly $$$n$$$ subsequences equal to $$$1337$$$.For example, sequence $$$337133377$$$ has $$$6$$$ subsequences equal to $$$1337$$$: $$$337\underline{1}3\underline{3}\underline{3}7\underline{7}$$$ (you can remove the second and fifth characters); $$$337\underline{1}\underline{3}3\underline{3}7\underline{7}$$$ (you can remove the third and fifth characters); $$$337\underline{1}\underline{3}\underline{3}37\underline{7}$$$ (you can remove the fourth and fifth characters); $$$337\underline{1}3\underline{3}\underline{3}\underline{7}7$$$ (you can remove the second and sixth characters); $$$337\underline{1}\underline{3}3\underline{3}\underline{7}7$$$ (you can remove the third and sixth characters); $$$337\underline{1}\underline{3}\underline{3}3\underline{7}7$$$ (you can remove the fourth and sixth characters). Note that the length of the sequence $$$s$$$ must not exceed $$$10^5$$$.You have to answer $$$t$$$ independent queries.
For the $$$i$$$-th query print one string $$$s_i$$$ ($$$1 \le |s_i| \le 10^5$$$) consisting of digits $$$\{1, 3, 7\}$$$. String $$$s_i$$$ must have exactly $$$n_i$$$ subsequences $$$1337$$$. If there are multiple such strings, print any of them.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) β€” the number of queries. Next $$$t$$$ lines contains a description of queries: the $$$i$$$-th line contains one integer $$$n_i$$$ ($$$1 \le n_i \le 10^9$$$).
standard output
standard input
PyPy 3
Python
1,900
train_040.jsonl
51c5581cac1155fb157b78ae2010b466
256 megabytes
["2\n6\n1"]
PASSED
import sys input = sys.stdin.readline from bisect import bisect_right Q = int(input()) Query = [int(input()) for _ in range(Q)] A = [0] for t in range(1, 10**5): A.append(A[-1]+t) for n in Query: NUMs = [] while n: i = bisect_right(A, n) NUMs.append(i) n -= A[i-1] ans = "1" now = 0 while NUMs: p = NUMs.pop() ans += "3"*(p-now) + "7" now = p print(ans)
1565188500
[ "math", "strings" ]
[ 0, 0, 0, 1, 0, 0, 1, 0 ]
2 seconds
["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"]
a36fb51b1ebb3552308e578477bdce8f
NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.
You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
standard output
standard input
Python 3
Python
1,600
train_059.jsonl
e39eddae0688acafb6355f57cc705c06
256 megabytes
["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"]
PASSED
from itertools import permutations as p l = [list(map(int, input().split())) + [_] for _ in range(1, 9)] def dist(a, b): return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 def rect(a, b, c, d): return dist(a, b) == dist(c, d) and dist(a, c) == dist(b, d) and dist(a, d) == dist(b, c) and dist(a, b) * dist(b, c) != 0 def sq(a, b, c, d): # print(rect(a, b, c, d)) return rect(a, b, c, d) and dist(a, b) == dist(b, c) for t in p(l): if sq(*t[:4]) and rect(*t[4:]): print("YES") print(' '.join([str(_[2]) for _ in t[:4]])) print(' '.join([str(_[2]) for _ in t[4:]])) exit() print("NO")
1323443100
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["-1\n1\n2\n1\n2\n36"]
f3e413954c9c02520fd25bd2cba4747e
NoteIn the third case, $$$4100 = 2050 + 2050$$$.In the fifth case, $$$22550 = 20500 + 2050$$$.
A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.
For each test case, output the minimum number of 2050-numbers in one line. If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead.
The first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.
standard output
standard input
PyPy 3-64
Python
800
train_101.jsonl
0ec72625a943261675a4690af2d46e07
256 megabytes
["6\n205\n2050\n4100\n20500\n22550\n25308639900"]
PASSED
for _ in range(int(input())): n = int(input()) a = n//2050 if n%2050 != 0: print(-1) continue sum = 0 for i in str(a): sum += int(i) if sum: print(sum) else: print(-1)
1619188500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
531746ba8d93a76d5bdf4bab67d9ba19
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$)Β β€” vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$)Β β€” the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$)Β β€” the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
standard output
standard input
PyPy 2
Python
1,900
train_040.jsonl
5ca19367e9cafe4857ecad9cf174b3dc
256 megabytes
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
PASSED
n = input() flag = 0 freq = [0] * (n + 1) for i in xrange(n - 1): a, b = map(int, raw_input().strip().split()) if b != n: flag = 1 break freq[a] += 1 if flag: print "NO" exit() tree = [0] * n tree[0] = n free = 0 freeptr = 1 fillptr = 0 for u in xrange(n - 1, 0, -1): if freq[u] == 0: if free <= 0: flag = 1 break else: while tree[freeptr] != 0: freeptr += 1 if freeptr >= n: flag = 1 break if flag: break tree[freeptr] = u free -= 1 while tree[freeptr] != 0: freeptr += 1 if freeptr >= n: break continue fillptr += freq[u] free += (freq[u] - 1) if fillptr >= n: flag = 1 break tree[fillptr] = u if flag: print "NO" else: print "YES" for i in xrange(n - 1): print tree[i], tree[i + 1]
1537094100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1", "4"]
1a73bda2b9c2038d6ddf39918b90da61
NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) β€” the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
Print the only integer β€” the minimum number of elements Petya needs to add to the array so that its median equals x.
The first input line contains two space-separated integers n and x (1 ≀ n ≀ 500, 1 ≀ x ≀ 105) β€” the initial array's length and the required median's value. The second line contains n space-separated numbers β€” the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.
standard output
standard input
Python 3
Python
1,500
train_002.jsonl
b2490614a4d65c002dc6da8d2a095df7
256 megabytes
["3 10\n10 20 30", "3 4\n1 2 3"]
PASSED
n, x = (int(x) for x in input().split()) a = [int(x) for x in input().split()] hasx = False for ai in a: if ai == x: hasx = True val = 0 if not hasx: a.append(x) val = 1 a = sorted(a) while a[(len(a) - 1) // 2] != x: val += 1 if a[len(a) // 2] > x: a.insert(0, 0) else: a.append(1000000) print(val)
1332516600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES", "NO", "YES"]
8ab4db92e595b6a0a4c020693c5f2b24
NoteIn the first sample, one can act in the following way: Swap second and third columns. Now the table is 1Β 2Β 3Β 4 1Β 4Β 3Β 2 In the second row, swap the second and the fourth elements. Now the table is 1Β 2Β 3Β 4 1Β 2Β 3Β 4
You are given a table consisting of n rows and m columns.Numbers in each row form a permutation of integers from 1 to m.You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to n + 1 actions in total. Operations can be performed in any order.You have to check whether it's possible to obtain the identity permutation 1, 2, ..., m in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.
If there is a way to obtain the identity permutation in each row by following the given rules, print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 20)Β β€” the number of rows and the number of columns in the given table. Each of next n lines contains m integersΒ β€” elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.
standard output
standard input
Python 3
Python
1,500
train_019.jsonl
caa3a3a49a0472c997520b68c756d73a
256 megabytes
["2 4\n1 3 2 4\n1 3 4 2", "4 4\n1 2 3 4\n2 3 4 1\n3 4 1 2\n4 1 2 3", "3 6\n2 1 3 4 5 6\n1 2 4 3 5 6\n1 2 3 4 6 5"]
PASSED
import sys, re, itertools rai=lambda x:list(map(int, x.split())) def pm(a): for l in a: print(l) print() _use_stdin = True if _use_stdin: inp = sys.stdin else: inp = open("input.txt", "r") ls = inp.read().splitlines() n, m = rai(ls[0]) a = [rai(l) for l in ls[1:]] b = list(range(1,m+1)) c = [] def f(x): t = 0 for i, x in enumerate(a[x]): if x != b[i]: t += 1 return t flag = False for i in range(m): for j in range(i, m): for k in range(n): a[k][i], a[k][j] = a[k][j], a[k][i] flag2 = True for k in range(n): if f(k) > 2: flag2 = False break # for k in range(n): # print(a[k], f(k)) # print() if not flag: flag = flag2 for k in range(n): a[k][i], a[k][j] = a[k][j], a[k][i] print("YES" if flag else "NO")
1475928900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["48\n4"]
fe9b1527571ea37f402512ac378dee13
null
We guessed some integer number $$$x$$$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $$$1$$$ and $$$x$$$ in the list.Your task is to find the minimum possible integer $$$x$$$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.You have to answer $$$t$$$ independent queries.
For each query print the answer to it. If the input data in the query is contradictory and it is impossible to find such number $$$x$$$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $$$x$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25$$$) β€” the number of queries. Then $$$t$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) β€” the number of divisors in the list. The second line of the query contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$2 \le d_i \le 10^6$$$), where $$$d_i$$$ is the $$$i$$$-th divisor of the guessed number. It is guaranteed that all values $$$d_i$$$ are distinct.
standard output
standard input
PyPy 3
Python
1,600
train_005.jsonl
413ceadb9fc42985f9f5ddd8107d4bb0
256 megabytes
["2\n8\n8 2 12 6 4 24 16 3\n1\n2"]
PASSED
from bisect import bisect_right as br from bisect import bisect_left as bl from collections import * from itertools import * import functools import sys from math import * from decimal import * from copy import * getcontext().prec = 30 MAX = sys.maxsize MAXN = 10**6+10 MOD = 10**9+7 def isprime(n): n = abs(int(n)) if n < 2: return False if n == 2: return True if not n & 1: return False for x in range(3, int(n**0.5) + 1, 2): if n % x == 0: return False return True def mhd(a,b,x,y): return abs(a-x)+abs(b-y) def numIN(x = " "): return(map(int,sys.stdin.readline().strip().split(x))) def charIN(x= ' '): return(sys.stdin.readline().strip().split(x)) def arrIN(): return list(numIN()) def dis(x,y): a = y[0]-x[0] b = x[1]-y[1] return (a*a+b*b)**0.5 def lgcd(a): g = a[0] for i in range(1,len(a)): g = math.gcd(g,a[i]) return g def ms(a): msf = -MAX meh = 0 st = en = be = 0 for i in range(len(a)): meh+=a[i] if msf<meh: msf = meh st = be en = i if meh<0: meh = 0 be = i+1 return msf,st,en def res(ans,t): print('Case #{}: {} {}'.format(t,ans[0],ans[1])) def divi(n): l = [] for i in range(1,int(n**0.5)+1): if n%i==0: if n//i==i: l.append(i) else: l.append(i) l.append(n//i) return l for _ in range(int(input())): n = int(input()) a = arrIN() a.sort() x = a[0]*a[-1] fl = [0]*MAXN f = 1 for i in a: fl[i] = 1 fl[1] = 1 for j in a: l = divi(j) for i in l: if not fl[i]: print(-1) f = 0 break if not f: break if f: for i in range(n//2+1): if a[i]*a[n-i-1]!=x: print(-1) f = 0 break if f: print(x)
1557844500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["aad", "daab", "-1", "abczaa"]
a1739619b5ee88e22ae31f4d72bed90a
NoteIn the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: n &lt; m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk &lt; qk for some k (1 ≀ k ≀ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.
Print the sought name or -1 if it doesn't exist.
The first line contains a non-empty string s (1 ≀ |s| ≀ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≀ |t| ≀ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.
standard output
standard input
Python 2
Python
1,900
train_058.jsonl
d2f4ac013460c143026454730cbd9230
256 megabytes
["aad\naac", "abad\nbob", "abc\ndefg", "czaaab\nabcdef"]
PASSED
a = raw_input() b = raw_input() c = {} for i in xrange(26): c[chr(i + 97)] = 0 for i in xrange(len(a)): c[a[i]] += 1 pref = '' ans = chr(255) for i in xrange(min(len(a), len(b))): j = chr(ord(b[i]) + 1) while j <= 'z' and c[j] == 0: j = chr(ord(j) + 1) if j <= 'z': suff = j c[j] -= 1 for ch, num in sorted(c.iteritems()): suff += ch * num c[j] += 1 ans = pref + suff if c[b[i]] == 0: break; pref += b[i] c[b[i]] -= 1 if pref == b and len(b) < len(a): ans = pref for ch, num in sorted(c.iteritems()): ans += ch * num if ans == chr(255): ans = -1 print ans
1335078000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["6", "150352234", "1"]
385ac4db5b0e7613b03fb4f1044367dd
NoteHere are all the distinct strings for the first example. The chosen letters 'a' and 'b' are there just to show that the characters in $$$A$$$ are different. "aaa" "aab" = "baa" "aba" "abb" = "bba" "bab" "bbb"
Consider some set of distinct characters $$$A$$$ and some string $$$S$$$, consisting of exactly $$$n$$$ characters, where each character is present in $$$A$$$.You are given an array of $$$m$$$ integers $$$b$$$ ($$$b_1 &lt; b_2 &lt; \dots &lt; b_m$$$). You are allowed to perform the following move on the string $$$S$$$: Choose some valid $$$i$$$ and set $$$k = b_i$$$; Take the first $$$k$$$ characters of $$$S = Pr_k$$$; Take the last $$$k$$$ characters of $$$S = Su_k$$$; Substitute the first $$$k$$$ characters of $$$S$$$ with the reversed $$$Su_k$$$; Substitute the last $$$k$$$ characters of $$$S$$$ with the reversed $$$Pr_k$$$. For example, let's take a look at $$$S =$$$ "abcdefghi" and $$$k = 2$$$. $$$Pr_2 =$$$ "ab", $$$Su_2 =$$$ "hi". Reversed $$$Pr_2 =$$$ "ba", $$$Su_2 =$$$ "ih". Thus, the resulting $$$S$$$ is "ihcdefgba".The move can be performed arbitrary number of times (possibly zero). Any $$$i$$$ can be selected multiple times over these moves.Let's call some strings $$$S$$$ and $$$T$$$ equal if and only if there exists such a sequence of moves to transmute string $$$S$$$ to string $$$T$$$. For the above example strings "abcdefghi" and "ihcdefgba" are equal. Also note that this implies $$$S = S$$$.The task is simple. Count the number of distinct strings.The answer can be huge enough, so calculate it modulo $$$998244353$$$.
Print a single integer β€” the number of distinct strings of length $$$n$$$ with characters from set $$$A$$$ modulo $$$998244353$$$.
The first line contains three integers $$$n$$$, $$$m$$$ and $$$|A|$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le m \le min(\frac n 2, 2 \cdot 10^5)$$$, $$$1 \le |A| \le 10^9$$$) β€” the length of the strings, the size of the array $$$b$$$ and the size of the set $$$A$$$, respectively. The second line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le \frac n 2$$$, $$$b_1 &lt; b_2 &lt; \dots &lt; b_m$$$).
standard output
standard input
Python 3
Python
2,300
train_001.jsonl
25823da0147cebf9b01a2e9dad63a68f
256 megabytes
["3 1 2\n1", "9 2 26\n2 3", "12 3 1\n2 5 6"]
PASSED
n,m,a=map(int,input().split()) b=list(map(int,input().split())) for i in range(m): if i==0: diffs=[b[0]] else: diffs.append(b[i]-b[i-1]) powers=[a%998244353] for i in range(30): powers.append(powers[-1]**2%998244353) def power(x,y,binpowers): prod=1 bits=bin(y)[2:] bits=bits[::-1] for i in range(len(bits)): if bits[i]=="1": prod*=binpowers[i] prod%=998244353 return prod maxi=b[-1] prod1=power(a,n-2*maxi,powers) for guy in diffs: newprod=power(a,guy,powers) newprod=(newprod*(newprod+1))//2 newprod%=998244353 prod1*=newprod prod1%=998244353 print(prod1)
1539269400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["50", "119.4"]
6421a81f85a53a0c8c63fbc32750f77f
NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.
Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.
Print a single real numberΒ β€” the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .
The first line of the input contains a single integer l (1 ≀ l ≀ 1 000)Β β€” the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≀ p, q ≀ 500)Β β€” the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.
standard output
standard input
Python 3
Python
900
train_024.jsonl
34651dcd5e51ba9ffb9d79d3a51843d7
256 megabytes
["100\n50\n50", "199\n60\n40"]
PASSED
l=int(input()) p=int(input()) q=int(input()) print(l * p / float(p + q))
1445763600
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["3\n8 7 9 10 5 6 1 2 3 4", "2\n8 7 10 9 5 6 4 3 2 1", "20\n2 1"]
a375cfcfab66bedb13e3f6f5549cc613
NoteIn the first example the following pairs of pearls are combined: $$$(7, 9)$$$, $$$(10, 5)$$$, $$$(6, 1)$$$, $$$(2, 3)$$$ and $$$(4, 8)$$$. The beauties of connections equal correspondingly: $$$3$$$, $$$3$$$, $$$3$$$, $$$20$$$, $$$20$$$.The following drawing shows this construction.
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklaceΒ β€” do it yourself!". It contains many necklace parts and some magic glue. The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors $$$u$$$ and $$$v$$$ is defined as follows: let $$$2^k$$$ be the greatest power of two dividing $$$u \oplus v$$$Β β€” exclusive or of $$$u$$$ and $$$v$$$. Then the beauty equals $$$k$$$. If $$$u = v$$$, you may assume that beauty is equal to $$$20$$$.Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
The first line should contain a single integer $$$b$$$ denoting the maximum possible beauty of a necklace built from all given parts. The following line should contain $$$2n$$$ distinct integers $$$p_i$$$ $$$(1 \leq p_i \leq 2n)$$$Β β€” the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so $$$1\,4\,3\,2$$$ is not a valid output, whereas $$$2\,1\,4\,3$$$ and $$$4\,3\,1\,2$$$ are). If there are many possible answers, you can print any.
The first line contains $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$Β β€” the number of necklace parts in the box. Each of the next $$$n$$$ lines contains two integers $$$a$$$ and $$$b$$$ $$$(0 \leq a, b &lt; 2^{20})$$$, which denote colors of pearls presented in the necklace parts. Pearls in the $$$i$$$-th line have indices $$$2i - 1$$$ and $$$2i$$$ respectively.
standard output
standard input
PyPy 2
Python
2,500
train_058.jsonl
25d80f4a99574ae9ee6447102525bd6b
512 megabytes
["5\n13 11\n11 1\n3 5\n17 1\n9 27", "5\n13 11\n11 1\n3 5\n17 1\n7 29", "1\n1 1"]
PASSED
import sys range = xrange input = raw_input def eulerian_cycle(coupl, V): for c in coupl: if len(c) & 1: return None m = len(V) >> 1 found = [0]*m cycle = [] stack = [0] while stack: eind = stack.pop() if eind < 0: eind = ~eind cycle.append(eind) node = V[eind ^ 1] else: node = V[eind] while coupl[node]: eind = coupl[node].pop() if not found[eind >> 1]: found[eind >> 1] = 1 stack.append(~eind) stack.append(eind) break if len(cycle) == m: return cycle else: return None inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 m = 20 mshift = 1 << m bitreverse = [0] * mshift for i in range(1, mshift): x = i.bit_length() - 1 bitreverse[i] = (mshift >> x + 1) + bitreverse[i - (1 << x)] n = inp[ii]; ii += 1 A = [bitreverse[a] for a in inp[ii:]] B = [[] for _ in range(mshift)] for i in range(2 * n): B[A[i]].append(i) while len(B) > 1: found = [0] * len(B) bfs = [A[0]] found[A[0]] = 1 count = 0 odd = 0 for val in bfs: t = len(B[val]) count += t odd += t & 1 for i in B[val]: x = A[i ^ 1] if not found[x]: found[x] = 1 bfs.append(x) if not odd and count == 2 * n: break B2 = B[::2] for i in range(1,len(B),2): B2[i >> 1] += B[i] B = B2 for i in range(2 * n): A[i] >>= 1 ans = len(B).bit_length() - 1 for i in range(0, 2 * n, 2): A[i], A[i + 1] = A[i + 1], A[i] cycle = eulerian_cycle(B, A) out = [] for i in cycle: out.append(i ^ 1) out.append(i) print ans print ' '.join(str(x + 1) for x in out)
1591281300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["YES\nNO\nYES\nYES"]
5b1f33228a58d9e14bc9479767532c25
NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.
Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps: the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?
For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) β€” the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) β€” the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) β€” the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) β€” the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,100
train_104.jsonl
7e9210984adc3d1498b25f25fc0e583d
256 megabytes
["4\n25 4\n9 20\n1 1 10\n25 4\n12 20\n1 1 10\n100 1\n45 2\n0 4 10\n9 2\n69 2\n4 2 7"]
PASSED
n = int(input()) for _ in range(n): value = "NO" hc, ac = list(map(int, input().split())) hm, am = list(map(int, input().split())) k,w,a = list(map(int, input().split())) for i in range(0,k+1): y = ac + (k-i)*w x = hc + i*a if(x + am - 1)//am >= (hm + y - 1)//y: value = "YES" break print(value)
1643639700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["hell no", "abacaba", "asd fasd f"]
436c00c832de8df739fc391f2ed6dac4
null
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example: the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.
The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.
standard output
standard input
Python 3
Python
1,500
train_003.jsonl
81c91eaa2e6aaaf750b74806032f632f
256 megabytes
["hellno", "abacaba", "asdfasdf"]
PASSED
q = ['q','w','r','t','p','s','d','f','y','g','h','j','k','l','z','x','c','v','b','n','m'] s = input() if(len(s)<3): print(s) else: a=s[0] b=s[1] print(s[:2],end='') for i in range(2,len(s)): if(s[i] in q and a in q and b in q and not(a==b and b==s[i])): print(' '+s[i],end='') a=' ' b=s[i] else: a=b b=s[i] print(s[i],end='') print()
1505653500
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]