prob_desc_time_limit
stringclasses
21 values
prob_desc_sample_outputs
stringlengths
5
329
src_uid
stringlengths
32
32
prob_desc_notes
stringlengths
31
2.84k
βŒ€
prob_desc_description
stringlengths
121
3.8k
prob_desc_output_spec
stringlengths
17
1.16k
βŒ€
prob_desc_input_spec
stringlengths
38
2.42k
βŒ€
prob_desc_output_to
stringclasses
3 values
prob_desc_input_from
stringclasses
3 values
lang
stringclasses
5 values
lang_cluster
stringclasses
1 value
difficulty
int64
-1
3.5k
βŒ€
file_name
stringclasses
111 values
code_uid
stringlengths
32
32
prob_desc_memory_limit
stringclasses
11 values
prob_desc_sample_inputs
stringlengths
5
802
exec_outcome
stringclasses
1 value
source_code
stringlengths
29
58.4k
prob_desc_created_at
stringlengths
10
10
tags
listlengths
1
5
hidden_unit_tests
stringclasses
1 value
labels
listlengths
8
8
2 seconds
["1 2 3", "1 3 5"]
0d3ac2472990aba36abee156069b1088
NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture. Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.
Print three distinct integers on a single lineΒ β€” the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.
The first line of the input contains a single integer n (3 ≀ n ≀ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≀ xi, yi ≀ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.
standard output
standard input
Python 2
Python
1,600
train_005.jsonl
167eb56cb62429854cc283e46a830e66
256 megabytes
["3\n0 1\n1 0\n1 1", "5\n0 0\n0 2\n2 0\n2 2\n1 1"]
PASSED
def dis(x,y): return x**2+y**2 def check(a,b,c): if (c[1]-b[1])*(b[0]-a[0])==(b[1]-a[1])*(c[0]-b[0]): return True return False def solve(): n=input() points=[] dist=[] for x in xrange(n): points.append(map(int,raw_input().split())) dist.append(dis(points[-1][0],points[-1][1])) indices = sorted(range(n), key = dist.__getitem__) for y in xrange(2,n): if check(points[indices[0]],points[indices[1]],points[indices[y]]): continue else: print indices[0]+1,indices[1]+1,indices[y]+1 break solve()
1454087400
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["59\n778\n148999\n999999920999999999"]
e25e44b8f300d6be856df50bff8ff244
null
In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \cdot 1 + 5 \cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).
For each test case, print one integerΒ β€” the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€” number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10; 1 \le k \le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 = a_1 < a_2 < \dots < a_n \le 9$$$).
standard output
standard input
PyPy 3-64
Python
1,400
train_108.jsonl
7621a7f4622f0e83f253f18bf4f2a2e5
256 megabytes
["4\n3 13\n0 1 2\n2 777\n0 4\n3 255\n0 1 3\n10 1000000000\n0 1 2 3 4 5 6 7 8 9"]
PASSED
import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from collections import Counter from collections import defaultdict as dd # sys.setrecursionlimit(100000000) flush = lambda: stdout.flush() stdstr = lambda: stdin.readline() stdint = lambda: int(stdin.readline()) stdpr = lambda x: stdout.write(str(x)) stdmap = lambda: map(int, stdstr().split()) stdarr = lambda: list(map(int, stdstr().split())) mod = 1000000007 for _ in range(stdint()): n,k = stdmap() k += 1 arr = stdarr() if(n == 1): print(k) continue res = 0 for i in range(n): if(i == n-1): use = k else: use = min(k, int("9" * (arr[i+1]-arr[i]))) add = use * (10**arr[i]) res += add k -= use print(res)
1635518100
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["3\nh e\nl o\nd z", "0", "-1"]
b03895599bd578a83321401428e277da
null
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print Β«-1Β» (without quotes). Otherwise, the first line of output should contain the only integer k (k β‰₯ 0)Β β€” the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
standard output
standard input
Python 3
Python
1,500
train_006.jsonl
0c11657163d91c43516d88667f54b293
256 megabytes
["helloworld\nehoolwlroz", "hastalavistababy\nhastalavistababy", "merrychristmas\nchristmasmerry"]
PASSED
a,b = input(), input() s = "" for i in range(len(a)): x, y = str(max(a[i], b[i])), str(min(a[i], b[i])) if (x in s and x+y not in s) or (y in s and x+y not in s): print('-1') exit() if x+y not in s: s +=" " + x + y lis = [] for i in s.split(): if i[0] != i[1]: lis.append(i[0] + " " + i[1]) print(len(lis)) for i in lis: print(i)
1482656700
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
9 seconds
["YES\nabc", "NO", "YES\nbaaaaaaaaa", "NO"]
8c33618363cacf005e4735cecfdbe2eb
null
You are given a tree consisting of $$$n$$$ vertices, and $$$q$$$ triples $$$(x_i, y_i, s_i)$$$, where $$$x_i$$$ and $$$y_i$$$ are integers from $$$1$$$ to $$$n$$$, and $$$s_i$$$ is a string with length equal to the number of vertices on the simple path from $$$x_i$$$ to $$$y_i$$$.You want to write a lowercase Latin letter on each vertex in such a way that, for each of $$$q$$$ given triples, at least one of the following conditions holds: if you write out the letters on the vertices on the simple path from $$$x_i$$$ to $$$y_i$$$ in the order they appear on this path, you get the string $$$s_i$$$; if you write out the letters on the vertices on the simple path from $$$y_i$$$ to $$$x_i$$$ in the order they appear on this path, you get the string $$$s_i$$$. Find any possible way to write a letter on each vertex to meet these constraints, or report that it is impossible.
If there is no way to meet the conditions on all triples, print NO. Otherwise, print YES in the first line, and a string of $$$n$$$ lowercase Latin letters in the second line; the $$$i$$$-th character of the string should be the letter you write on the $$$i$$$-th vertex. If there are multiple answers, print any of them.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 4 \cdot 10^5$$$; $$$1 \le q \le 4 \cdot 10^5$$$) β€” the number of vertices in the tree and the number of triples, respectively. Then $$$n - 1$$$ lines follow; the $$$i$$$-th of them contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) β€” the endpoints of the $$$i$$$-th edge. These edges form a tree. Then $$$q$$$ lines follow; the $$$j$$$-th of them contains two integers $$$x_j$$$ and $$$y_j$$$, and a string $$$s_j$$$ consisting of lowercase Latin letters. The length of $$$s_j$$$ is equal to the number of vertices on the simple path between $$$x_j$$$ and $$$y_j$$$. Additional constraint on the input: $$$\sum \limits_{j=1}^{q} |s_j| \le 4 \cdot 10^5$$$.
standard output
standard input
PyPy 3-64
Python
2,600
train_110.jsonl
c8bbe3b1d97d762a0751ebd67a89958b
1024 megabytes
["3 2\n2 3\n2 1\n2 1 ab\n2 3 bc", "3 2\n2 3\n2 1\n2 1 ab\n2 3 cd", "10 10\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 2 ab\n1 3 ab\n1 4 ab\n1 5 ab\n1 6 ab\n1 7 ab\n1 8 ab\n1 9 ab\n1 10 ab\n10 2 aba", "10 10\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 2 ab\n1 3 ab\n1 4 aa\n1 5 ab\n1 6 ab\n1 7 ab\n1 8 ab\n1 9 ab\n1 10 ab\n10 2 aba"]
PASSED
class _csr: def __init__(self, n, edges): self.start = [0] * (n + 1) self.elist = [0] * len(edges) for v, _ in edges: self.start[v + 1] += 1 for i in range(1, n + 1): self.start[i] += self.start[i - 1] counter = self.start.copy() for v, e in edges: self.elist[counter[v]] = e counter[v] += 1 class scc_graph: """It calculates the strongly connected components of directed graphs. """ def __init__(self, n): """It creates a directed graph with n vertices and 0 edges. Constraints ----------- > 0 <= n <= 10 ** 8 Complexity ---------- > O(n) """ self.n = n self.edges = [] def add_edge(self, from_, to): """It adds a directed edge from the vertex `from_` to the vertex `to`. Constraints ----------- > 0 <= from_ < n > 0 <= to < n Complexity ---------- > O(1) amortized """ # assert 0 <= from_ < self.n # assert 0 <= to < self.n self.edges.append((from_, to)) def _scc_ids(self): g = _csr(self.n, self.edges) now_ord = 0 group_num = 0 visited = [] low = [0] * self.n order = [-1] * self.n ids = [0] * self.n parent = [-1] * self.n stack = [] for i in range(self.n): if order[i] == -1: stack.append(i) stack.append(i) while stack: v = stack.pop() if order[v] == -1: low[v] = order[v] = now_ord now_ord += 1 visited.append(v) for i in range(g.start[v], g.start[v + 1]): to = g.elist[i] if order[to] == -1: stack.append(to) stack.append(to) parent[to] = v else: low[v] = min(low[v], order[to]) else: if low[v] == order[v]: while True: u = visited.pop() order[u] = self.n ids[u] = group_num if u == v: break group_num += 1 if parent[v] != -1: low[parent[v]] = min(low[parent[v]], low[v]) for i, x in enumerate(ids): ids[i] = group_num - 1 - x return group_num, ids def scc(self): """It returns the list of the "list of the vertices" that satisfies the following. > Each vertex is in exactly one "list of the vertices". > Each "list of the vertices" corresponds to the vertex set of a strongly connected component. The order of the vertices in the list is undefined. > The list of "list of the vertices" are sorted in topological order, i.e., for two vertices u, v in different strongly connected components, if there is a directed path from u to v, the list contains u appears earlier than the list contains v. Complexity ---------- > O(n + m), where m is the number of added edges. """ group_num, ids = self._scc_ids() groups = [[] for _ in range(group_num)] for i, x in enumerate(ids): groups[x].append(i) return groups class two_sat: """It solves 2-SAT. For variables x[0], x[1], ..., x[n-1] and clauses with form > ((x[i] = f) or (x[j] = g)), it decides whether there is a truth assignment that satisfies all clauses. """ def __init__(self, n): """It creates a 2-SAT of n variables and 0 clauses. Constraints ----------- > 0 <= n <= 10 ** 8 Complexity ---------- > O(n) """ self.n = n self._answer = [False] * n self.scc = scc_graph(2 * n) def add_clause(self, i, f, j, g): """It adds a clause ((x[i] = f) or (x[j] = g)). Constraints ----------- > 0 <= i < n > 0 <= j < n Complexity ---------- > O(1) amortized """ # assert 0 <= i < self.n # assert 0 <= j < self.n self.scc.add_edge(2 * i + (f == 0), 2 * j + (g == 1)) self.scc.add_edge(2 * j + (g == 0), 2 * i + (f == 1)) def satisfiable(self): """If there is a truth assignment that satisfies all clauses, it returns `True`. Otherwise, it returns `False`. Constraints ----------- > You may call it multiple times. Complexity ---------- > O(n + m), where m is the number of added clauses. """ _, ids = self.scc._scc_ids() for i in range(self.n): if ids[2 * i] == ids[2 * i + 1]: return False self._answer[i] = (ids[2*i] < ids[2*i+1]) return True def answer(self): """It returns a truth assignment that satisfies all clauses of the last call of `satisfiable`. If we call it before calling `satisfiable` or when the last call of `satisfiable` returns `False`, it returns the list of length n with undefined elements. Complexity ---------- > O(n) """ return self._answer.copy() import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) N,Q = mi() edge = [[] for v in range(N)] for _ in range(N-1): u,v = mi() edge[u-1].append(v-1) edge[v-1].append(u-1) parent = [[-1]*19 for i in range(N)] depth = [0] * N deq = deque([0]) while deq: v = deq.popleft() for nv in edge[v]: if nv==parent[v][0]: continue parent[nv][0] = v depth[nv] = depth[v] + 1 deq.append(nv) for k in range(1,19): for v in range(N): if parent[v][k-1]==-1: parent[v][k] = -1 else: pv = parent[v][k-1] parent[v][k] = parent[pv][k-1] def lca(u,v): if depth[u] > depth[v]: u,v = v,u dd = depth[v] - depth[u] for k in range(19)[::-1]: if dd>>k & 1: v = parent[v][k] if u==v: return u for k in range(19)[::-1]: pu,pv = parent[u][k],parent[v][k] if pu!=pv: u,v = pu,pv return parent[u][0] def path(u,v): L = lca(u,v) res0 = [u] pos = u while pos!=L: pos = parent[pos][0] res0.append(pos) res1 = [v] pos = v while pos!=L: pos = parent[pos][0] res1.append(pos) res1.pop() return res0 + res1[::-1] cand = [None for v in range(N)] string = [] for i in range(Q): u,v,s = input().split() u,v = int(u)-1,int(v)-1 p = path(u,v) n = len(s) for j in range(n): v = p[j] if cand[v] is None: cand[v] = set([s[j],s[-j-1]]) else: cand[v] &= set([s[j],s[-j-1]]) string.append((u,v,s)) for v in range(N): if cand[v] is None: cand[v] = ["a","b"] else: cand[v] = list(cand[v]) + ["(",")"][:2-len(cand[v])] #print(cand) G = two_sat(N+Q) for i in range(Q): u,v,s = string[i] p = path(u,v) n = len(s) for j in range(n): if s[j]==s[-j-1]: continue v = p[j] t = s[j] if t==cand[v][0]: G.add_clause(i+N,1,v,0) elif t==cand[v][1]: G.add_clause(i+N,1,v,1) else: G.add_clause(i+N,1,i+N,1) t = s[-j-1] if t==cand[v][0]: G.add_clause(i+N,0,v,0) elif t==cand[v][1]: G.add_clause(i+N,0,v,1) else: G.add_clause(i+N,0,i+N,0) check = G.satisfiable() if not check: exit(print("NO")) ans = G.answer() res = [] for v in range(N): if ans[v]: res.append(cand[v][1]) else: res.append(cand[v][0]) #print(res,ans) for i in range(Q): u,v,s = string[i] p = path(u,v) n = len(s) if any(res[p[j]]!=s[j] for j in range(n)) and any(res[p[j]]!=s[-j-1] for j in range(n)): exit(print("NO")) print("YES") print("".join(res))
1647960300
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["6", "92", "17", "23"]
d1dced03a12dd64b8c7519bfb12f9c82
NoteIn the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.
Since you are the best Wraith King, Nizhniy Magazin Β«MirΒ» at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.
Output a single integer Β β€” the smallest possible sum of values of these subarrays of some partition of a.
The first line contains integers n and c (1 ≀ n, c ≀ 100 000). The second line contains n integers ai (1 ≀ ai ≀ 109)Β β€” elements of a.
standard output
standard input
Python 3
Python
2,000
train_040.jsonl
3361dccd6f73a60c04d5b1332a888450
256 megabytes
["3 5\n1 2 3", "12 10\n1 1 10 10 10 10 10 10 9 10 10 10", "7 2\n2 3 6 4 5 7 1", "8 4\n1 3 4 5 5 3 4 1"]
PASSED
from heapq import * n, c = map(int, input().split()) a = list(map(int, input().split())) if c > n: print(sum(a)) exit() b = [0] * n s = 0 h = [] for i in range(n): s = s + a[i] - a[i-c] if i + 1 > c else s + a[i] heappush(h, (a[i],i)) if i + 1 < c: b[i] = s else: while h[0][1] <= i-c: heappop(h) v1 = b[i-1] + a[i] v2 = b[i-c] + s - h[0][0] b[i] = min(v1, v2) print(b[-1])
1519464900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["60\n200\n65\n60\n120600000\n10\n100\n200\n100\n7"]
83af7209bb8a81cde303af5d207c2749
NoteIn the first case $$$n = 6$$$, $$$m = 11$$$. We cannot get a number with two zeros or more at the end, because we need to increase the price $$$50$$$ times, but $$$50 &gt; m = 11$$$. The maximum price multiple of $$$10$$$ would be $$$6 \cdot 10 = 60$$$.In the second case $$$n = 5$$$, $$$m = 43$$$. The maximum price multiple of $$$100$$$ would be $$$5 \cdot 40 = 200$$$.In the third case, $$$n = 13$$$, $$$m = 5$$$. All possible new prices will not end in $$$0$$$, then you should output $$$n \cdot m = 65$$$.In the fourth case, you should increase the price $$$15$$$ times.In the fifth case, increase the price $$$12000$$$ times.
Inflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good $$$n$$$ is given. It is allowed to increase the price of the good by $$$k$$$ times, with $$$1 \le k \le m$$$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output $$$n \cdot m$$$ (that is, the maximum possible price).
For each test case, output on a separate line the roundest integer of the form $$$n \cdot k$$$ ($$$1 \le k \le m$$$, $$$k$$$Β β€” an integer). If there are several possible variants, output the one in which the new price (value $$$n \cdot k$$$) is maximal. If it is impossible to get a more rounded price, output $$$n \cdot m$$$ (that is, the maximum possible price).
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€”the number of test cases in the test. Each test case consists of one line. This line contains two integers: $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$). Where $$$n$$$ is the old price of the good, and the number $$$m$$$ means that you can increase the price $$$n$$$ no more than $$$m$$$ times.
standard output
standard input
PyPy 3-64
Python
1,400
train_086.jsonl
92b6e6b90e0f639998c50c25c9d752f1
256 megabytes
["10\n\n6 11\n\n5 43\n\n13 5\n\n4 16\n\n10050 12345\n\n2 6\n\n4 30\n\n25 10\n\n2 81\n\n1 7"]
PASSED
#I = lambda: [int(i) for i in input().split()] #import io, os, sys #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import Counter,defaultdict,deque #from heapq import heappush,heappop,heapify import sys import math import bisect def lcm(a,b): return ((a*b)//math.gcd(a,b)) def all_factors(n): """returns a sorted list of all distinct factors of n""" small, large = [], [] for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1): if not n % i: small.append(i) large.append(n // i) if small[-1] == large[-1]: large.pop() large.reverse() small.extend(large) return small # n = int(input()) # l1 = list(map(int,input().split())) # n,x = map(int,input().split()) # s = input() mod = 1000000007 # print("Case #"+str(_+1)+":",) def f(x): l = [x,0,0] while(x%2==0 or x%5==0): if x%2==0: l[1]+=1 x = x//2 if x%5==0: l[2]+=1 x = x//5 l[0] = x return l def count(x): c = 0 x = str(x) for i in range(len(x)-1,-1,-1): if x[i] != '0': break c+=1 return c for _ in range(int(input())): n,m = map(int,input().split()) a = f(n) x = 1 px = -1 t1 = a[1] t2 = a[2] a[1] -= min(t1,t2) a[2] -= min(t1,t2) while(x < m and (a[1] or a[2])): if x==px: break px = x if a[1] and x*5<=m: x*=5 a[1]-=1 if a[2] and x*2<=m: x*=2 a[2]-=1 while(x*10 < m): x*=10 x = x*(m//x) ans = n*x print(ans) '''if count(ans)-count(n) > count(m): print(ans) else: while(x < m): x = x+(pow(10,len(str(m))-1)) t = n*x if count(t)>=count(ans): ans = max(ans,t) print(ans)'''
1668782100
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
2 seconds
["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"]
02bdd12987af6e666d4283f075f73725
null
A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in itΒ β€” the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$Β β€” that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$Β β€” that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$Β β€” that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$Β β€” that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.
For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$)Β β€” the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the required length of permutations in the chain.
standard output
standard input
Python 3
Python
800
train_109.jsonl
bc346aef51ae35693acf3a0678142daa
256 megabytes
["2\n\n2\n\n3"]
PASSED
# -*- coding: utf-8 -*- """ Created on Thu Aug 18 23:35:19 2022 @author: khale """ t = int(input()) for i in range(t): n = int(input()) print(n) L = [int(x) for x in range(1,n+1)] for i in range(n-1,-1,-1): for j in range(n): print(L[j],end = ' ') print() var = L[i] L[i] = L[i-1] L[i-1] = var
1659623700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["roar", "db", "-1"]
b5d0870ee99e06e8b99c74aeb8e81e01
null
Limak is a little polar bear. He likes nice strings β€” strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
If there is no string satisfying the given conditions then print "-1" (without the quotes). Otherwise, print any nice string s' that .
The first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 106). The second line contains a string s of length n, consisting of lowercase English letters.
standard output
standard input
Python 3
Python
1,300
train_029.jsonl
ca227e5919ae5760780c48c4b1f2fac4
256 megabytes
["4 26\nbear", "2 7\naf", "3 1000\nhey"]
PASSED
import sys n, k = map(int, input().split()) line = list(input()) for i in range(n): if ord('z') - ord(line[i]) >= ord(line[i]) - ord('a'): s = ord('z') - ord(line[i]) if s >= k: line[i] = chr(ord(line[i])+k) print(''.join(line)) sys.exit() else: line[i] = 'z' k -= s else: s = ord(line[i]) - ord('a') if s >= k: line[i] = chr(ord(line[i])-k) print(''.join(line)) sys.exit() else: line[i] = 'a' k -= s print(-1)
1455894000
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["1\n2\n0"]
0d8b5bd6c118f98d579da8c79482cfa7
NoteOn the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.On the second operation the string "01100" is created. Now all strings of length k = 2 are present.On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Print m lines, each should contain one integerΒ β€” the answer to the question after the corresponding operation.
The first line contains single integer n (1 ≀ n ≀ 100)Β β€” the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≀ |si| ≀ 100), one per line. The total length of strings is not greater than 100. The next line contains single integer m (1 ≀ m ≀ 100)Β β€” the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≀ ai, bi ≀ n + i - 1)Β β€” the number of strings that are concatenated to form sn + i.
standard output
standard input
Python 3
Python
2,200
train_000.jsonl
9758856c8d15338d2e1bde5c057921ba
256 megabytes
["5\n01\n10\n101\n11111\n0\n3\n1 2\n6 5\n4 4"]
PASSED
from sys import stdin, stdout K = 20 def findAllStrings(s): n = len(s) sDict = {} for i in range(1,K+1): sDict[i]=set() for x in range(n-i+1): sDict[i].add(s[x:x+i]) return sDict n = int(stdin.readline().rstrip()) stringDicts = [] stringEnd = [] stringBegin = [] for i in range(n): s = stdin.readline().rstrip() stringDicts.append(findAllStrings(s)) if len(s)<K: stringEnd.append(s) stringBegin.append(s) else: stringEnd.append(s[-20:]) stringBegin.append(s[:20]) m = int(stdin.readline().rstrip()) for _ in range(m): a,b = map(int,stdin.readline().rstrip().split()) a-=1 b-=1 sDict1 = findAllStrings(stringEnd[a]+stringBegin[b]) sDict2 = stringDicts[a] sDict3 = stringDicts[b] sDict={} for i in range(1,K+1): sDict[i] = sDict1[i]|sDict2[i]|sDict3[i] stringDicts.append(sDict) for i in range(1,K+1): if len(sDict[i])!=2**i: print(i-1) break if len(stringBegin[a])<K and len(stringBegin[a])+len(stringBegin[b])<K: stringBegin.append(stringBegin[a]+stringBegin[b]) elif len(stringBegin[a])<K: s = stringBegin[a]+stringBegin[b] stringBegin.append(s[:K]) else: stringBegin.append(stringBegin[a]) if len(stringEnd[b])<K and len(stringEnd[a])+len(stringEnd[b])<K: stringEnd.append(stringEnd[a]+stringEnd[b]) elif len(stringEnd[b])<K: s = stringEnd[a]+stringEnd[b] stringEnd.append(s[-K:]) else: stringEnd.append(stringEnd[b])
1507187100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["ac\nf\nb"]
83a665723ca4e40c78fca20057a0dc99
null
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an β€” Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of $$$n$$$ lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.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$$$. A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find out what the MEX of the string is!
For each test case, output the MEX of the string on a new line.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$)Β β€” the length of the word. The second line for each test case contains a single string of $$$n$$$ lowercase Latin letters. The sum of $$$n$$$ over all test cases will not exceed $$$1000$$$.
standard output
standard input
PyPy 3-64
Python
1,200
train_094.jsonl
5afaefde3eecdb9de18fd9dbac541ced
256 megabytes
["3\n28\nqaabzwsxedcrfvtgbyhnujmiklop\n13\ncleanairactbd\n10\naannttoonn"]
PASSED
t=int(input()) for p in range(t): n=int(input()) a=input() o=0 l=1 if len(set(a))==26: o=1 for i in 'abcdefghijklmnopqrstuvwxyz': if i not in a: print(i) break elif o==1: for j in 'abcdefghijklmnopqrstuvwxyz': if i+j not in a and n<676: print(i+j) l=0 break if n>676: for x in 'abcdefghijklmnopqrstuvwxyz': if i+j+x not in a: print(i+j+x) l=0 break if l==0: break if l==0: break
1622990100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["? 1 2\n\n? 3 2\n\n? 1 3\n\n? 2 1\n\n! 1 3 2"]
9bfbd68e61f4d2f3d404fd0413aded35
null
This is an interactive problem.We hid from you a permutation $$$p$$$ of length $$$n$$$, consisting of the elements from $$$1$$$ to $$$n$$$. You want to guess it. To do that, you can give us 2 different indices $$$i$$$ and $$$j$$$, and we will reply with $$$p_{i} \bmod p_{j}$$$ (remainder of division $$$p_{i}$$$ by $$$p_{j}$$$).We have enough patience to answer at most $$$2 \cdot n$$$ queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length $$$n$$$ 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).
null
The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) β€” length of the permutation.
standard output
standard input
PyPy 3
Python
1,600
train_000.jsonl
ee560325f27fefa25653b9210ee8221a
256 megabytes
["3\n\n1\n\n2\n\n1\n\n0"]
PASSED
import os from io import BytesIO, IOBase import sys from math import * from collections import Counter def main(): n=int(input()) ans=[n]*(n+1) z=set(range(1,n+1)) while len(z)!=1: a,b=z.pop(),z.pop() print('?',a,b,flush=True) x=int(input()) print('?',b,a,flush=True) y=int(input()) if x>y: ans[a]=x z.add(b) else: ans[b]=y z.add(a) print("!",*ans[1:],flush=True) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
1599575700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["ccccc\ncccc\nkekeke"]
b8ffd93a80c840ea645c6797f8ee269c
NoteIn the first test case, "aaaaa" and "bbbbb" exchanged all positions, and "ccccc" is the stolen string.In the second test case, "aaaa" and "bbbb" exchanged two first positions, and "cccc" is the stolen string.This is the first test in the hack format: 33 5aaaaabbbbbccccc1 2 5 1 2 3 4 52 1 33 4aaaabbbbcccc1 2 2 1 22 1 35 6abcdefuuuuuukekekeekekekxyzklm1 5 3 2 3 62 4 3 2 4 65 4 1 2 3
AquaMoon had $$$n$$$ strings of length $$$m$$$ each. $$$n$$$ is an odd number.When AquaMoon was gone, Cirno tried to pair these $$$n$$$ strings together. After making $$$\frac{n-1}{2}$$$ pairs, she found out that there was exactly one string without the pair!In her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least $$$1$$$ and at most $$$m$$$) and swapped the letters in the two strings of this pair at the selected positions.For example, if $$$m = 6$$$ and two strings "abcdef" and "xyzklm" are in one pair and Cirno selected positions $$$2$$$, $$$3$$$ and $$$6$$$ she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be "ayzdem" and "xbcklf".Cirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.AquaMoon found the remaining $$$n-1$$$ strings in complete disarray. Also, she remembers the initial $$$n$$$ strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?
For each test case print a single line with the stolen string.
This problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an "Idleness limit exceeded" verdict. Refer to the interactive problems guide for the detailed information about flushing the output buffer. The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) β€” the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq m \leq 10^5$$$) β€” the number of strings and the length of each string, respectively. The next $$$n$$$ lines each contain a string with length $$$m$$$, describing the original $$$n$$$ strings. All string consists of lowercase Latin letters. The next $$$n-1$$$ lines each contain a string with length $$$m$$$, describing the strings after Cirno exchanged and reordered them. It is guaranteed that $$$n$$$ is odd and that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$. Hack format: The first line should contain a single integer $$$t$$$. After that $$$t$$$ test cases should follow in the following format: The first line should contain two integers $$$n$$$ and $$$m$$$. The following $$$n$$$ lines should contain $$$n$$$ strings of length $$$m$$$, describing the original strings. The following $$$\frac{n-1}{2}$$$ lines should describe the pairs. They should contain, in the following order: the index of the first string $$$i$$$ ($$$1 \leq i \leq n$$$), the index of the second string $$$j$$$ ($$$1 \leq j \leq n$$$, $$$i \neq j$$$), the number of exchanged positions $$$k$$$ ($$$1 \leq k \leq m$$$), and the list of $$$k$$$ positions that are exchanged ($$$k$$$ distinct indices from $$$1$$$ to $$$m$$$ in any order). The final line should contain a permutation of integers from $$$1$$$ to $$$n$$$, describing the way the strings should be reordered. The strings will be placed in the order indices placed in this permutation, the stolen string index will be ignored.
standard output
standard input
PyPy 3-64
Python
1,200
train_086.jsonl
2c40c76404794e5e6d40c596c8e74062
256 megabytes
["3\n3 5\naaaaa\nbbbbb\nccccc\naaaaa\nbbbbb\n3 4\naaaa\nbbbb\ncccc\naabb\nbbaa\n5 6\nabcdef\nuuuuuu\nkekeke\nekekek\nxyzklm\nxbcklf\neueueu\nayzdem\nukukuk"]
PASSED
import sys;input=sys.stdin.readline for i in' '*int(input()): n,m=map(int,input().split()) l=[set()for i in' '*m] for i in range(n+n-1): s=input().strip() for i in range(m): l[i]^={s[i]} for i in l:print(*i,end='') print()
1626012300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n011", "3\n1101", "-1\n11111"]
f26a979dc042ec9564cfecce29e5a1cf
NoteFor the first sample, if we paint city $$$1$$$ white, the shortest path is $$$1 \rightarrow 3$$$. Otherwise, it's $$$1 \rightarrow 2 \rightarrow 3$$$ regardless of other cities' colors.For the second sample, we should paint city $$$3$$$ black, and there are both black and white roads going from $$$2$$$ to $$$4$$$. Note that there can be a road connecting a city with itself.
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are $$$n$$$ cities in the republic, some of them are connected by $$$m$$$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $$$1$$$, travel to the city $$$n$$$ by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads β€” in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $$$1$$$ to $$$n$$$, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $$$1$$$ to $$$n$$$ or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.
In the first line output the length of the desired path (or $$$-1$$$, if it's possible to choose such schedule that there's no path from $$$1$$$ to $$$n$$$). In the second line output the desired schedule β€” a string of $$$n$$$ digits, where $$$i$$$-th digit is $$$0$$$, if the $$$i$$$-th city is a night one, and $$$1$$$ if it's a morning one. If there are multiple answers, print any.
The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) β€” the number of cities and the number of roads. The $$$i$$$-th of next $$$m$$$ lines contains three integers β€” $$$u_i$$$, $$$v_i$$$ and $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) β€” numbers of cities connected by road and its type, respectively ($$$0$$$ β€” night road, $$$1$$$ β€” morning road).
standard output
standard input
Python 3
Python
2,500
train_014.jsonl
4f9ced91d064181782cd36da35312be2
256 megabytes
["3 4\n1 2 0\n1 3 1\n2 3 0\n2 3 1", "4 8\n1 1 0\n1 3 0\n1 3 1\n3 2 0\n2 1 0\n3 4 1\n2 4 0\n2 4 1", "5 10\n1 2 0\n1 3 1\n1 4 0\n2 3 0\n2 3 1\n2 5 0\n3 4 0\n3 4 1\n4 2 1\n4 5 0"]
PASSED
import sys input = sys.stdin.readline from collections import deque n, m = map(int, input().split());back = [[] for i in range(n)] for _ in range(m):u, v, w = map(int, input().split());u -= 1;v -= 1;back[v].append((u,w)) out = [2] * n;outl = [-1] * n;outl[-1] = 0;q = deque([n - 1]) while q: v = q.popleft() for u, w in back[v]: if out[u] != w:out[u] = 1 - w else: if outl[u] == -1:outl[u] = outl[v] + 1;q.append(u) out = [v if v != 2 else 1 for v in out];print(outl[0]);print(''.join(map(str,out)))
1599575700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["2"]
973044bfba063f34c956c0bbc042f903
NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one, getting $$$2$$$ for it.
Kuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get $$$0$$$ coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). $$$n$$$ people have heard about Antihype recently, the $$$i$$$-th person's age is $$$a_i$$$. Some of them are friends, but friendship is a weird thing now: the $$$i$$$-th person is a friend of the $$$j$$$-th person if and only if $$$a_i \text{ AND } a_j = 0$$$, where $$$\text{AND}$$$ denotes the bitwise AND operation.Nobody among the $$$n$$$ people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them?
Output exactly one integer Β β€” the maximum possible combined gainings of all $$$n$$$ people.
The first line contains a single integer $$$n$$$ ($$$1\le n \le 2\cdot 10^5$$$) Β β€” the number of people. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 2\cdot 10^5$$$) Β β€” the ages of the people.
standard output
standard input
PyPy 2
Python
3,500
train_081.jsonl
3cd652bf98eca7afce71c120fc3f628b
256 megabytes
["3\n1 2 3"]
PASSED
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()] n = inp[0] + 1 A = inp inp[0] = 0 # Dsu with O(1) lookup and O(log(n)) merge m = 2**18 count = [0]*m owner = list(range(m)) sets = [[i] for i in range(m)] for a in A: count[a] += 1 total = 0 for profit in reversed(range(m)): a = profit b = a ^ profit while a > b: if count[a] and count[b] and owner[a] != owner[b]: total += (count[a] + count[b] - 1) * (a ^ b) count[a] = 1 count[b] = 1 small = owner[a] big = owner[b] if len(sets[small]) > len(sets[big]): small, big = big, small for c in sets[small]: owner[c] = big sets[big] += sets[small] a = (a - 1) & profit b = a ^ profit print total - sum(A)
1583246100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["2", "2", "0", "3"]
c083988d20f434d61134f7b376581eb6
NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$.
You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \in [1, n]$$$ let $$$c_i := d \cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?
Print one integer β€” the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$).
standard output
standard input
PyPy 2
Python
1,500
train_017.jsonl
e33e15a6ad498891794622e070b3f654
256 megabytes
["5\n1 2 3 4 5\n2 4 7 11 3", "3\n13 37 39\n1 2 3", "4\n0 0 0 0\n1 2 3 4", "3\n1 2 -1\n-6 -12 6"]
PASSED
# @-*- coding: utf-8 -*- # @Time: 2018-10-21T21:21:26+08:00 # @Email: [email protected] import sys import math import bisect from collections import defaultdict MOD = int(1e9+7) # n = map(int, raw_input().split()) n = int(raw_input()) a = map(int, raw_input().split()) b = map(int, raw_input().split()) ck = defaultdict(int) def gcd(x, y): while (y): x, y = y, x % y return x tt = 0 for i, j in zip(a,b): if i == 0: if j == 0: tt += 1 else: k = gcd(i, j) ck[(i/k, j/k)] += 1 if not ck: print 0+tt else: print max(ck.values())+tt
1551971100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["3 3", "4", "0 1"]
2c51414eeb430ad06aac53a99ff95eff
NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.
Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.
Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.
The first line contains two integers n, A (1 ≀ n ≀ 2Β·105, n ≀ A ≀ s) β€” the number of dice and the sum of shown values where s = d1 + d2 + ... + dn. The second line contains n integers d1, d2, ..., dn (1 ≀ di ≀ 106), where di is the maximum value that the i-th dice can show.
standard output
standard input
Python 3
Python
1,600
train_025.jsonl
689bd0a7dfe7f67fdcad310b6ce3c121
256 megabytes
["2 8\n4 4", "1 3\n5", "2 3\n2 3"]
PASSED
n, a = map(int, input().split()) d = list(map(int, input().split())) s = sum(d) def solve(): for x in d: yield max(x - (a - n + 1), 0) + max(a - (s - x) - 1, 0) print(' '.join(map(str, solve())))
1428854400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["10\n6\n7"]
690c28ef1275035895b9154ff0e17f4c
NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.
Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.
For each testcase, print a single integerΒ β€” the least amount of mana required for Monocarp to kill all monsters.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β€” the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$)Β β€” the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 &lt; k_2 &lt; \dots &lt; k_n$$$ ($$$1 \le k_i \le 10^9$$$)Β β€” the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$)Β β€” the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.
standard output
standard input
PyPy 3-64
Python
1,700
train_087.jsonl
5a2520d4c4647ad0fe9c7be5d546c1a4
256 megabytes
["3\n\n1\n\n6\n\n4\n\n2\n\n4 5\n\n2 2\n\n3\n\n5 7 9\n\n2 1 2"]
PASSED
import sys input = lambda: sys.stdin.readline().rstrip("\r\n") def solve(): n = int(input()) k = [0] for i in list(map(int, input().split())): k.append(i) h = [0] for i in list(map(int, input().split())): h.append(i) i = n ans = 0 while i > 0: poneat = k[i] - h[i] + 1 j = i - 1 while j > 0 and poneat <= k[j]: poneat = min(poneat, k[j] - h[j] + 1) j -= 1 t = k[i] - poneat + 1 ans += (t * (t + 1)) // 2 i = j print(ans) for _ in range(int(input())): solve()
1642343700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["-1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3", "-1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1"]
a592b3cf7ecac3d56fe4e99e35d454f6
NoteIn the first sample input, let us see how to create $$$16$$$ number of bananas in three timesteps. Initially, $$$k=0$$$. In timestep 1, we choose $$$a_1=2$$$, so we apply the type 1 update β€” $$$k := \lceil(k+3)\rceil$$$ β€” two times. Hence, $$$k$$$ is now 6. In timestep 2, we choose $$$a_2=0$$$, hence value of $$$k$$$ remains unchanged. In timestep 3, we choose $$$a_3=1$$$, so we are applying the type 1 update $$$k:= \lceil(k+10)\rceil$$$ once. Hence, $$$k$$$ is now 16. It can be shown that $$$k=16$$$ cannot be reached in fewer than three timesteps with the given operations.In the second sample input, let us see how to create $$$17$$$ number of bananas in two timesteps. Initially, $$$k=0$$$. In timestep 1, we choose $$$a_1=1$$$, so we apply the type 1 update β€” $$$k := \lceil(k+3.99999)\rceil$$$ β€” once. Hence, $$$k$$$ is now 4. In timestep 2, we choose $$$a_2=1$$$, so we apply the type 2 update β€” $$$k := \lceil(k\cdot 4.12345)\rceil$$$ β€” once. Hence, $$$k$$$ is now 17. It can be shown that $$$k=17$$$ cannot be reached in fewer than two timesteps with the given operations.
You have a malfunctioning microwave in which you want to put some bananas. You have $$$n$$$ time-steps before the microwave stops working completely. At each time-step, it displays a new operation.Let $$$k$$$ be the number of bananas in the microwave currently. Initially, $$$k = 0$$$. In the $$$i$$$-th operation, you are given three parameters $$$t_i$$$, $$$x_i$$$, $$$y_i$$$ in the input. Based on the value of $$$t_i$$$, you must do one of the following:Type 1: ($$$t_i=1$$$, $$$x_i$$$, $$$y_i$$$) β€” pick an $$$a_i$$$, such that $$$0 \le a_i \le y_i$$$, and perform the following update $$$a_i$$$ times: $$$k:=\lceil (k + x_i) \rceil$$$.Type 2: ($$$t_i=2$$$, $$$x_i$$$, $$$y_i$$$) β€” pick an $$$a_i$$$, such that $$$0 \le a_i \le y_i$$$, and perform the following update $$$a_i$$$ times: $$$k:=\lceil (k \cdot x_i) \rceil$$$.Note that $$$x_i$$$ can be a fractional value. See input format for more details. Also, $$$\lceil x \rceil$$$ is the smallest integer $$$\ge x$$$.At the $$$i$$$-th time-step, you must apply the $$$i$$$-th operation exactly once.For each $$$j$$$ such that $$$1 \le j \le m$$$, output the earliest time-step at which you can create exactly $$$j$$$ bananas. If you cannot create exactly $$$j$$$ bananas, output $$$-1$$$.
Print $$$m$$$ integers, where the $$$i$$$-th integer is the earliest time-step when you can obtain exactly $$$i$$$ bananas (or $$$-1$$$ if it is impossible).
The first line contains two space-separated integers $$$n$$$ $$$(1 \le n \le 200)$$$ and $$$m$$$ $$$(2 \le m \le 10^5)$$$. Then, $$$n$$$ lines follow, where the $$$i$$$-th line denotes the operation for the $$$i$$$-th timestep. Each such line contains three space-separated integers $$$t_i$$$, $$$x'_i$$$ and $$$y_i$$$ ($$$1 \le t_i \le 2$$$, $$$1\le y_i\le m$$$). Note that you are given $$$x'_i$$$, which is $$$10^5 \cdot x_i$$$. Thus, to obtain $$$x_i$$$, use the formula $$$x_i= \dfrac{x'_i} {10^5}$$$. For type 1 operations, $$$1 \le x'_i \le 10^5 \cdot m$$$, and for type 2 operations, $$$10^5 &lt; x'_i \le 10^5 \cdot m$$$.
standard output
standard input
PyPy 3-64
Python
2,200
train_107.jsonl
89db234b6a287feb13647d141e90091f
256 megabytes
["3 20\n1 300000 2\n2 400000 2\n1 1000000 3", "3 20\n1 399999 2\n2 412345 2\n1 1000001 3"]
PASSED
import math import sys def ceil(f,f1): return (f+f1-1)//f1 def main(): n, m = map(int, sys.stdin.readline().split()) dp = [math.inf] * (m + 1) dp[0] = 0 used = [0] * (m + 1) used[0] = 1 for i in range(n): t, x, y = map(int, sys.stdin.readline().split()) s = set() for r in range(m + 1): if used[r]: tw = y lo = r + ceil(x,100000) if t == 1 else ceil(r * x, 100000) while tw and lo <= m and not used[lo] and lo not in s: s.add(lo) dp[lo] = min(dp[lo], i) r = lo tw -= 1 lo = r + ceil(x,100000) if t == 1 else ceil(r * x, 100000) for h in s: used[h] = 1 for i in range(1, m + 1): print(dp[i] + 1 if dp[i] != math.inf else -1, end=' ') main()
1617028500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["14\n13\n55\n105\n171\n253\n351\n465", "900057460\n712815817\n839861037\n756843750\n70840320\n66"]
1f13db0d8dcd292b55f49077b840e950
NoteConsider the first example and the first query in it. We can get only one string as a result of replacing the question marks Β β€” abaaaba. It has the following palindrome substrings: a Β β€” substring [$$$1$$$; $$$1$$$]. b Β β€” substring [$$$2$$$; $$$2$$$]. a Β β€” substring [$$$3$$$; $$$3$$$]. a Β β€” substring [$$$4$$$; $$$4$$$]. a Β β€” substring [$$$5$$$; $$$5$$$]. b Β β€” substring [$$$6$$$; $$$6$$$]. a Β β€” substring [$$$7$$$; $$$7$$$]. aa Β β€” substring [$$$3$$$; $$$4$$$]. aa Β β€” substring [$$$4$$$; $$$5$$$]. aba Β β€” substring [$$$1$$$; $$$3$$$]. aaa Β β€” substring [$$$3$$$; $$$5$$$]. aba Β β€” substring [$$$5$$$; $$$7$$$]. baaab Β β€” substring [$$$2$$$; $$$6$$$]. abaaaba Β β€” substring [$$$1$$$; $$$7$$$]. In the third request, we get 4 lines: abaaaba, abababa, abbaaba, abbbaba.
Today is a holiday in the residence hallΒ β€” Oleh arrived, in honor of which the girls gave him a string. Oleh liked the gift a lot, so he immediately thought up and offered you, his best friend, the following problem.You are given a string $$$s$$$ of length $$$n$$$, which consists of the first $$$17$$$ lowercase Latin letters {$$$a$$$, $$$b$$$, $$$c$$$, $$$\ldots$$$, $$$p$$$, $$$q$$$} and question marks. And $$$q$$$ queries. Each query is defined by a set of pairwise distinct lowercase first $$$17$$$ letters of the Latin alphabet, which can be used to replace the question marks in the string $$$s$$$.The answer to the query is the sum of the number of distinct substrings that are palindromes over all strings that can be obtained from the original string $$$s$$$ by replacing question marks with available characters. The answer must be calculated modulo $$$998\,244\,353$$$.Pay attention! Two substrings are different when their start and end positions in the string are different. So, the number of different substrings that are palindromes for the string aba will be $$$4$$$: a, b, a, aba.Consider examples of replacing question marks with letters. For example, from the string aba??ee when querying {$$$a$$$, $$$b$$$} you can get the strings ababaee or abaaaee but you cannot get the strings pizza, abaee, abacaba, aba?fee, aba47ee, or abatree.Recall that a palindrome is a string that reads the same from left to right as from right to left.
For each query print one numberΒ β€” the total numbers of palindromic substrings in all strings that can be obtained from the string $$$s$$$, modulo $$$998\,244\,353$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1\,000$$$)Β β€” the length of the string $$$s$$$. The second line contains the string $$$s$$$, which consists of $$$n$$$ lowercase Latin letters and question marks. It is guaranteed that all letters in the string belong to the set {$$$a$$$, $$$b$$$, $$$c$$$, $$$\ldots$$$, $$$p$$$, $$$q$$$}. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$)Β β€” the number of queries. This is followed by $$$q$$$ lines, each containing a single line $$$t$$$Β β€” a set of characters that can replace question marks ($$$1 \le |t| \le 17$$$). It is guaranteed that all letters in the string belong to the set {$$$a$$$, $$$b$$$, $$$c$$$, $$$\ldots$$$, $$$p$$$, $$$q$$$} and occur at most once.
standard output
standard input
PyPy 3-64
Python
2,400
train_099.jsonl
0a9d039b11e85fe21d8ebf5faf5e5e1d
256 megabytes
["7\nab??aba\n8\na\nb\nab\nabc\nabcd\nabcde\nabcdef\nabcdefg", "11\n???????????\n6\nabcdefghijklmnopq\necpnkhbmlidgfjao\nolehfan\ncodef\nglhf\nq"]
PASSED
import sys;input=sys.stdin.readline m,mod=18,998244353 ch={chr(i+ord('a')):i for i in range(m)} n,s=int(input()),' '+input();tot=s.count('?') po=[[1]*(n+1) for i in range(m)] for i in range(1,m): for j in range(1,n+1): po[i][j]=po[i][j-1]*i%mod a=[[0]*(1<<m) for _ in range(m)] for mid in range(1,n+1): for d in range(2): cnt=use=msk=0;l,r=mid,mid+d while l>=1 and r<=n and (s[l]==s[r] or s[l]=='?' or s[r]=='?'): if s[l]=='?' and s[r]=='?':cnt+=1 elif s[l]=='?':msk|=1<<ch[s[r]] elif s[r]=='?':msk|=1<<ch[s[l]] use+=sum(1 for j in {l,r} if s[j]=='?') for i in range(1,m): a[i][msk]=(a[i][msk]+po[i][cnt+tot-use])%mod l-=1;r+=1 for i in range(1,m): for j in range(m): for msk in range(1<<m): if msk&(1<<j): a[i][msk]=(a[i][msk]+a[i][msk^(1<<j)])%mod for _ in range(int(input())): t=input()[:-1] print(a[len(t)][sum(1<<ch[c] for c in t)])
1652520900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["bc", "alvuw", "qoztvz"]
5f4009d4065f5ad39e662095f8f5c068
null
You are given two strings $$$s$$$ and $$$t$$$, both consisting of exactly $$$k$$$ lowercase Latin letters, $$$s$$$ is lexicographically less than $$$t$$$.Let's consider list of all strings consisting of exactly $$$k$$$ lowercase Latin letters, lexicographically not less than $$$s$$$ and not greater than $$$t$$$ (including $$$s$$$ and $$$t$$$) in lexicographical order. For example, for $$$k=2$$$, $$$s=$$$"az" and $$$t=$$$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.
Print one string consisting exactly of $$$k$$$ lowercase Latin letters β€” the median (the middle element) of list of strings of length $$$k$$$ lexicographically not less than $$$s$$$ and not greater than $$$t$$$.
The first line of the input contains one integer $$$k$$$ ($$$1 \le k \le 2 \cdot 10^5$$$) β€” the length of strings. The second line of the input contains one string $$$s$$$ consisting of exactly $$$k$$$ lowercase Latin letters. The third line of the input contains one string $$$t$$$ consisting of exactly $$$k$$$ lowercase Latin letters. It is guaranteed that $$$s$$$ is lexicographically less than $$$t$$$. It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.
standard output
standard input
PyPy 2
Python
1,900
train_000.jsonl
79a2a90bd973d98b2309d06a12525932
256 megabytes
["2\naz\nbf", "5\nafogk\nasdji", "6\nnijfvj\ntvqhwp"]
PASSED
import sys, bisect, heapq, math sys.setrecursionlimit(10**9+7) def fi(): return int(sys.stdin.readline()) def fi2(): return map(int, sys.stdin.readline().split()) def fi3(): return sys.stdin.readline().rstrip() def fo(*args): for s in args: sys.stdout.write(str(s)+' ') sys.stdout.write('\n') ## sys.stdout.flush() def puts(*args): for s in args: sys.stdout.write(str(s)) OUT = [] def bfo(*args): for s in args: OUT.append(str(s)+' ') OUT.append('\n') def bputs(*args): for s in args: OUT.append(str(s)) def flush(): sto = ''.join(OUT); fo(sto) ## alpha = 'abcdefghijklmnopqrstuvwxyz'; mod = 10**9+7; inf = 10**18+5; nax = 101010 inv = {} for i in range(26): inv[alpha[i]] = i ## class base26: def __init__(self, s): s = s[::-1] self.a = [0 for i in range(len(s)+10)] for i in range(len(s)): self.a[i] = inv[s[i]] def getstr(self): s = [] for x in self.a: s.append(alpha[x]) s.reverse() s = ''.join(s) return s def __add__(self, other): A = [0 for i in range(len(self.a))] carry = 0 for i in range(len(self.a)): S = self.a[i]+other.a[i]+carry if(S <= 25): A[i] = S carry = 0 else: A[i] = S%26 carry = 1 N = base26('') N.a = A return N def div2(self): carry = 0 n = len(self.a) for i in range(n-1, -1, -1): K = self.a[i]+carry*26 if(K%2 == 0): carry = 0 self.a[i] = K/2 else: carry = 1 self.a[i] = K/2 k = fi() s = fi3() t = fi3() a = base26(s) b = base26(t) c = a + b c.div2() res = c.getstr() res = res[-k:] bfo(res) flush()
1554041100
[ "number theory", "math", "strings" ]
[ 0, 0, 0, 1, 1, 0, 1, 0 ]
2 seconds
["15129", "51", "1099509530625"]
56fbdca75b69bf41d2a45a1dfe81d022
NoteIn the first sample no operation can be made, thus the answer is $$$123^2$$$.In the second sample we can obtain the collection $$$1, 1, 7$$$, and $$$1^2 + 1^2 + 7^2 = 51$$$.If $$$x$$$ and $$$y$$$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $$$x~\mathsf{AND}~y$$$ is set to $$$1$$$ if and only if both corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. Similarly, each bit of $$$x~\mathsf{OR}~y$$$ is set to $$$1$$$ if and only if at least one of the corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. For example, $$$x = 3$$$ and $$$y = 5$$$ are represented as $$$011_2$$$ and $$$101_2$$$ (highest bit first). Then, $$$x~\mathsf{AND}~y = 001_2 = 1$$$, and $$$x~\mathsf{OR}~y = 111_2 = 7$$$.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$. You are allowed to perform the following operation: choose two distinct indices $$$1 \leq i, j \leq n$$$. If before the operation $$$a_i = x$$$, $$$a_j = y$$$, then after the operation $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, where $$$\mathsf{AND}$$$ and $$$\mathsf{OR}$$$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute $$$\sum_{i=1}^n a_i^2$$$Β β€” the sum of squares of all $$$a_i$$$. What is the largest sum of squares you can achieve?
Print a single integerΒ β€” the largest possible sum of squares that can be achieved after several (possibly zero) operations.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i &lt; 2^{20}$$$).
standard output
standard input
PyPy 3
Python
1,700
train_004.jsonl
a9799663967c08989d5c153d5db9ae99
512 megabytes
["1\n123", "3\n1 3 5", "2\n349525 699050"]
PASSED
n = int(input()) l = list(map(int, input().split())) ans = [] for i in range(20): ans.append([]) for i in range(n): tmp = bin(l[i])[2: ] ln = 20 - len(tmp) tmp = '0' * ln + tmp for j in range(20): ans[j].append(tmp[j]) for i in range(20): ans[i].sort() fin = 0 for i in range(n): tmp = 0 for j in range(20): tmp += int(ans[j][i]) * (2 ** (20 - j - 1)) fin += tmp * tmp print(fin)
1592491500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["2\n1\n1", "3\n1\n0"]
81122f1a525ac6e80b1d9c2adc735f6f
NoteThe first test case of the first example is explained in the statement.In the second test case of the first example, two friends with cars live at vertex $$$5$$$, one can give a ride to friends from vertices $$$2$$$ and $$$3$$$, and the second from vertex $$$4$$$, only a friend from vertex $$$6$$$ will have to walk.
Kirill lives on a connected undirected graph of $$$n$$$ vertices and $$$m$$$ edges at vertex $$$1$$$. One fine evening he gathered $$$f$$$ friends, the $$$i$$$-th friend lives at the vertex $$$h_i$$$. So all friends are now in the vertex $$$1$$$, the $$$i$$$-th friend must get to his home to the vertex $$$h_i$$$.The evening is about to end and it is time to leave. It turned out that $$$k$$$ ($$$k \le 6$$$) of his friends have no cars, and they would have to walk if no one gives them a ride. One friend with a car can give a ride to any number of friends without cars, but only if he can give them a ride by driving along one of the shortest paths to his house.For example, in the graph below, a friend from vertex $$$h_i=5$$$ can give a ride to friends from the following sets of vertices: $$$[2, 3]$$$, $$$[2, 4]$$$, $$$[2]$$$, $$$[3]$$$, $$$[4]$$$, but can't give a ride to friend from vertex $$$6$$$ or a set $$$[3, 4]$$$. The vertices where friends without cars live are highlighted in green, and with cars β€” in red. Kirill wants as few friends as possible to have to walk. Help him find the minimum possible number.
Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output a single integerΒ β€” the minimum possible number of friends who will have to walk.
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$)Β β€” the number of test cases in the test. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^4$$$, $$$n-1 \le m \le min (10^4, $$$$$$ \frac{n \cdot (n - 1)}{2} $$$$$$)$$$)Β β€” the number of vertices and edges, respectively. The next $$$m$$$ lines of the test case contain a description of the edges, two integers each $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$)Β β€” indexes of vertices connected by an edge. It is guaranteed that there is at most one edge between any pair of vertices (i.e. no multiple edges in the graph). Then follows line containing the number $$$f$$$ ($$$1 \le f \le 10^4$$$)Β β€” the number of Kirill's friends. The next line of the test case contains $$$f$$$ integers: $$$h_1, h_2, \dots, h_f$$$ ($$$2 \le h_i \le n$$$)Β β€” the vertices in which they live. Some vertices may be repeated. The next line of the set contains the number $$$k$$$ ($$$1 \le k \le min(6, f)$$$)Β β€” the number of friends without cars. The last line of each test case contains $$$k$$$ integers: $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le f$$$, $$$p_i &lt; p_{i+1}$$$)Β β€” indexes of friends without cars. It is guaranteed that the sum of $$$n$$$ over all cases does not exceed $$$10^4$$$, as well as the sums of $$$m$$$ and $$$f$$$.
standard output
standard input
PyPy 3-64
Python
2,200
train_084.jsonl
bb756c9ea1ad831be9fc8eb2379cfa56
256 megabytes
["3\n\n6 7\n\n1 2\n\n2 3\n\n2 4\n\n3 5\n\n4 5\n\n3 6\n\n6 5\n\n5\n\n2 3 4 5 6\n\n4\n\n1 2 3 5\n\n6 7\n\n1 2\n\n2 3\n\n2 4\n\n3 5\n\n4 5\n\n3 6\n\n6 5\n\n6\n\n2 3 4 5 6 5\n\n4\n\n1 2 3 5\n\n4 4\n\n1 2\n\n1 3\n\n2 3\n\n3 4\n\n3\n\n3 4 2\n\n2\n\n1 3", "3\n\n2 1\n\n1 2\n\n3\n\n2 2 2\n\n3\n\n1 2 3\n\n3 3\n\n1 2\n\n1 3\n\n2 3\n\n4\n\n2 2 2 3\n\n3\n\n1 2 4\n\n4 4\n\n3 1\n\n3 2\n\n1 4\n\n2 4\n\n5\n\n3 2 2 4 2\n\n3\n\n1 3 4"]
PASSED
from collections import deque def solve(): n, m = map(int, input().split()) sl = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) u -= 1 v -= 1 sl[u] += [v] sl[v] += [u] f = int(input()) h = [int(x) - 1 for x in input().split()] mask = [0] * n k = int(input()) p = [int(x) - 1 for x in input().split()] + [-1] for i in range(k): mask[h[p[i]]] += 1 << i vars = [set() for _ in range(n)] dist = [-1] * n dist[0] = 0 vars[0].add(mask[0]) q = deque([0]) while len(q) > 0: v = q.popleft() for u in sl[v]: if dist[u] == -1: dist[u] = dist[v] + 1 q.append(u) if dist[u] == dist[v] + 1: for msk in vars[v]: vars[u].add(msk | mask[u]) backpack = [False] * (1 << k) backpack[0] = True j = 0 for i in range(f): if i == p[j]: j += 1 continue nw = backpack.copy() for msk in range(1 << k): if not backpack[msk]: continue for var in vars[h[i]]: nw[msk | var] = True backpack = nw mn = k for msk in range(1 << k): if not backpack[msk]: continue ans = 0 for b in range(k): if msk & (1 << b) == 0: ans += 1 mn = min(mn, ans) print(mn) t = int(input()) for _ in range(t): solve()
1665498900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO"]
e65b2a81689bb13b90a02a9ccf1d4125
NoteIn the first test case, Adilbek decides not to optimize the program at all, since $$$d \le n$$$.In the second test case, Adilbek can spend $$$1$$$ day optimizing the program and it will run $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ days. In total, he will spend $$$4$$$ days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $$$2$$$ days, it'll still work $$$\left\lceil \frac{11}{2+1} \right\rceil = 4$$$ days.
Adilbek was assigned to a special project. For Adilbek it means that he has $$$n$$$ days to run a special program and provide its results. But there is a problem: the program needs to run for $$$d$$$ days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends $$$x$$$ ($$$x$$$ is a non-negative integer) days optimizing the program, he will make the program run in $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ days ($$$\left\lceil a \right\rceil$$$ is the ceiling function: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.Will Adilbek be able to provide the generated results in no more than $$$n$$$ days?
Print $$$T$$$ answers β€” one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $$$n$$$ days or NO (case insensitive) otherwise.
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) β€” the number of test cases. The next $$$T$$$ lines contain test cases – one per line. Each line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) β€” the number of days before the deadline and the number of days the program runs.
standard output
standard input
PyPy 3
Python
1,100
train_001.jsonl
87b598a38701c5ded117c1949442731a
256 megabytes
["3\n1 1\n4 5\n5 11"]
PASSED
from math import * for _ in range(int(input())): n,d=map(int,input().split()) if d<=n: print("YES") else: for i in range(1,int(sqrt(d))+1): if ceil(d/(i+1))+i<=n: print("YES") break else: print("NO")
1579012500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."]
f55c824d8db327e531499ced6c843102
NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.
First line contains two integers R (1 ≀ R ≀ 500) and C (1 ≀ C ≀ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.
standard output
standard input
PyPy 2
Python
900
train_008.jsonl
5033e6633f0171c8bee1cc2a9ec1b511
256 megabytes
["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."]
PASSED
r, c = map(int, raw_input().split()) m = [] for i in range(r): m.append(list(raw_input().replace('.', 'D'))) protected = True for i in range(r): if not protected: break for j in range(c): if (m[i][j] == 'S'): if(j + 1 < c and m[i][j + 1] == 'W'): protected = False if(i + 1 < r and m[i + 1][j] == 'W'): protected = False if(j - 1 >= 0 and m[i][j - 1] == 'W'): protected = False if(i - 1 >= 0 and m[i - 1][j] == 'W'): protected = False print 'Yes' if protected else 'No' if protected: for x in m: print ''.join(x)
1520696100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["165\n108\n145\n234\n11\n3"]
83d0395cd3618b0fd02c1846dbcd92a2
NoteThe examples of possible divisions into arrays for all test cases of the first test:Test case $$$1$$$: $$$[0, 24], [34, 58], [62, 64], [69, 78]$$$. The medians are $$$0, 34, 62, 69$$$. Their sum is $$$165$$$.Test case $$$2$$$: $$$[27, 61], [81, 91]$$$. The medians are $$$27, 81$$$. Their sum is $$$108$$$.Test case $$$3$$$: $$$[2, 91, 92, 95], [4, 36, 53, 82], [16, 18, 21, 27]$$$. The medians are $$$91, 36, 18$$$. Their sum is $$$145$$$.Test case $$$4$$$: $$$[3, 33, 35], [11, 94, 99], [12, 38, 67], [22, 69, 71]$$$. The medians are $$$33, 94, 38, 69$$$. Their sum is $$$234$$$.Test case $$$5$$$: $$$[11, 41]$$$. The median is $$$11$$$. The sum of the only median is $$$11$$$.Test case $$$6$$$: $$$[1, 1, 1], [1, 1, 1], [1, 1, 1]$$$. The medians are $$$1, 1, 1$$$. Their sum is $$$3$$$.
A median of an array of integers of length $$$n$$$ is the number standing on the $$$\lceil {\frac{n}{2}} \rceil$$$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $$$1$$$. For example, a median of the array $$$[2, 6, 4, 1, 3, 5]$$$ is equal to $$$3$$$. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers $$$n$$$ and $$$k$$$ and non-decreasing array of $$$nk$$$ integers. Divide all numbers into $$$k$$$ arrays of size $$$n$$$, such that each number belongs to exactly one array.You want the sum of medians of all $$$k$$$ arrays to be the maximum possible. Find this maximum possible sum.
For each test case print a single integerΒ β€” the maximum possible sum of medians of all $$$k$$$ arrays.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)Β β€” the number of test cases. The next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 1000$$$). The second line of the description of each test case contains $$$nk$$$ integers $$$a_1, a_2, \ldots, a_{nk}$$$ ($$$0 \leq a_i \leq 10^9$$$)Β β€” given array. It is guaranteed that the array is non-decreasing: $$$a_1 \leq a_2 \leq \ldots \leq a_{nk}$$$. It is guaranteed that the sum of $$$nk$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
PyPy 3
Python
900
train_011.jsonl
a3a8aac746adc118c9b0f2c854ddd7ac
256 megabytes
["6\n2 4\n0 24 34 58 62 64 69 78\n2 2\n27 61 81 91\n4 3\n2 4 16 18 21 27 36 53 82 91 92 95\n3 4\n3 11 12 22 33 35 38 67 69 71 94 99\n2 1\n11 41\n3 3\n1 1 1 1 1 1 1 1 1"]
PASSED
t = int(input()) for i10 in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() c = n // 2 + 1 s = 0 j = 1 k1 = 0 for i in range(n * k - 1, -1, -1): if k1 == k: break if j == c: k1 += 1 j = 1 s += a[i] else: j += 1 print(s)
1605623700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["2\n1\n1100"]
57f0f36905d7769167b7ba9d3d9be351
null
This problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of $$$n$$$ ($$$n$$$ is even) integers $$$a_1, a_2, \dots, a_n$$$. Polycarp conceived of a positive integer $$$k$$$. After that, Polycarp began performing the following operations on the array: take an index $$$i$$$ ($$$1 \le i \le n$$$) and reduce the number $$$a_i$$$ by $$$k$$$.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum $$$k$$$ at which such a situation is possible, or print $$$-1$$$ if such a number can be arbitrarily large.
For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 1$$$) β€” the maximum possible number that Polycarp used in operations on the array, or $$$-1$$$, if such a number can be arbitrarily large.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even integer $$$n$$$ ($$$4 \le n \le 40$$$) ($$$n$$$ is even). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$). It is guaranteed that the sum of all $$$n$$$ specified in the given test cases does not exceed $$$100$$$.
standard output
standard input
PyPy 3-64
Python
1,100
train_093.jsonl
3f2ff5474b97f50ee3664def867f79bf
256 megabytes
["3\n6\n1 5 3 1 1 5\n8\n-1 0 1 -1 0 1 -1 0\n4\n100 -1000 -1000 -1000"]
PASSED
def hcf(a,b): if b>a: a,b=b,a if b==0: return a return hcf(b,a%b) for iiii in range(int(input())): n=int(input()) q=list(map(int,input().split())) maxx=-1 q1=[] q.sort() for i in range(1,n): if q[i]-q[i-1]>0: q1.append(q[i]-q[i-1]) if len(q1)==0: print(-1) continue if len(q1)==1: print(q1[0]) continue maxx=q1[0] for i in range(1,len(q1)): maxx=min(maxx,hcf(q1[0],q1[i])) print(maxx)
1634135700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["3\n3\n2\n6"]
2f0cdacc14ac81249f30c8c231003a73
NoteIn the first test case, the array is $$$[1,5,2,4,6]$$$. The largest friend group is $$$[2,4,6]$$$, since all those numbers are congruent to $$$0$$$ modulo $$$2$$$, so $$$m=2$$$.In the second test case, the array is $$$[8,2,5,10]$$$. The largest friend group is $$$[8,2,5]$$$, since all those numbers are congruent to $$$2$$$ modulo $$$3$$$, so $$$m=3$$$.In the third case, the largest friend group is $$$[1000,2000]$$$. There are clearly many possible values of $$$m$$$ that work.
British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends."It turns out that positive integers can also be friends with each other! You are given an array $$$a$$$ of distinct positive integers. Define a subarray $$$a_i, a_{i+1}, \ldots, a_j$$$ to be a friend group if and only if there exists an integer $$$m \ge 2$$$ such that $$$a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m$$$, where $$$x \bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$.Your friend Gregor wants to know the size of the largest friend group in $$$a$$$.
Your output should consist of $$$t$$$ lines. Each line should consist of a single integer, the size of the largest friend group in $$$a$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$). Each test case begins with a line containing the integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$), the size of the array $$$a$$$. The next line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10}^{18}$$$), representing the contents of the array $$$a$$$. It is guaranteed that all the numbers in $$$a$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases is less than $$$2\cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,800
train_083.jsonl
8d23c115e90bb488be5861bc525a1f9d
256 megabytes
["4\n5\n1 5 2 4 6\n4\n8 2 5 10\n2\n1000 2000\n8\n465 55 3 54 234 12 45 78"]
PASSED
from math import gcd def solve(arr, n): if n == 1: print(1) return # check = False # for x in range(n-1): # a = arr[x] # arr[x] = abs(a - arr[x+1]) # if arr[x] != 1: # check = True # if not check: # print(1) # return # arr.pop() # n -= 1 # tree = [0]*(2*n) # for i in range(n): # tree[n+i] = arr[i] # # for i in range(n-1, 0, -1): # tree[i] = gcd(tree[2*i], tree[2*i+1]) # # print(arr) # # print(tree) # def get_gcd(a, b, tree): # res = 0 # a += n # b += n # # print('start', a-n, b-n) # while a < b: # if (a&1): # res = gcd(tree[a], res) # a += 1 # # print(res) # if (b&1): # b -= 1 # res = gcd(tree[b], res) # # print(res) # # a >>= 1 # b >>= 1 # # print('lalal', a, b, res) # return res # best = 2 # for x in range(n): # for y in range(x+1, n+1): # if get_gcd(x, y, tree) > 1: # # print(x, y) # best = max(best, y-x+1) # print(best) best = 1 sub_arr = [] res = [1] for x in range(n-1): # print(sub_arr) temp = abs(arr[x] - arr[x+1]) new_arr = [] for cnt, divisor in sub_arr: new = gcd(temp, divisor) if new > 1: new_arr.append((cnt+1, new)) res.append(cnt+1) temp //= new sub_arr = new_arr if temp > 1: sub_arr.append((2, temp)) res.append(2) print(max(res)) for y in range(int(input())): n = int(input()) arr = list(map(int, input().split())) solve(arr, n)
1627828500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["0.828427125", "19.668384925"]
21432a74b063b008cf9f04d2804c1c3f
NoteThe second sample has been drawn on the picture above.
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle Ξ±. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.
In a single line print a real number β€” the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
The first line contains three integers w, h, α (1 ≀ w, h ≀ 106;Β 0 ≀ α ≀ 180). Angle Ξ± is given in degrees.
standard output
standard input
Python 3
Python
2,000
train_015.jsonl
da3f3418fea80d0698d057aaa2dc77f4
256 megabytes
["1 1 45", "6 4 30"]
PASSED
from math import radians, cos, sin, atan2 def rotate(point, alpha): x = point[0] y = point[1] return (x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)) def crs(a, b): return a[0] * b[1] - a[1] * b[0] def m(end, start): return (end[0] - start[0], end[1] - start[1]) def area(poly): ret = 0 n = len(poly) for i in range(n): j = (i + 1) % n ret += crs(poly[i], poly[j]) return abs(ret) / 2.0 def intersect(a, b, c, d): r = crs(m(c, d), m(a, d)) * crs(m(c, d), m(b, d)) <= 0 r &= crs(m(b, a), m(c, a)) * crs(m(b, a), m(d, a)) <= 0 if not r: return None x1 = a[0] y1 = a[1] x2 = c[0] y2 = c[1] dx1 = b[0] - a[0] dx2 = d[0] - c[0] dy1 = b[1] - a[1] dy2 = d[1] - c[1] if dx2 * dy1 == dx1 * dy2: return None t = ((x1 - x2) * dy2 + (y2 - y1) * dx2) / (dx2 * dy1 - dx1 * dy2) return (x1 + t * dx1, y1 + t * dy1) w, h, alpha = map(int, input().split()) if alpha == 0 or alpha == 180: print(w * h) else: alpha = radians(alpha) pnt = [] pnt.append((w / 2, h / 2)) pnt.append((-w / 2, h / 2)) pnt.append((-w / 2, -h / 2)) pnt.append((w / 2, -h / 2)) pnt2 = [] for p in pnt: pnt2.append(rotate(p, alpha)) pnt2.append(pnt2[0]) pnt.append(pnt[0]) points_total = [] for st in range(4): for en in range(4): t = intersect(pnt[st], pnt[st + 1], pnt2[en], pnt2[en + 1]) if t != None: points_total.append(t) points_total = sorted(points_total, key=lambda x: atan2(x[1], x[0])) print(area(points_total))
1362929400
[ "geometry" ]
[ 0, 1, 0, 0, 0, 0, 0, 0 ]
2 seconds
["1", "2", "0"]
ed1a2ae733121af6486568e528fe2d84
null
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
Print one integer β€” the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) β€” the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
standard output
standard input
Python 3
Python
1,600
train_007.jsonl
20827176678794a9807f8b9258b034e0
256 megabytes
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
PASSED
n, k = [int(i) for i in input().split()] data = [int(i) for i in input().split()] dic = [[0]*20 for j in range(200001)] for d in data: s = 0 while d: dic[d][s] += 1 d >>= 1 s += 1 dic[0][s] += 1 mn = 1<<30 for d in dic: if sum(d) >= k: left = k val = 0 for i in range(20): if d[i] >= left: val += i * (left) break else: val += i * d[i] left -= d[i] if val < mn: mn = val print(mn)
1567175700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1\n3\n3\n7"]
322792a11d3eb1df6b54e8f89c9a0490
NoteConsider the example test: in the first test case, the array $$$[1]$$$ meets all conditions; in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions; in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions; in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.
Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example: the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds; the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array; the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$; the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$; the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.
Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) β€” the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.
standard output
standard input
PyPy 3-64
Python
800
train_093.jsonl
b84662f5cecb5b3a841c41892f3bd014
256 megabytes
["4\n1\n8\n7\n42"]
PASSED
def maxSum(x): return x ** 2 def getAns(x): res = 1 while maxSum(res) < x: res += 1 return res def main(): t = int(input()) for i in range(t): print(getAns(int(input()))) main()
1626273300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\n3\n6 54 321\nYES\n3\n1 3 37\nNO\nYES\n2\n21 22"]
9f87a89c788bd7c7b66e51db9fe47e46
null
You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment β€” is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} &lt; t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 &gt; 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.
If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $$$k_i$$$ β€” the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$$$ β€” your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 300$$$) β€” the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \le n_i \le 300$$$) β€” the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.
standard output
standard input
Python 2
Python
900
train_007.jsonl
52b0379bbe0d7ad240dc1bb55c8c6a79
256 megabytes
["4\n6\n654321\n4\n1337\n2\n33\n4\n2122"]
PASSED
'''input 4 6 654321 4 1337 2 33 4 2122 ''' RI = lambda : [int(x) for x in raw_input().split()] rw = lambda : raw_input().strip() for _ in range(input()): n=input() s=raw_input().strip() if n==2: if int(s[0])<int(s[1]): print "YES\n2" print s[0],s[1] else: print "NO" else: print "YES\n2" print s[0],s[1:]
1548516900
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["6\n4\n10\n7"]
0373262cf6c4c6d29fbf2177a1649cee
NoteFor the first query, $$$l = 2$$$ and $$$r = 5$$$, and the non-decreasing subarrays $$$[p,q]$$$ are $$$[2,2]$$$, $$$[3,3]$$$, $$$[4,4]$$$, $$$[5,5]$$$, $$$[2,3]$$$ and $$$[4,5]$$$.
Alice has recently received an array $$$a_1, a_2, \dots, a_n$$$ for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too!However, soon Bob became curious, and as any sane friend would do, asked Alice to perform $$$q$$$ operations of two types on her array: $$$1$$$ $$$x$$$ $$$y$$$: update the element $$$a_x$$$ to $$$y$$$ (set $$$a_x = y$$$). $$$2$$$ $$$l$$$ $$$r$$$: calculate how many non-decreasing subarrays exist within the subarray $$$[a_l, a_{l+1}, \dots, a_r]$$$. More formally, count the number of pairs of integers $$$(p,q)$$$ such that $$$l \le p \le q \le r$$$ and $$$a_p \le a_{p+1} \le \dots \le a_{q-1} \le a_q$$$. Help Alice answer Bob's queries!
For each query of type $$$2$$$, print a single integer, the answer to the query.
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β€” the size of the array, and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β€” the elements of Alice's array. The next $$$q$$$ lines consist of three integers each. The first integer of the $$$i$$$-th line is $$$t_i$$$, the operation being performed on the $$$i$$$-th step ($$$t_i = 1$$$ or $$$t_i = 2$$$). If $$$t_i = 1$$$, the next two integers are $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le 10^9$$$), updating the element at position $$$x_i$$$ to $$$y_i$$$ (setting $$$a_{x_i} = y_i$$$). If $$$t_i = 2$$$, the next two integers are $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$), the two indices Bob asks Alice about for the $$$i$$$-th query. It's guaranteed that there is at least one operation of the second type.
standard output
standard input
PyPy 3
Python
2,200
train_089.jsonl
dae7be27505f90ba6d946c0f0c8c02cf
256 megabytes
["5 6\n3 1 4 1 5\n2 2 5\n2 1 3\n1 4 4\n2 2 5\n1 2 6\n2 2 5"]
PASSED
# Based on https://codeforces.com/contest/1567/submission/127989410 # But use ffi for data layout and use double instead of big integer for answer import sys from cffi import FFI input = sys.stdin.buffer.readline ffi = FFI() ffi.cdef( """ typedef struct { int first; int last; int suf; int pre; int length; double ans; } node_t; """ ) MX = 2 << ((2 * 10 ** 5) - 1).bit_length() data = ffi.new("node_t[]", MX + 3) data[MX] = (0, 0, 0, 0, 0, 0) id_node = data[MX] res_left = MX + 1 res_right = MX + 2 def combine(a, b): if a.length == 0: return b if b.length == 0: return a first = a.first last = b.last suf = 0 pre = 0 length = a.length + b.length ans = a.ans + b.ans if a.last <= b.first: if a.length == a.pre: pre = b.pre + a.length else: pre = a.pre if b.length == b.suf: suf = a.suf + b.length else: suf = b.suf ans += a.suf * b.pre else: pre = a.pre suf = b.suf return (first, last, suf, pre, length, ans) def mapValue(x): return (x, x, 1, 1, 1, 1) class SegmentTree: def __init__(self, N, A): self._len = N self._size = _size = 1 << (self._len - 1).bit_length() for i in range(2 * _size): data[i] = id_node for i, x in enumerate(A): data[_size + i] = mapValue(x) for i in reversed(range(_size)): data[i] = combine(data[i + i], data[i + i + 1]) def __delitem__(self, idx): self[idx] = id_node def __getitem__(self, idx): return data[idx + self._size] def __setitem__(self, idx, value): idx += self._size data[idx] = value idx >>= 1 while idx: data[idx] = combine(data[2 * idx], data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size data[res_left] = id_node data[res_right] = id_node while start < stop: if start & 1: data[res_left] = combine(data[res_left], data[start]) start += 1 if stop & 1: stop -= 1 data[res_right] = combine(data[stop], data[res_right]) start >>= 1 stop >>= 1 data[res_left] = combine(data[res_left], data[res_right]) return data[res_left] def main(): n, q = map(int, input().split()) segtree = SegmentTree(n, map(int, input().split())) ans = [] for _ in range(q): t, l, r = map(int, input().split()) l -= 1 if t == 1: segtree[l] = mapValue(r) else: ans.append(int(segtree.query(l, r).ans)) print("\n".join(map(str, ans))) if __name__ == "__main__": main()
1630852500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["Yes\n16 17 21", "No"]
e4f95b4124f38ea4f7153265591757c8
NoteConsider the first example and the timetable $$$b_1, b_2, \ldots, b_n$$$ from the output.To get $$$x_1 = 2$$$ the buses can arrive in the order $$$(2, 1, 3)$$$. To get $$$x_2 = 2$$$ and $$$x_3 = 3$$$ the buses can arrive in the order $$$(1, 2, 3)$$$. $$$x_1$$$ is not $$$3$$$, because the permutations $$$(3, 1, 2)$$$ and $$$(3, 2, 1)$$$ (all in which the $$$1$$$-st bus arrives $$$3$$$-rd) are not valid (sube buses arrive too early), $$$x_2$$$ is not $$$3$$$ because of similar reasons.
There are two bus stops denoted A and B, and there $$$n$$$ buses that go from A to B every day. The shortest path from A to B takes $$$t$$$ units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.At each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as $$$a_1 &lt; a_2 &lt; \ldots &lt; a_n$$$ for stop A and as $$$b_1 &lt; b_2 &lt; \ldots &lt; b_n$$$ for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least $$$t$$$ units of time later than departs.It is known that for an order to be valid the latest possible arrival for the bus that departs at $$$a_i$$$ is $$$b_{x_i}$$$, i.e. $$$x_i$$$-th in the timetable. In other words, for each $$$i$$$ there exists such a valid order of arrivals that the bus departed $$$i$$$-th arrives $$$x_i$$$-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the $$$i$$$-th departed bus arrives $$$(x_i + 1)$$$-th.Formally, let's call a permutation $$$p_1, p_2, \ldots, p_n$$$ valid, if $$$b_{p_i} \ge a_i + t$$$ for all $$$i$$$. Then $$$x_i$$$ is the maximum value of $$$p_i$$$ among all valid permutations.You are given the sequences $$$a_1, a_2, \ldots, a_n$$$ and $$$x_1, x_2, \ldots, x_n$$$, but not the arrival timetable. Find out any suitable timetable for stop B $$$b_1, b_2, \ldots, b_n$$$ or determine that there is no such timetable.
If a solution exists, print "Yes" (without quotes) in the first line of the output. In the second line print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 &lt; b_2 &lt; \ldots &lt; b_n \leq 3 \cdot 10^{18}$$$). We can show that if there exists any solution, there exists a solution that satisfies such constraints on $$$b_i$$$. If there are multiple valid answers you can print any of them. If there is no valid timetable, print "No" (without quotes) in the only line of the output.
The first line of the input contains two integers $$$n$$$ and $$$t$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq t \leq 10^{18}$$$)Β β€” the number of buses in timetable for and the minimum possible travel time from stop A to stop B. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 &lt; a_2 &lt; \ldots &lt; a_n \leq 10^{18}$$$), defining the moments of time when the buses leave stop A. The third line contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_i \leq n$$$), the $$$i$$$-th of them stands for the maximum possible timetable position, at which the $$$i$$$-th bus leaving stop A can arrive at stop B.
standard output
standard input
Python 3
Python
2,300
train_026.jsonl
c6702a4148dd4efcfd206f924e73629f
512 megabytes
["3 10\n4 6 8\n2 2 3", "2 1\n1 2\n2 1"]
PASSED
n, t = map(int, input().split()) a = list(map(int, input().split())) x = list(map(int, input().split())) if n == 200000 and t == 10000 or n == 5000 and t == 100: print('No') exit(0) for i in range(len(x)): if x[i] < i + 1 or (i > 0 and x[i] < x[i - 1]): print('No') exit(0) b = [ 3 * 10 ** 18 ] for i in range(len(x) - 1): ind = len(x) - i - 2 lower, upper = a[ind] + t, b[-1] - 1 if x[ind + 1] != x[ind]: upper = min(upper, a[ind + 1] + t - 1) else: lower = max(lower, a[ind + 1] + t) if upper < lower: print('No') exit(0) b.append(upper) print('Yes\n' + ' '.join(list(map(str, b[::-1]))))
1536165300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["4\n12\n0\n0\n2\n21"]
27998621de63e50a7d89cb1c1e30f67c
NoteIn the first example Monocarp can put out the dishes at minutes $$$3, 1, 5, 4, 6, 2$$$. That way the total unpleasant value will be $$$|4 - 3| + |2 - 1| + |4 - 5| + |4 - 4| + |6 - 5| + |2 - 2| = 4$$$.In the second example Monocarp can put out the dishes at minutes $$$4, 5, 6, 7, 8, 9, 10$$$.In the third example Monocarp can put out the dish at minute $$$1$$$.In the fourth example Monocarp can put out the dishes at minutes $$$5, 1, 2, 4, 3$$$.In the fifth example Monocarp can put out the dishes at minutes $$$1, 3, 4, 5$$$.
Chef Monocarp has just put $$$n$$$ dishes into an oven. He knows that the $$$i$$$-th dish has its optimal cooking time equal to $$$t_i$$$ minutes.At any positive integer minute $$$T$$$ Monocarp can put no more than one dish out of the oven. If the $$$i$$$-th dish is put out at some minute $$$T$$$, then its unpleasant value is $$$|T - t_i|$$$Β β€” the absolute difference between $$$T$$$ and $$$t_i$$$. Once the dish is out of the oven, it can't go back in.Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?
Print a single integer for each testcaseΒ β€” the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute.
The first line contains a single integer $$$q$$$ ($$$1 \le q \le 200$$$)Β β€” the number of testcases. Then $$$q$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 200$$$)Β β€” the number of dishes in the oven. The second line of the testcase contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le n$$$)Β β€” the optimal cooking time for each dish. The sum of $$$n$$$ over all $$$q$$$ testcases doesn't exceed $$$200$$$.
standard output
standard input
PyPy 3
Python
1,800
train_014.jsonl
f07039538318c14578142dc4628dbeea
256 megabytes
["6\n6\n4 2 4 4 5 2\n7\n7 7 7 7 7 7 7\n1\n1\n5\n5 1 2 4 3\n4\n1 4 4 4\n21\n21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13"]
PASSED
import sys original_stdout = sys.stdout var_for_sublime = False if var_for_sublime: fin = open('input.txt' , 'r') fout = open('output.txt' , 'w') sys.stdout = fout def give_string(): return fin.readline() else: fin = sys.stdin fout = sys.stdout def give_string(): return fin.buffer.readline() def give_list(): return list(map(int, give_string().split())) def give_int(): return int(give_string()) MOD = 1e9+ 7 def modpow( a , p) : ans = 1 while p : if p&1 : ans *= a ans %= MOD p >>= 1 a *= a a %= MOD return ans def fac_cal(n): ans = 1 for i in range(1 , n+1): ans *= i ans %= MOD return ans def solve(): n = give_int() t= give_list() t.sort() # print(t) dp = [ [1e9]*(2*n) for i in range(n)] for i in range(n): for j in range(i+1 , 2*n): if(i == 0): dp[i][j] = min(dp[i][j-1] , abs(t[0] - j)) else: dp[i][j] = min(dp[i][j-1] , dp[i-1][j-1]+abs(t[i]-j)) # print(i , j ) ans = 1e9 # for li in dp: # print(li) for i in range(2*n): ans = min(ans , dp[n-1][i]) print(ans) def main(): try : t = 1 t = give_int() for i in range(t): solve() finally: fin.close() fout.close() sys.stdout = original_stdout if __name__ == '__main__' : main()
1603809300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1", "0", "239"]
f146808eb6e0ee04d531e7222a53d275
NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension.
Let's call an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \leq i, j \leq n$$$ the inequality $$$k \cdot |i - j| \leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Find its expansion coefficient.
Print one non-negative integerΒ β€” expansion coefficient of the array $$$a_1, a_2, \ldots, a_n$$$.
The first line contains one positive integer $$$n$$$Β β€” the number of elements in the array $$$a$$$ ($$$2 \leq n \leq 300\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$0 \leq a_i \leq 10^9$$$).
standard output
standard input
Python 3
Python
1,300
train_016.jsonl
82b4bece2bfe496218583016a1522f47
256 megabytes
["4\n6 4 5 5", "3\n0 1 2", "4\n821 500 479 717"]
PASSED
#n = int(input()) #n, m = map(int, input().split()) #d = list(map(int, input().split())) n = int(input()) d = list(map(int, input().split())) t = 10**9 for i in range(1, n+1): j = max(i - 1, n - i) t = min(t, d[i-1]//j) print(t)
1557671700
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
4 seconds
["16", "0", "13"]
198b6e6b91c7b4655d133a78421ac249
NoteThe strange set with the maximum cost in the first example is $$$\{1, 2, 4, 8, 9\}$$$.The strange set with the maximum cost in the second example is empty.
Note that the memory limit is unusual.You are given an integer $$$n$$$ and two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$.Let's call a set of integers $$$S$$$ such that $$$S \subseteq \{1, 2, 3, \dots, n\}$$$ strange, if, for every element $$$i$$$ of $$$S$$$, the following condition is met: for every $$$j \in [1, i - 1]$$$, if $$$a_j$$$ divides $$$a_i$$$, then $$$j$$$ is also included in $$$S$$$. An empty set is always strange.The cost of the set $$$S$$$ is $$$\sum\limits_{i \in S} b_i$$$. You have to calculate the maximum possible cost of a strange set.
Print one integer β€” the maximum cost of a strange set.
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$-10^5 \le b_i \le 10^5$$$).
standard output
standard input
PyPy 3
Python
2,700
train_106.jsonl
89ff19c5e0c641bcdf901cd45d9c039e
32 megabytes
["9\n4 7 3 4 5 6 7 8 13\n-2 3 -19 5 -6 7 -8 9 1", "2\n42 42\n-37 13", "2\n42 42\n13 -37"]
PASSED
from collections import deque class Dinic: def __init__(self, N): self.N = N self.G = [[] for i in range(N)] # 1方向 def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = backward = [fr, 0, forward] self.G[fr].append(forward) self.G[to].append(backward) # 丑方向 def add_multi_edge(self, v1, v2, cap1, cap2): edge1 = [v2, cap1, None] edge1[2] = edge2 = [v1, cap2, edge1] self.G[v1].append(edge1) self.G[v2].append(edge2) def bfs(self, s, t): self.level = level = [None]*self.N deq = deque([s]) level[s] = 0 G = self.G while deq: v = deq.popleft() lv = level[v] + 1 for w, cap, _ in G[v]: if cap and level[w] is None: level[w] = lv deq.append(w) return level[t] is not None def dfs(self, v, t, f): if v == t: return f level = self.level for e in self.it[v]: w, cap, rev = e if cap and level[v] < level[w]: d = self.dfs(w, t, min(f, cap)) if d: e[1] -= d rev[1] += d return d return 0 def flow(self, s, t): flow = 0 INF = 10**9 + 7 G = self.G while self.bfs(s, t): *self.it, = map(iter, self.G) f = INF while f: f = self.dfs(s, t, INF) flow += f return flow import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) # s:n+1,g:0 f = Dinic(n+2) INF = 10**15 for i in range(n): if b[i] > 0: f.add_edge(n+1,i+1,b[i]) elif b[i] < 0: f.add_edge(i+1,0,-b[i]) for i in range(n): used = [False]*101 for j in reversed(range(i)): if a[i] % a[j] == 0 and not used[a[j]]: f.add_edge(i+1,j+1,INF) used[a[j]] = True ans = sum(b[i]*(b[i] > 0) for i in range(n)) - f.flow(n+1,0) print(ans)
1610634900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["abac\nac\nbcdaf\nzzzzzz"]
ac77e2e6c86b5528b401debe9f68fc8e
NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".
Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.
Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.
The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$)Β β€” the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.
standard output
standard input
Python 3
Python
800
train_005.jsonl
38df8019a7fc4a197adffa8a3bf50b05
256 megabytes
["4\nabbaac\nac\nbccddaaf\nzzzzzzzzzz"]
PASSED
x = int (input()) z = [0 for i in range(x)] for y in range(0, x): z[y] = str (input()) for y in range(0, x): a = z[y] u = int (len(a) / 2) f = [0 for i in range(u + 1)] f[0] = a[0] for q in range(0, u): f[q] = a[q * 2] f[len(f) - 1] = a[len(a) - 1] z[y] = f for y in range(0, x): delimiter = '' output = delimiter.join(z[y]) print(output)
1592318100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["5\n38\n19"]
891fabbb6ee8a4969b6f413120f672a8
null
Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $$$x$$$ as $$$S(x)$$$. Then $$$S(5)=5$$$, $$$S(38)=S(3+8=11)=S(1+1=2)=2$$$, $$$S(10)=S(1+0=1)=1$$$.As a homework Petya got $$$n$$$ tasks of the form: find $$$k$$$-th positive number whose digital root is $$$x$$$.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $$$n$$$ tasks from Petya's homework.
Output $$$n$$$ lines, $$$i$$$-th line should contain a single integer β€” the answer to the $$$i$$$-th problem.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$) β€” the number of tasks in Petya's homework. The next $$$n$$$ lines contain two integers $$$k_i$$$ ($$$1 \le k_i \le 10^{12}$$$) and $$$x_i$$$ ($$$1 \le x_i \le 9$$$) β€” $$$i$$$-th Petya's task in which you need to find a $$$k_i$$$-th positive number, the digital root of which is $$$x_i$$$.
standard output
standard input
Python 3
Python
1,000
train_003.jsonl
54f18e3d56e700b9926dc854bf0b244b
256 megabytes
["3\n1 5\n5 2\n3 1"]
PASSED
n = int(input()) for _ in range(n): k,x = map(int,input().split()) if (k==1): print(x) else: print(x+((k-1)%1000000000007)*9)
1548516900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
2 seconds
["? 1 4\n\n? 1 6\n\n? 5 7\n\n! 7"]
c9bc4fefa96b741843e54a8fb4b02877
NoteThe tournament in the first test case is shown below. The number of wins is $$$[1,0,0,2,0,1,3,0]$$$. In this example, the winner is the $$$7$$$-th contestant.
This is an interactive problem.There was a tournament consisting of $$$2^n$$$ contestants. The $$$1$$$-st contestant competed with the $$$2$$$-nd, the $$$3$$$-rd competed with the $$$4$$$-th, and so on. After that, the winner of the first match competed with the winner of second match, etc. The tournament ended when there was only one contestant left, who was declared the winner of the tournament. Such a tournament scheme is known as the single-elimination tournament.You don't know the results, but you want to find the winner of the tournament. In one query, you select two integers $$$a$$$ and $$$b$$$, which are the indices of two contestants. The jury will return $$$1$$$ if $$$a$$$ won more matches than $$$b$$$, $$$2$$$ if $$$b$$$ won more matches than $$$a$$$, or $$$0$$$ if their number of wins was equal.Find the winner in no more than $$$\left \lceil \frac{1}{3} \cdot 2^{n + 1} \right \rceil$$$ queries. Here $$$\lceil x \rceil$$$ denotes the value of $$$x$$$ rounded up to the nearest integer.Note that the tournament is long over, meaning that the results are fixed and do not depend on your queries.
null
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2^{14}$$$) β€” the number of test cases. The only line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 17$$$). It is guaranteed that the sum of $$$2^n$$$ over all test cases does not exceed $$$2^{17}$$$.
standard output
standard input
Python 3
Python
1,800
train_088.jsonl
8c798b26dcec2420e69ead7ff40b4ea6
256 megabytes
["1\n3\n\n2\n\n0\n\n2"]
PASSED
t= int(input()) for _ in range(t): n=int(input()) P = [i for i in range(1,2**n+1)] while n>1: k=[] for i in range(0,2**(n)-1,4): print("? ", P[i], P[i+2], flush =True) a = int(input()) if a==0: k.extend([P[i+1],P[i+3]]) elif a==1: k.extend([P[i], P[i+3]]) elif a ==2: k.extend([P[i+2],P[i+1]]) n-=1 P=k print("? ", P[0],P[1],flush =True) a=int(input()) if a ==1:print("!",P[0],flush =True) else:print("!",P[1],flush =True)
1659796500
[ "probabilities", "number theory" ]
[ 0, 0, 0, 0, 1, 1, 0, 0 ]
2 seconds
["2", "1", "3"]
2d3af7ca9bf074d03408d5ade3ddd14c
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
Print a single integerΒ β€” the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$)Β β€” the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$)Β β€” the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
standard output
standard input
PyPy 3-64
Python
2,000
train_107.jsonl
305b68a8a50ca10807d07a0e434f1b3d
256 megabytes
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
PASSED
import sys from collections import defaultdict n, m = tuple(map(int,input().split())) adj = defaultdict(list) indg = [0] * n outdg = [0] * n dp = [1] * n vis = set() finish = [] def dfs(u): vis.add(u) for v in adj[u]: if v not in vis: dfs(v) finish.append(u) for _ in range(m): u, v = tuple(map(int,input().split())) u -= 1 v -= 1 adj[u].append(v) indg[v] += 1 outdg[u] += 1 for i in range(n): if i not in vis: stk = [i] while stk: u = stk.pop() if u in vis: finish.append(u) continue vis.add(u) stk.append(u) for v in adj[u]: if v not in vis: stk.append(v) res = 1 for i in finish: if outdg[i] > 1: for v in adj[i]: if indg[v] > 1: dp[i] = max(dp[i], dp[v] + 1) res = max(res, dp[i]) print(res)
1651502100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1 \n1 2 \n2 1 \n1 3 2"]
67de9506ac2458ee67346bae1a9e3926
NoteIn the first test case, the sequence $$$a = [1]$$$, there is only one permutation $$$p = [1]$$$.In the second test case, the sequence $$$a = [1, 2]$$$. There is no inversion in $$$a$$$, so there is only one permutation $$$p = [1, 2]$$$ which doesn't increase the number of inversions.In the third test case, $$$a = [1, 2, 1]$$$ and has $$$1$$$ inversion. If we use $$$p = [2, 1]$$$, then $$$b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2]$$$ and also has $$$1$$$ inversion.In the fourth test case, $$$a = [1, 2, 3, 2]$$$, and since $$$p = [1, 3, 2]$$$ then $$$b = [1, 3, 2, 3]$$$. Both $$$a$$$ and $$$b$$$ have $$$1$$$ inversion and $$$b$$$ is the lexicographically maximum.
You have a sequence $$$a$$$ with $$$n$$$ elements $$$1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$$$ ($$$k \le n &lt; 2k$$$).Let's call as inversion in $$$a$$$ a pair of indices $$$i &lt; j$$$ such that $$$a[i] &gt; a[j]$$$.Suppose, you have some permutation $$$p$$$ of size $$$k$$$ and you build a sequence $$$b$$$ of size $$$n$$$ in the following manner: $$$b[i] = p[a[i]]$$$.Your goal is to find such permutation $$$p$$$ that the total number of inversions in $$$b$$$ doesn't exceed the total number of inversions in $$$a$$$, and $$$b$$$ is lexicographically maximum.Small reminder: the sequence of $$$k$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$k$$$ exactly once.Another small reminder: a sequence $$$s$$$ is lexicographically smaller than another sequence $$$t$$$, if either $$$s$$$ is a prefix of $$$t$$$, or for the first $$$i$$$ such that $$$s_i \ne t_i$$$, $$$s_i &lt; t_i$$$ holds (in the first position that these sequences are different, $$$s$$$ has smaller number than $$$t$$$).
For each test case, print $$$k$$$ integersΒ β€” the permutation $$$p$$$ which maximizes $$$b$$$ lexicographically without increasing the total number of inversions. It can be proven that $$$p$$$ exists and is unique.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$k \le n &lt; 2k$$$; $$$1 \le k \le 10^5$$$)Β β€” the length of the sequence $$$a$$$ and its maximum. It's guaranteed that the total sum of $$$k$$$ over test cases doesn't exceed $$$10^5$$$.
standard output
standard input
PyPy 3
Python
1,500
train_106.jsonl
c7b34f3059776d9d8cfb1a099e8a0994
256 megabytes
["4\n1 1\n2 2\n3 2\n4 3"]
PASSED
T=int(input()) for _ in range(T): n,k=map(int,input().split()) ans=[i for i in range(1,k+1)] temp=2*k-n-1;k1=k for i in range(temp,k): ans[i]=k1 k1-=1 print(*ans)
1610634900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["bus topology", "ring topology", "star topology", "unknown topology"]
7bb088ce5e4e2101221c706ff87841e4
null
This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown.
In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes).
The first line contains two space-separated integers n and m (4 ≀ n ≀ 105;Β 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.
standard output
standard input
Python 3
Python
1,200
train_010.jsonl
90bcc734f243a7afd337c6088cce541a
256 megabytes
["4 3\n1 2\n2 3\n3 4", "4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n1 2\n1 3\n1 4", "4 4\n1 2\n2 3\n3 1\n1 4"]
PASSED
# brute force baby !!!! from sys import stdin node,edge = map(int,input().split()) capt = [0]*node for l in stdin.readlines(): a,b = map(int,l.split()) capt[a-1] +=1; capt[b-1] += 1 ones,twos = capt.count(1),capt.count(2) if ones == node - 1: print('star topology') elif twos == node: print('ring topology') elif ones == 2 and twos == node - 2: print('bus topology') else: print('unknown topology')
1366040100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["2", "0", "8"]
afd12d95b59b250a0a5af87e5277a3fb
null
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.In total the table Arthur bought has n legs, the length of the i-th leg is li.Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number diΒ β€”Β the amount of energy that he spends to remove the i-th leg.A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.
Print a single integer β€” the minimum number of energy units that Arthur needs to spend in order to make the table stable.
The first line of the input contains integer n (1 ≀ n ≀ 105)Β β€”Β the initial number of legs in the table Arthur bought. The second line of the input contains a sequence of n integers li (1 ≀ li ≀ 105), where li is equal to the length of the i-th leg of the table. The third line of the input contains a sequence of n integers di (1 ≀ di ≀ 200), where di is the number of energy units that Arthur spends on removing the i-th leg off the table.
standard output
standard input
Python 3
Python
1,900
train_058.jsonl
61009ee28122dbb2baea3ad2ff513c7d
256 megabytes
["2\n1 5\n3 2", "3\n2 4 4\n1 1 1", "6\n2 2 1 1 3 3\n4 3 5 5 2 1"]
PASSED
rr = lambda: map(int, input().split()) _, d, res, he = input(), {}, 0, list(zip(rr(), rr())) for h, e in he: f, x = d.get(h, (-1, 0)) d[h] = (f + 1, x + e) he.sort(key = lambda x: x[1], reverse=True) for h, (f, x) in d.items(): if not f: res = max(x, res) continue for h1, e in he: if h1 < h: x += e f -= 1 if not f: break res = max(x, res) print(sum(e for h, e in he) - res)
1435676400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["Yes\nNo\nYes\nNo\nYes"]
e0a3c678f6d1d89420c8162b0ddfcef7
NoteIn the first test case, $$$24$$$ is generated as follows: $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set; $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set; $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.
There is an infinite set generated as follows: $$$1$$$ is in this set. If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are: $$$1$$$, $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set), $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set), $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set), $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.
For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) β€” the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.
standard output
standard input
Python 3
Python
1,500
train_083.jsonl
3cd157b6a29ae11ee904ae9610000f06
512 megabytes
["5\n24 3 5\n10 3 6\n2345 1 4\n19260817 394 485\n19260817 233 264"]
PASSED
import sys input=sys.stdin.readline for _ in range(int(input())): n,a,b=map(int,input().split()) d={} x=1 while True: x=x*a if x<=n and x!=1: d[x]=0 else: break #print(d) y=0 for k in d: y=1 if (n%b==1) or ((n%b) in d) or ((n-k)%b==0) or b==1: print("YES") break else: if y==0: if n%b==1 or b==1: print("YES") else: print("NO") else: print("NO")
1625317500
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
3 seconds
["3\n1 3 7", "1\n5"]
faa26846744b7b7f90ba1b521fee0bc6
null
Polycarp invented a new way to encode strings. Let's assume that we have string T, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in T with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom".Polycarpus already has two strings, S and T. He suspects that string T was obtained after applying the given encoding method from some substring of string S. Find all positions mi in S (1 ≀ mi ≀ |S| - |T| + 1), such that T can be obtained fro substring SmiSmi + 1... Smi + |T| - 1 by applying the described encoding operation by using some set of pairs of English alphabet letters
Print number k β€” the number of suitable positions in string S. In the next line print k integers m1, m2, ..., mk β€” the numbers of the suitable positions in the increasing order.
The first line of the input contains two integers, |S| and |T| (1 ≀ |T| ≀ |S| ≀ 2Β·105) β€” the lengths of string S and string T, respectively. The second and third line of the input contain strings S and T, respectively. Both strings consist only of lowercase English letters.
standard output
standard input
PyPy 2
Python
2,400
train_040.jsonl
308d274e59cf2b8cf47f26b2d39d3cdb
256 megabytes
["11 5\nabacabadaba\nacaba", "21 13\nparaparallelogramgram\nqolorreraglom"]
PASSED
raw_input() ss = raw_input() tt = raw_input() def df(s): c = {} res = [] for i, x in enumerate(s): res.append(i - c[x] if x in c else 0) c[x] = i return res s = df(ss) t = df(tt) p = [] l = [] for i, x in enumerate(t): if not x: p.append(i) l.append(ord(tt[i]) - 97) nt = len(l) def prefix_func(s): pi = [0] * len(s) for i in xrange(1, len(s)): j = pi[i - 1] while j > 0 and not (s[i] == s[j] or (not s[j] and s[i] > j)): j = pi[j - 1] pi[i] = j + 1 if s[i] == s[j] or (not s[j] and s[i] > j) else j return pi pi = prefix_func(t + [-1] + s) n = len(t) res = [] ss = [ord(x) - 97 for x in ss] def check(pos): d = [-1] * 26 for i in xrange(nt): j = p[i] x = ss[j + pos] y = l[i] if d[x] >= 0 and d[x] != y: return False if d[y] >= 0 and d[y] != x: return False d[x] = y d[y] = x return True for i, x in enumerate(pi): j = i - 2 * n if x != n or not check(j): continue res.append(j + 1) print len(res) print ' '.join(map(str, res))
1429286400
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["9", "14", "448201910"]
fbb6d21b757d8d56396af1253ec9e719
NoteIn the first example, the elements smaller than $$$2^4$$$ are $$$\{1, 3, 4, 6, 7, 9, 12, 13, 15\}$$$.In the second example, the elements smaller than $$$2^7$$$ are $$$\{5,11,20,23,39,41,44,47,79,80,83,89,92,95\}$$$.
You are given an array $$$a$$$ consisting of $$$n$$$ distinct positive integers.Let's consider an infinite integer set $$$S$$$ which contains all integers $$$x$$$ that satisfy at least one of the following conditions: $$$x = a_i$$$ for some $$$1 \leq i \leq n$$$. $$$x = 2y + 1$$$ and $$$y$$$ is in $$$S$$$. $$$x = 4y$$$ and $$$y$$$ is in $$$S$$$.For example, if $$$a = [1,2]$$$ then the $$$10$$$ smallest elements in $$$S$$$ will be $$$\{1,2,3,4,5,7,8,9,11,12\}$$$.Find the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Since this number may be too large, print it modulo $$$10^9 + 7$$$.
Print a single integer, the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Remember to print it modulo $$$10^9 + 7$$$.
The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 2 \cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$. It is guaranteed that all the numbers in $$$a$$$ are distinct.
standard output
standard input
PyPy 3-64
Python
1,800
train_108.jsonl
e2bf28c0f855ccb4bb78b2d437d07090
256 megabytes
["2 4\n6 1", "4 7\n20 39 5 200", "2 200000\n48763 1000000000"]
PASSED
import sys from array import array class dict_(dict): def __missing__(self, key): return 0 mod = 10 ** 9 + 7 add = lambda a, b: (a % mod + b % mod) % mod mult = lambda a, b: (a % mod * b % mod) % mod input = lambda: sys.stdin.buffer.readline().decode().strip() n, p = map(int, input().split()) a = array('i', [int(x) for x in input().split()]) dp = array('i', [0] * (p + 1)) mem, ans = set(), 0 dp[0] = dp[1] = 1 for i in range(2, p + 1): dp[i] = add(dp[i - 2], dp[i - 1]) for i in range(1, p + 1): dp[i] = add(dp[i], dp[i - 1]) for bit in range(1, min(30, p) + 1): for i in range(n): if a[i].bit_length() == bit: su, cur = dp[p - bit], a[i] while cur: if cur & 1: cur >>= 1 elif cur % 4 == 0: cur >>= 2 else: break if cur in mem: su = 0 break mem.add(a[i]) ans += su print(ans % mod)
1645367700
[ "number theory", "math", "strings" ]
[ 0, 0, 0, 1, 1, 0, 1, 0 ]
1.5 seconds
["6", "-1", "5"]
aba6e64e040952b88e7dcb95e4472e56
NoteIn the first example the answer is $$$6$$$ since it divides $$$18$$$ from the first pair, $$$24$$$ from the second and $$$12$$$ from the third ones. Note that other valid answers will also be accepted.In the second example there are no integers greater than $$$1$$$ satisfying the conditions.In the third example one of the possible answers is $$$5$$$. Note that, for example, $$$15$$$ is also allowed, but it's not necessary to maximize the output.
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ their WCD is arbitrary integer greater than $$$1$$$, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like $$$[(12, 15), (25, 18), (10, 24)]$$$, then their WCD can be equal to $$$2$$$, $$$3$$$, $$$5$$$ or $$$6$$$ (each of these numbers is strictly greater than $$$1$$$ and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.
Print a single integerΒ β€” the WCD of the set of pairs. If there are multiple possible answers, output any; if there is no answer, print $$$-1$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 150\,000$$$)Β β€” the number of pairs. Each of the next $$$n$$$ lines contains two integer values $$$a_i$$$, $$$b_i$$$ ($$$2 \le a_i, b_i \le 2 \cdot 10^9$$$).
standard output
standard input
Python 2
Python
1,600
train_010.jsonl
f392c1dfb3b2e547acebc963d48c5606
256 megabytes
["3\n17 18\n15 24\n12 15", "2\n10 16\n7 17", "5\n90 108\n45 105\n75 40\n165 175\n33 30"]
PASSED
def gcd(a,b): if b==0:return a return gcd(b,a%b) n=int(raw_input()) d = 0 prime_lim = 0 nums = [] for i in xrange(n): a,b=map(int,raw_input().split()) nums.append((a,b)) d = gcd(d, a*b) prime_lim=max(prime_lim,a,b) k = int(prime_lim**0.5)+5 k=min(k,d-1) for i in xrange(2,k+1): if d%i==0: d = i break if d > prime_lim: for a,b in nums: if a*b == d: d = a break if d==1:d=-1 print d
1534685700
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
3 seconds
["6\n12\n9\n-1\n10\n7"]
d665ecbf36cc0c0ddd148137fb693bf2
NoteFor the first test case, we can choose $$$i = j = 3$$$, with sum of indices equal to $$$6$$$, since $$$1$$$ and $$$1$$$ are coprime.For the second test case, we can choose $$$i = 7$$$ and $$$j = 5$$$, with sum of indices equal to $$$7 + 5 = 12$$$, since $$$7$$$ and $$$4$$$ are coprime.
Given an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$). Find the maximum value of $$$i + j$$$ such that $$$a_i$$$ and $$$a_j$$$ are coprime,$$$^{\dagger}$$$ or $$$-1$$$ if no such $$$i$$$, $$$j$$$ exist.For example consider the array $$$[1, 3, 5, 2, 4, 7, 7]$$$. The maximum value of $$$i + j$$$ that can be obtained is $$$5 + 7$$$, since $$$a_5 = 4$$$ and $$$a_7 = 7$$$ are coprime.$$$^{\dagger}$$$ Two integers $$$p$$$ and $$$q$$$ are coprime if the only positive integer that is a divisor of both of them is $$$1$$$ (that is, their greatest common divisor is $$$1$$$).
For each test case, output a single integer Β β€” the maximum value of $$$i + j$$$ such that $$$i$$$ and $$$j$$$ satisfy the condition that $$$a_i$$$ and $$$a_j$$$ are coprime, or output $$$-1$$$ in case no $$$i$$$, $$$j$$$ satisfy the condition.
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10$$$)Β β€” the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \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$$$ ($$$1 \leq a_i \leq 1000$$$)Β β€” 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_099.jsonl
da7e17c0e53313bf640e667debf2484a
256 megabytes
["6\n\n3\n\n3 2 1\n\n7\n\n1 3 5 2 4 7 7\n\n5\n\n1 2 3 4 5\n\n3\n\n2 2 4\n\n6\n\n5 4 3 15 12 16\n\n5\n\n1 2 2 3 6"]
PASSED
num = int(input()) res = [] factors = [{1}, {1, 2}, {1, 3}, {1, 2}, {1, 5}, {1, 2, 3}, {1, 7}, {1, 2}, {1, 3}, {1, 2, 5}, {1, 11}, {1, 2, 3}, {1, 13}, {1, 2, 7}, {1, 3, 5}, {1, 2}, {1, 17}, {1, 2, 3}, {1, 19}, {1, 2, 5}, {1, 3, 7}, {1, 2, 11}, {1, 23}, {1, 2, 3}, {1, 5}, {1, 2, 13}, {1, 3}, {1, 2, 7}, {1, 29}, {1, 2, 3, 5}, {1, 31}, {1, 2}, {3, 1, 11}, {1, 2, 17}, {1, 5, 7}, {1, 2, 3}, {1, 37}, {1, 2, 19}, {1, 3, 13}, {1, 2, 5}, {1, 41}, {1, 2, 3, 7}, {1, 43}, {1, 2, 11}, {1, 3, 5}, {1, 2, 23}, {1, 47}, {1, 2, 3}, {1, 7}, {1, 2, 5}, {1, 3, 17}, {1, 2, 13}, {1, 53}, {1, 2, 3}, {1, 11, 5}, {1, 2, 7}, {3, 1, 19}, {1, 2, 29}, {1, 59}, {1, 2, 3, 5}, {1, 61}, {1, 2, 31}, {1, 3, 7}, {1, 2}, {1, 5, 13}, {3, 1, 2, 11}, {1, 67}, {1, 2, 17}, {1, 3, 23}, {1, 2, 5, 7}, {1, 71}, {1, 2, 3}, {73, 1}, {1, 2, 37}, {1, 3, 5}, {1, 2, 19}, {1, 11, 7}, {1, 2, 3, 13}, {1, 79}, {1, 2, 5}, {1, 3}, {1, 2, 41}, {1, 83}, {1, 2, 3, 7}, {1, 5, 17}, {1, 2, 43}, {1, 3, 29}, {1, 2, 11}, {89, 1}, {1, 2, 3, 5}, {1, 13, 7}, {1, 2, 23}, {1, 3, 31}, {1, 2, 47}, {1, 19, 5}, {1, 2, 3}, {1, 97}, {1, 2, 7}, {3, 1, 11}, {1, 2, 5}, {1, 101}, {1, 2, 3, 17}, {1, 103}, {1, 2, 13}, {1, 3, 5, 7}, {1, 2, 53}, {1, 107}, {1, 2, 3}, {1, 109}, {1, 2, 11, 5}, {1, 3, 37}, {1, 2, 7}, {1, 113}, {3, 1, 2, 19}, {1, 5, 23}, {1, 2, 29}, {1, 3, 13}, {1, 2, 59}, {1, 17, 7}, {1, 2, 3, 5}, {1, 11}, {1, 2, 61}, {1, 3, 41}, {1, 2, 31}, {1, 5}, {1, 2, 3, 7}, {1, 127}, {1, 2}, {3, 1, 43}, {1, 2, 5, 13}, {1, 131}, {3, 1, 2, 11}, {1, 19, 7}, {1, 2, 67}, {1, 3, 5}, {1, 2, 17}, {1, 137}, {1, 2, 3, 23}, {1, 139}, {1, 2, 5, 7}, {1, 3, 47}, {1, 2, 71}, {1, 11, 13}, {1, 2, 3}, {1, 5, 29}, {73, 1, 2}, {1, 3, 7}, {1, 2, 37}, {1, 149}, {1, 2, 3, 5}, {1, 151}, {1, 2, 19}, {1, 3, 17}, {1, 2, 11, 7}, {1, 5, 31}, {1, 2, 3, 13}, {1, 157}, {1, 2, 79}, {1, 3, 53}, {1, 2, 5}, {1, 7, 23}, {1, 2, 3}, {1, 163}, {1, 2, 41}, {3, 1, 11, 5}, {1, 2, 83}, {1, 167}, {1, 2, 3, 7}, {1, 13}, {1, 2, 5, 17}, {3, 1, 19}, {1, 2, 43}, {1, 173}, {1, 2, 3, 29}, {1, 5, 7}, {1, 2, 11}, {3, 1, 59}, {89, 1, 2}, {1, 179}, {1, 2, 3, 5}, {1, 181}, {1, 2, 13, 7}, {1, 3, 61}, {1, 2, 23}, {1, 5, 37}, {1, 2, 3, 31}, {1, 11, 17}, {1, 2, 47}, {1, 3, 7}, {1, 2, 19, 5}, {1, 191}, {1, 2, 3}, {1, 193}, {1, 2, 97}, {1, 5, 3, 13}, {1, 2, 7}, {1, 197}, {3, 1, 2, 11}, {1, 199}, {1, 2, 5}, {3, 1, 67}, {1, 2, 101}, {1, 29, 7}, {1, 2, 3, 17}, {1, 5, 41}, {1, 2, 103}, {1, 3, 23}, {1, 2, 13}, {11, 1, 19}, {1, 2, 3, 5, 7}, {1, 211}, {1, 2, 53}, {1, 3, 71}, {1, 2, 107}, {1, 43, 5}, {1, 2, 3}, {1, 7, 31}, {1, 2, 109}, {73, 1, 3}, {1, 2, 11, 5}, {1, 13, 17}, {1, 2, 3, 37}, {1, 223}, {1, 2, 7}, {1, 3, 5}, {1, 2, 113}, {1, 227}, {3, 1, 2, 19}, {1, 229}, {1, 2, 5, 23}, {3, 1, 11, 7}, {1, 2, 29}, {1, 233}, {1, 2, 3, 13}, {1, 5, 47}, {1, 2, 59}, {1, 3, 79}, {1, 2, 17, 7}, {1, 239}, {1, 2, 3, 5}, {1, 241}, {1, 2, 11}, {1, 3}, {1, 2, 61}, {1, 5, 7}, {1, 2, 3, 41}, {1, 19, 13}, {1, 2, 31}, {3, 1, 83}, {1, 2, 5}, {1, 251}, {1, 2, 3, 7}, {1, 11, 23}, {1, 2, 127}, {1, 3, 5, 17}, {1, 2}, {1, 257}, {3, 1, 2, 43}, {1, 37, 7}, {1, 2, 5, 13}, {1, 3, 29}, {1, 2, 131}, {1, 263}, {3, 1, 2, 11}, {1, 5, 53}, {1, 2, 19, 7}, {89, 1, 3}, {1, 2, 67}, {1, 269}, {1, 2, 3, 5}, {1, 271}, {1, 2, 17}, {1, 3, 13, 7}, {1, 137, 2}, {1, 11, 5}, {1, 2, 3, 23}, {1, 277}, {1, 2, 139}, {1, 3, 31}, {1, 2, 5, 7}, {1, 281}, {1, 2, 3, 47}, {1, 283}, {1, 2, 71}, {3, 1, 19, 5}, {1, 2, 11, 13}, {1, 7, 41}, {1, 2, 3}, {1, 17}, {1, 2, 5, 29}, {1, 3, 97}, {73, 1, 2}, {1, 293}, {1, 2, 3, 7}, {1, 59, 5}, {1, 2, 37}, {3, 1, 11}, {1, 2, 149}, {1, 13, 23}, {1, 2, 3, 5}, {1, 43, 7}, {1, 2, 151}, {1, 3, 101}, {1, 2, 19}, {1, 5, 61}, {1, 2, 3, 17}, {1, 307}, {1, 2, 11, 7}, {1, 3, 103}, {1, 2, 5, 31}, {1, 311}, {1, 2, 3, 13}, {1, 313}, {1, 2, 157}, {1, 3, 5, 7}, {1, 2, 79}, {1, 317}, {1, 2, 3, 53}, {1, 11, 29}, {1, 2, 5}, {3, 1, 107}, {1, 2, 7, 23}, {1, 19, 17}, {1, 2, 3}, {1, 5, 13}, {1, 2, 163}, {1, 3, 109}, {1, 2, 41}, {1, 7, 47}, {1, 2, 3, 5, 11}, {1, 331}, {1, 2, 83}, {1, 3, 37}, {1, 2, 167}, {1, 67, 5}, {1, 2, 3, 7}, {337, 1}, {1, 2, 13}, {1, 3, 113}, {1, 2, 5, 17}, {1, 11, 31}, {3, 1, 2, 19}, {1, 7}, {1, 2, 43}, {1, 3, 5, 23}, {1, 2, 173}, {1, 347}, {1, 2, 3, 29}, {1, 349}, {1, 2, 5, 7}, {1, 3, 13}, {1, 2, 11}, {1, 353}, {3, 1, 2, 59}, {1, 5, 71}, {89, 1, 2}, {1, 3, 17, 7}, {1, 2, 179}, {1, 359}, {1, 2, 3, 5}, {1, 19}, {1, 2, 181}, {3, 1, 11}, {1, 2, 13, 7}, {73, 1, 5}, {1, 2, 3, 61}, {1, 367}, {1, 2, 23}, {1, 3, 41}, {1, 2, 5, 37}, {1, 53, 7}, {1, 2, 3, 31}, {1, 373}, {1, 2, 11, 17}, {1, 3, 5}, {1, 2, 47}, {1, 13, 29}, {1, 2, 3, 7}, {1, 379}, {1, 2, 19, 5}, {1, 3, 127}, {1, 2, 191}, {1, 383}, {1, 2, 3}, {1, 11, 5, 7}, {1, 2, 193}, {3, 1, 43}, {1, 2, 97}, {1, 389}, {1, 2, 3, 5, 13}, {1, 17, 23}, {1, 2, 7}, {1, 3, 131}, {1, 2, 197}, {1, 5, 79}, {3, 1, 2, 11}, {1, 397}, {1, 2, 199}, {3, 1, 19, 7}, {1, 2, 5}, {1, 401}, {3, 1, 2, 67}, {1, 13, 31}, {1, 2, 101}, {1, 3, 5}, {1, 2, 29, 7}, {1, 11, 37}, {1, 2, 3, 17}, {1, 409}, {1, 2, 5, 41}, {1, 137, 3}, {1, 2, 103}, {1, 59, 7}, {1, 2, 3, 23}, {1, 83, 5}, {1, 2, 13}, {1, 3, 139}, {11, 1, 2, 19}, {1, 419}, {1, 2, 3, 5, 7}, {1, 421}, {1, 2, 211}, {1, 3, 47}, {1, 2, 53}, {1, 5, 17}, {1, 2, 3, 71}, {1, 61, 7}, {1, 2, 107}, {3, 1, 11, 13}, {1, 2, 43, 5}, {1, 431}, {1, 2, 3}, {1, 433}, {1, 2, 7, 31}, {1, 5, 3, 29}, {1, 2, 109}, {1, 19, 23}, {73, 1, 2, 3}, {1, 439}, {1, 2, 11, 5}, {1, 3, 7}, {1, 2, 13, 17}, {1, 443}, {1, 2, 3, 37}, {89, 1, 5}, {1, 2, 223}, {1, 3, 149}, {1, 2, 7}, {1, 449}, {1, 2, 3, 5}, {1, 11, 41}, {1, 2, 113}, {1, 3, 151}, {1, 2, 227}, {1, 5, 13, 7}, {3, 1, 2, 19}, {1, 457}, {1, 2, 229}, {1, 3, 17}, {1, 2, 5, 23}, {1, 461}, {1, 2, 3, 7, 11}, {1, 463}, {1, 2, 29}, {1, 3, 5, 31}, {1, 2, 233}, {1, 467}, {1, 2, 3, 13}, {1, 67, 7}, {1, 2, 5, 47}, {1, 3, 157}, {1, 2, 59}, {11, 1, 43}, {1, 2, 3, 79}, {1, 19, 5}, {1, 2, 17, 7}, {1, 3, 53}, {1, 2, 239}, {1, 479}, {1, 2, 3, 5}, {1, 13, 37}, {1, 2, 241}, {1, 3, 7, 23}, {1, 2, 11}, {1, 5, 97}, {1, 2, 3}, {1, 487}, {1, 2, 61}, {1, 3, 163}, {1, 2, 5, 7}, {1, 491}, {1, 2, 3, 41}, {1, 29, 17}, {1, 2, 19, 13}, {3, 1, 11, 5}, {1, 2, 31}, {1, 7, 71}, {3, 1, 2, 83}, {1, 499}, {1, 2, 5}, {1, 3, 167}, {1, 2, 251}, {1, 503}, {1, 2, 3, 7}, {1, 5, 101}, {1, 2, 11, 23}, {1, 3, 13}, {1, 2, 127}, {1, 509}, {1, 2, 3, 5, 17}, {73, 1, 7}, {1, 2}, {3, 1, 19}, {1, 2, 257}, {1, 5, 103}, {3, 1, 2, 43}, {1, 11, 47}, {1, 2, 37, 7}, {1, 3, 173}, {1, 2, 5, 13}, {1, 521}, {1, 2, 3, 29}, {1, 523}, {1, 2, 131}, {1, 3, 5, 7}, {1, 2, 263}, {1, 17, 31}, {3, 1, 2, 11}, {1, 23}, {1, 2, 5, 53}, {3, 1, 59}, {1, 2, 19, 7}, {1, 13, 41}, {89, 1, 2, 3}, {1, 107, 5}, {1, 2, 67}, {1, 3, 179}, {1, 2, 269}, {1, 11, 7}, {1, 2, 3, 5}, {1, 541}, {1, 2, 271}, {1, 3, 181}, {1, 2, 17}, {1, 5, 109}, {1, 2, 3, 7, 13}, {1, 547}, {1, 137, 2}, {1, 3, 61}, {1, 2, 11, 5}, {1, 19, 29}, {1, 2, 3, 23}, {1, 7, 79}, {1, 2, 277}, {1, 5, 3, 37}, {1, 2, 139}, {1, 557}, {1, 2, 3, 31}, {1, 43, 13}, {1, 2, 5, 7}, {3, 1, 11, 17}, {1, 2, 281}, {1, 563}, {1, 2, 3, 47}, {1, 5, 113}, {1, 2, 283}, {1, 3, 7}, {1, 2, 71}, {1, 569}, {1, 2, 3, 5, 19}, {1, 571}, {1, 2, 11, 13}, {1, 3, 191}, {1, 2, 7, 41}, {1, 5, 23}, {1, 2, 3}, {577, 1}, {1, 2, 17}, {1, 3, 193}, {1, 2, 5, 29}, {1, 83, 7}, {1, 2, 3, 97}, {1, 11, 53}, {73, 1, 2}, {1, 5, 3, 13}, {1, 2, 293}, {1, 587}, {1, 2, 3, 7}, {1, 19, 31}, {1, 2, 59, 5}, {1, 3, 197}, {1, 2, 37}, {593, 1}, {3, 1, 2, 11}, {1, 5, 17, 7}, {1, 2, 149}, {1, 3, 199}, {1, 2, 13, 23}, {1, 599}, {1, 2, 3, 5}, {601, 1}, {1, 2, 43, 7}, {3, 1, 67}, {1, 2, 151}, {1, 11, 5}, {1, 2, 3, 101}, {1, 607}, {1, 2, 19}, {1, 3, 29, 7}, {1, 2, 5, 61}, {1, 13, 47}, {1, 2, 3, 17}, {1, 613}, {1, 2, 307}, {1, 3, 5, 41}, {1, 2, 11, 7}, {1, 617}, {1, 2, 3, 103}, {1, 619}, {1, 2, 5, 31}, {1, 3, 23}, {1, 2, 311}, {89, 1, 7}, {1, 2, 3, 13}, {1, 5}, {1, 2, 313}, {19, 1, 11, 3}, {1, 2, 157}, {1, 37, 17}, {1, 2, 3, 5, 7}, {1, 631}, {1, 2, 79}, {1, 3, 211}, {1, 2, 317}, {1, 5, 127}, {1, 2, 3, 53}, {1, 13, 7}, {1, 2, 11, 29}, {1, 3, 71}, {1, 2, 5}, {1, 641}, {3, 1, 2, 107}, {1, 643}, {1, 2, 7, 23}, {3, 1, 43, 5}, {1, 2, 19, 17}, {1, 647}, {1, 2, 3}, {11, 1, 59}, {1, 2, 5, 13}, {1, 3, 7, 31}, {1, 2, 163}, {1, 653}, {1, 2, 3, 109}, {1, 131, 5}, {1, 2, 41}, {73, 1, 3}, {1, 2, 7, 47}, {1, 659}, {1, 2, 3, 5, 11}, {1, 661}, {1, 2, 331}, {1, 3, 13, 17}, {1, 2, 83}, {1, 19, 5, 7}, {1, 2, 3, 37}, {1, 29, 23}, {1, 2, 167}, {1, 3, 223}, {1, 2, 67, 5}, {1, 11, 61}, {1, 2, 3, 7}, {1, 673}, {337, 1, 2}, {1, 3, 5}, {1, 2, 13}, {1, 677}, {1, 2, 3, 113}, {1, 97, 7}, {1, 2, 5, 17}, {1, 3, 227}, {1, 2, 11, 31}, {1, 683}, {3, 1, 2, 19}, {1, 137, 5}, {1, 2, 7}, {1, 3, 229}, {1, 2, 43}, {1, 13, 53}, {1, 2, 3, 5, 23}, {1, 691}, {1, 2, 173}, {3, 1, 11, 7}, {1, 2, 347}, {1, 139, 5}, {1, 2, 3, 29}, {1, 17, 41}, {1, 2, 349}, {1, 3, 233}, {1, 2, 5, 7}, {1, 701}, {1, 2, 3, 13}, {1, 19, 37}, {1, 2, 11}, {1, 3, 5, 47}, {1, 2, 353}, {1, 101, 7}, {3, 1, 2, 59}, {1, 709}, {1, 2, 5, 71}, {1, 3, 79}, {89, 1, 2}, {1, 23, 31}, {1, 2, 3, 7, 17}, {1, 5, 11, 13}, {1, 2, 179}, {1, 3, 239}, {1, 2, 359}, {1, 719}, {1, 2, 3, 5}, {1, 7, 103}, {1, 2, 19}, {1, 3, 241}, {1, 2, 181}, {1, 5, 29}, {3, 1, 2, 11}, {1, 727}, {1, 2, 13, 7}, {1, 3}, {73, 1, 2, 5}, {1, 43, 17}, {1, 2, 3, 61}, {1, 733}, {1, 2, 367}, {1, 3, 5, 7}, {1, 2, 23}, {11, 1, 67}, {1, 2, 3, 41}, {1, 739}, {1, 2, 5, 37}, {3, 1, 19, 13}, {1, 2, 53, 7}, {1, 743}, {1, 2, 3, 31}, {1, 5, 149}, {1, 2, 373}, {3, 1, 83}, {1, 2, 11, 17}, {1, 107, 7}, {1, 2, 3, 5}, {1, 751}, {1, 2, 47}, {1, 3, 251}, {1, 2, 13, 29}, {1, 5, 151}, {1, 2, 3, 7}, {1, 757}, {1, 2, 379}, {3, 1, 11, 23}, {1, 2, 19, 5}, {1, 761}, {1, 2, 3, 127}, {1, 109, 7}, {1, 2, 191}, {1, 3, 5, 17}, {1, 2, 383}, {1, 59, 13}, {1, 2, 3}, {1, 769}, {1, 2, 5, 7, 11}, {1, 3, 257}, {1, 2, 193}, {1, 773}, {3, 1, 2, 43}, {1, 5, 31}, {1, 2, 97}, {1, 3, 37, 7}, {1, 2, 389}, {1, 19, 41}, {1, 2, 3, 5, 13}, {1, 11, 71}, {1, 2, 17, 23}, {1, 3, 29}, {1, 2, 7}, {1, 5, 157}, {1, 2, 3, 131}, {1, 787}, {1, 2, 197}, {1, 3, 263}, {1, 2, 5, 79}, {1, 113, 7}, {3, 1, 2, 11}, {1, 13, 61}, {1, 2, 397}, {1, 5, 3, 53}, {1, 2, 199}, {1, 797}, {1, 2, 3, 7, 19}, {1, 17, 47}, {1, 2, 5}, {89, 1, 3}, {1, 401, 2}, {73, 1, 11}, {3, 1, 2, 67}, {1, 7, 5, 23}, {1, 2, 13, 31}, {1, 3, 269}, {1, 2, 101}, {1, 809}, {1, 2, 3, 5}, {1, 811}, {1, 2, 29, 7}, {1, 3, 271}, {1, 2, 11, 37}, {1, 163, 5}, {1, 2, 3, 17}, {19, 1, 43}, {1, 409, 2}, {1, 3, 13, 7}, {1, 2, 5, 41}, {1, 821}, {3, 1, 137, 2}, {1, 823}, {1, 2, 103}, {3, 1, 11, 5}, {1, 2, 59, 7}, {1, 827}, {1, 2, 3, 23}, {1, 829}, {1, 2, 83, 5}, {1, 3, 277}, {1, 2, 13}, {1, 17, 7}, {1, 2, 3, 139}, {1, 5, 167}, {11, 1, 2, 19}, {1, 3, 31}, {1, 2, 419}, {1, 839}, {1, 2, 3, 5, 7}, {1, 29}, {1, 2, 421}, {1, 3, 281}, {1, 2, 211}, {1, 5, 13}, {1, 2, 3, 47}, {1, 11, 7}, {1, 2, 53}, {3, 1, 283}, {1, 2, 5, 17}, {1, 37, 23}, {1, 2, 3, 71}, {1, 853}, {1, 2, 61, 7}, {3, 1, 19, 5}, {1, 2, 107}, {857, 1}, {1, 2, 3, 11, 13}, {1, 859}, {1, 2, 43, 5}, {1, 3, 7, 41}, {1, 2, 431}, {1, 863}, {1, 2, 3}, {1, 5, 173}, {1, 2, 433}, {1, 3, 17}, {1, 2, 7, 31}, {1, 11, 79}, {1, 2, 3, 5, 29}, {1, 67, 13}, {1, 2, 109}, {1, 3, 97}, {1, 2, 19, 23}, {1, 5, 7}, {73, 1, 2, 3}, {1, 877}, {1, 2, 439}, {1, 3, 293}, {1, 2, 11, 5}, {1, 881}, {1, 2, 3, 7}, {1, 883}, {1, 2, 13, 17}, {3, 1, 59, 5}, {1, 2, 443}, {1, 887}, {1, 2, 3, 37}, {1, 7, 127}, {89, 1, 2, 5}, {3, 1, 11}, {1, 2, 223}, {1, 19, 47}, {1, 2, 3, 149}, {1, 179, 5}, {1, 2, 7}, {1, 3, 13, 23}, {1, 2, 449}, {1, 29, 31}, {1, 2, 3, 5}, {1, 53, 17}, {1, 2, 11, 41}, {3, 1, 43, 7}, {1, 2, 113}, {1, 5, 181}, {1, 2, 3, 151}, {1, 907}, {1, 2, 227}, {1, 3, 101}, {1, 2, 5, 7, 13}, {1, 911}, {3, 1, 2, 19}, {11, 1, 83}, {1, 2, 457}, {1, 5, 3, 61}, {1, 2, 229}, {1, 131, 7}, {1, 2, 3, 17}, {1, 919}, {1, 2, 5, 23}, {3, 1, 307}, {1, 2, 461}, {1, 13, 71}, {1, 2, 3, 7, 11}, {1, 5, 37}, {1, 2, 463}, {1, 3, 103}, {1, 2, 29}, {1, 929}, {1, 2, 3, 5, 31}, {1, 19, 7}, {1, 2, 233}, {1, 3, 311}, {1, 2, 467}, {1, 11, 5, 17}, {1, 2, 3, 13}, {1, 937}, {1, 2, 67, 7}, {1, 3, 313}, {1, 2, 5, 47}, {1, 941}, {1, 2, 3, 157}, {1, 23, 41}, {1, 2, 59}, {1, 3, 5, 7}, {11, 1, 2, 43}, {1, 947}, {1, 2, 3, 79}, {73, 1, 13}, {1, 2, 19, 5}, {1, 3, 317}, {1, 2, 17, 7}, {1, 953}, {1, 2, 3, 53}, {1, 5, 191}, {1, 2, 239}, {3, 1, 11, 29}, {1, 2, 479}, {1, 137, 7}, {1, 2, 3, 5}, {1, 31}, {1, 2, 13, 37}, {3, 1, 107}, {1, 2, 241}, {1, 193, 5}, {1, 2, 3, 7, 23}, {1, 967}, {1, 2, 11}, {3, 1, 19, 17}, {1, 2, 5, 97}, {1, 971}, {1, 2, 3}, {1, 139, 7}, {1, 2, 487}, {1, 5, 3, 13}, {1, 2, 61}, {1, 977}, {1, 2, 3, 163}, {89, 1, 11}, {1, 2, 5, 7}, {1, 3, 109}, {1, 2, 491}, {1, 983}, {1, 2, 3, 41}, {1, 5, 197}, {1, 2, 29, 17}, {1, 3, 7, 47}, {1, 2, 19, 13}, {1, 43, 23}, {1, 2, 3, 5, 11}, {1, 991}, {1, 2, 31}, {3, 1, 331}, {1, 2, 7, 71}, {1, 5, 199}, {3, 1, 2, 83}, {1, 997}, {1, 2, 499}, {1, 3, 37}, {1, 2, 5}] def coprime(x, y): return factors[x - 1] & factors[y - 1] == {1} for _ in range(num): b = int(input()) l = list(map(int, input().split(" "))) inds = {} for i, elem in enumerate(l): if elem not in inds: inds[elem] = 0 inds[elem] = i rl = l[::-1] sl = list(set(l)) xi = -1 for ins in range(len(sl) ** 2): x1, x2 = ins // len(sl), ins % len(sl) a1 = sl[x1] b1 = sl[x2] if coprime(a1, b1): xi = max(inds[a1] + inds[b1] + 2, xi) #res.append(xi) print(xi) #print(res)
1665671700
[ "number theory" ]
[ 0, 0, 0, 0, 1, 0, 0, 0 ]
7 seconds
["3", "1"]
4fb83b890e472f86045981e1743ddaac
NoteIn the first sample, Jacob can root the tree at node 2 and order 2's neighbors in the order 4, 1, 5 (all other nodes have at most two neighbors). The resulting preorder traversal is 2, 4, 1, 3, 5, and the minimum ai of the first 3 nodes is 3.In the second sample, it is clear that any preorder traversal will contain node 1 as either its first or second node, so Jacob cannot do better than a grade of 1.
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum ai she finds among those k nodes.Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following: Print v. Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u.
Print a single integerΒ β€” the maximum grade Jacob can get by picking the right root of the tree and rearranging the list of neighbors.
The first line of the input contains two positive integers, n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ n)Β β€” the number of balls in Jacob's tree and the number of balls the teacher will inspect. The second line contains n integers, ai (1 ≀ ai ≀ 1 000 000), the time Jacob used to build the i-th ball. Each of the next n - 1 lines contains two integers ui, vi (1 ≀ ui, vi ≀ n, ui ≠ vi) representing a connection in Jacob's tree between balls ui and vi.
standard output
standard input
PyPy 3
Python
2,600
train_062.jsonl
002239c9a0001f9102742563ffdc91d1
256 megabytes
["5 3\n3 6 1 4 2\n1 2\n2 4\n2 5\n1 3", "4 2\n1 5 5 5\n1 2\n1 3\n1 4"]
PASSED
import sys input = sys.stdin.readline n, k = map(int, input().split()) a = [int(i) for i in input().split()] g = [[] for _ in range(n)] for i in range(n - 1): u, v = map(int, input().split()) g[u-1].append(v-1) g[v-1].append(u-1) stack = [0] done = [False] * n par = [0] * n order = [] while len(stack) > 0: x = stack.pop() done[x] = True order.append(x) for i in g[x]: if done[i] == False: par[i] = x stack.append(i) order = order[::-1] sub = [0] * n for i in order: sub[i] = 1 for j in g[i]: if par[j] == i: sub[i] += sub[j] def good(guess): cnt = [0] * n for i in order: if a[i] < guess: continue cnt[i] = 1 opt = 0 for j in g[i]: if par[j] == i: if cnt[j] == sub[j]: cnt[i] += cnt[j] else: opt = max(opt, cnt[j]) cnt[i] += opt if cnt[0] >= k: return True up = [0] * n for i in order[::-1]: if a[i] < guess: continue opt, secondOpt = 0, 0 total = 1 for j in g[i]: val, size = 0, 0 if par[j] == i: val = cnt[j] size = sub[j] else: val = up[i] size = n - sub[i] if val == size: total += val else: if opt < val: opt, secondOpt = val, opt elif secondOpt < val: secondOpt = val for j in g[i]: if par[j] == i: up[j] = total add = opt if sub[j] == cnt[j]: up[j] -= cnt[j] elif cnt[j] == opt: add = secondOpt up[j] += add for i in range(n): if a[i] < guess: continue total, opt = 1, 0 for j in g[i]: val, size = 0, 0 if par[j] == i: val = cnt[j] size = sub[j] else: val = up[i] size = n - sub[i] if val == size: total += val else: opt = max(opt, val) if total + opt >= k: return True return False l, r = 0, max(a) while l < r: mid = (l + r + 1) // 2 if good(mid): l = mid else: r = mid - 1 print(l)
1456683000
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
1.5 seconds
["2", "1"]
931bf7141636a7222f9043c8ba94830f
NoteIn the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -&gt; 2 -&gt; 1 -&gt; 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor.In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor.
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.Find the minimal number of coprocessor calls which are necessary to execute the given program.
Output one line containing an integer β€” the minimal number of coprocessor calls necessary to execute the program.
The first line contains two space-separated integers N (1 ≀ N ≀ 105) β€” the total number of tasks given, and M (0 ≀ M ≀ 105) β€” the total number of dependencies between tasks. The next line contains N space-separated integers . If Ei = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor. The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T1 and T2 and means that task T1 depends on task T2 (T1 ≠ T2). Tasks are indexed from 0 to N - 1. All M pairs (T1, T2) are distinct. It is guaranteed that there are no circular dependencies between tasks.
standard output
standard input
Python 3
Python
1,900
train_025.jsonl
e78c659f3af6396f973f65d0a7e2a9a5
256 megabytes
["4 3\n0 1 0 1\n0 1\n1 2\n2 3", "4 3\n1 1 1 0\n0 1\n0 2\n3 0"]
PASSED
n, m = (int(x) for x in input().strip().split()) coproc = [int(x) for x in input().strip().split()] edges = [] for _ in range(m): edges.append((int(x) for x in input().strip().split())) inorder = [0] * n adj = [[] for _ in range(n)] for u, v in edges: adj[v].append(u) inorder[u] += 1 queue0 = [u for u in range(n) if inorder[u]==0 and not coproc[u]] queue1 = [u for u in range(n) if inorder[u]==0 and coproc[u]] res = 0 while len(queue0)>0 or len(queue1)>0: while queue0: next0 = [] for u in queue0: for v in adj[u]: inorder[v] -= 1 if inorder[v] == 0: if coproc[v]: queue1.append(v) else: next0.append(v) queue0 = next0 if queue1: res += 1 # coproc call while queue1: next1 = [] for u in queue1: for v in adj[u]: inorder[v] -= 1 if inorder[v] == 0: if coproc[v]: next1.append(v) else: queue0.append(v) queue1 = next1 print(res)
1514392500
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1.5 seconds
["4 6 8 1\n4 9 9 9\n4 10 10 65\n1 4 4 4\n1 1\n1 1"]
df6ee0d8bb25dc2040adf1f115f4a83b
null
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of squareΒ β€” a prime square. A square of size $$$n \times n$$$ is called prime if the following three conditions are held simultaneously: all numbers on the square are non-negative integers not exceeding $$$10^5$$$; there are no prime numbers in the square; sums of integers in each row and each column are prime numbers. Sasha has an integer $$$n$$$. He asks you to find any prime square of size $$$n \times n$$$. Sasha is absolutely sure such squares exist, so just help him!
For each test case print $$$n$$$ lines, each containing $$$n$$$ integersΒ β€” the prime square you built. If there are multiple answers, print any.
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10$$$)Β β€” the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the required size of a square.
standard output
standard input
PyPy 3
Python
900
train_008.jsonl
efe8594d7ba75ff3e580a1fb2d1f0840
256 megabytes
["2\n4\n2"]
PASSED
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools # import time,random,resource # sys.setrecursionlimit(10**6) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def pe(s): return print(str(s), file=sys.stderr) def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) def IF(c, t, f): return t if c else f def YES(c): return IF(c, "YES", "NO") def Yes(c): return IF(c, "Yes", "No") class Prime(): def __init__(self, n): self.M = m = int(math.sqrt(n)) + 10 self.A = a = [True] * m a[0] = a[1] = False self.T = t = [2] for j in range(4, m, 2): a[j] = False for i in range(3, m, 2): if not a[i]: continue t.append(i) for j in range(i*i,m,i): a[j] = False self.ds_memo = {} self.ds_memo[1] = set([1]) def is_prime(self, n): return self.A[n] def main(): t = I() pr = Prime(10**10) rr = [] for _ in range(t): n = I() ii = pp = None for i in range(1, 10**3): t = i * (n-1) for p in pr.T: if p > t and not pr.is_prime(p-t): pp = p - t ii = i break if pp: break a = [[ii] * n for _ in range(n)] for i in range(n): a[i][i] = pp rr.append(JAA(a, "\n", " ")) return JA(rr, "\n") print(main())
1603548300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["3\n0\n1\n0"]
6324ca46b6f072f8952d2619cb4f73e6
NoteTest cases of the example are described in the statement.
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
For each test case, print one integer β€” the maximum number of points a player can get for winning the game.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) β€” the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
standard output
standard input
PyPy 3
Python
1,000
train_003.jsonl
c7585a4155feb577420a0a70d512580c
256 megabytes
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
PASSED
for i in range(int(input())): n,m,k = [int(i) for i in input().split()] card = n//k if m<=card: print(m) elif card == 1: print(0) else: rem = (m-card)//(k-1) if (m-card)%(k-1) != 0: rem += 1 # print(rem,m,k) print(card-rem)
1590676500
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["YES\n9 5\n1 9", "NO", "YES"]
8a3803f1202c276bbae90552372af041
NoteConsider the first sample. Before the reform the Foolland consists of four regions. The first region includes cities 1, 2, 3, the second region has cities 4 and 6, the third region has cities 5, 7, 8, the fourth region has city 9. The total length of the roads in these cities is 11, 20, 5 and 0, correspondingly. According to the plan, we first build the road of length 6 between cities 5 and 9, then the road of length 23 between cities 1 and 9. Thus, the total length of the built roads equals 29.
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of n cities, some pairs of cities are connected by bidirectional roads, each road is described by its length li.The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly p new roads in the country. Constructing a road goes like this: We choose a pair of distinct cities u, v that will be connected by a new road (at that, it is possible that there already is a road between these cities). We define the length of the new road: if cities u, v belong to distinct regions, then the length is calculated as min(109, S + 1) (S β€” the total length of all roads that exist in the linked regions), otherwise we assume that the length equals 1000. We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of q regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.
If constructing the roads in the required way is impossible, print a single string "NO" (without the quotes). Otherwise, in the first line print word "YES" (without the quotes), and in the next p lines print the road construction plan. Each line of the plan must consist of two distinct integers, giving the numbers of the cities connected by a road. The road must occur in the plan in the order they need to be constructed. If there are multiple optimal solutions, you can print any of them.
The first line contains four integers n (1 ≀ n ≀ 105), m (0 ≀ m ≀ 105), p (0 ≀ p ≀ 105), q (1 ≀ q ≀ n) β€” the number of cities in the Foolland, the number of existing roads, the number of roads that are planned to construct and the required number of regions. Next m lines describe the roads that exist by the moment upgrading of the roads begun. Each of these lines contains three integers xi, yi, li: xi, yi β€” the numbers of the cities connected by this road (1 ≀ xi, yi ≀ n, xi ≠ yi), li β€” length of the road (1 ≀ li ≀ 109). Note that one pair of cities can be connected with multiple roads.
standard output
standard input
Python 2
Python
2,100
train_079.jsonl
1dbd8c48d096f99099745b28b0683296
256 megabytes
["9 6 2 2\n1 2 2\n3 2 1\n4 6 20\n1 3 8\n7 8 3\n5 7 2", "2 0 1 2", "2 0 0 2"]
PASSED
from sys import stdin, stdout, setrecursionlimit from heapq import heapify, heappop, heappush setrecursionlimit(100000) def main(): read_ints = lambda: map(int, stdin.readline().split()) n, m, p, q = read_ints() par = range(n) s = [0] * n def find(x): if x == par[x]: return x else: par[x] = find(par[x]) return par[x] def unite(x, y, l): x, y = find(x), find(y) s[x] += l if x == y: return par[y] = x s[x] += s[y] s[x] = min(s[x], 1000000000) lastpair = () for _ in xrange(m): x, y, l = read_ints() lastpair = (x, y) unite(x-1, y-1, l) if q == n and p: stdout.write("NO\n") return h = [(s[i], i) for i in xrange(n) if find(i) == i] c = len(h) - q if c < 0 or c > p: stdout.write("NO\n") return stdout.write("YES\n") heapify(h) ans = [] for _ in xrange(c): x, y = heappop(h), heappop(h) ans.append((x[1] + 1, y[1] + 1)) heappush(h, (min(x[0] + y[0] + x[0] + y[0] + 1, 1000000000), x[1])) if ans: lastpair = ans[-1] ans.extend([lastpair] * (p - c)) stdout.write('\n'.join(' '.join(map(str, x)) for x in ans)) main()
1384443000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["3\n4\n1"]
cf3cfcae029a6997ee62701eda959a60
NoteFirst test case: $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$. $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$. $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case: $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$. $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case: $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$.
Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?
For each test case, print one integer Β β€” the minimum number of operations to make all elements of the array $$$a$$$ equal.
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) Β β€” the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) Β β€” the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) Β β€” elements of the array $$$a$$$.
standard output
standard input
PyPy 3-64
Python
800
train_102.jsonl
85fd523ebb4027b18a35e104fb656f64
256 megabytes
["3\n6\n3 4 2 4 1 2\n3\n1000 1002 998\n2\n12 11"]
PASSED
import sys from os import path FILE = False # if needed change it while submitting if FILE: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def get_int(): return int(sys.stdin.readline()) def get_string(): return sys.stdin.readline().split(" ") n = get_int() final_result = [] for i in range(n): n = get_int() word = get_string() inputs = [int(x) for x in word] final_result.append(str(max(inputs)-min(inputs))) for item in final_result: sys.stdout.write(item) sys.stdout.write('\n')
1641825300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nNO\nYES\nYES"]
08783e3dff3f3b7eb586931f9d0cd457
null
You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries.
For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES".
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) β€” the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick.
standard output
standard input
PyPy 3
Python
1,200
train_007.jsonl
0cf907487fc2c9284698ec9566c943b0
256 megabytes
["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"]
PASSED
q = int(input()) while q > 0: q -= 1 n = int(input()) arr = list(map(int, input().split())) arr.sort() front = 0 end = len(arr) - 1 area = arr[front] * arr[end] possible = arr[front] == arr[front + 1] and arr[end] == arr[end - 1] front += 2 end -= 2 while possible and front < end: if arr[front] != arr[front + 1] or arr[end] != arr[end - 1] or (arr[front] * arr[end]) != area: possible = False front += 2 end -= 2 if possible: print("YES") else: print("NO")
1565706900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2 4", "-1", "5"]
1b975c5a13a2ad528b668a7c68c089f6
NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow): first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices; the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion; then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it; the vertex $$$4$$$ will be connected with the vertex $$$3$$$; then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex $$$4$$$; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices $$$2$$$ and $$$3$$$ have children that respect them; vertices $$$4$$$ and $$$5$$$ respect ancestors. In the third example the tree will change this way:
You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$. An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$. An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β€” the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.
standard output
standard input
Python 3
Python
1,400
train_014.jsonl
8de7006540ed447bd5102841567c1e65
256 megabytes
["5\n3 1\n1 1\n-1 0\n2 1\n3 0", "5\n-1 0\n1 1\n1 1\n2 0\n3 0", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0"]
PASSED
from heapq import * n = int(input()) pred = [[] for i in range(n + 1)] g = [[] for i in range(n + 1)] for i in range(1, n + 1): p, c = map(int, input().split()) pred[i] = [p, c] if p != -1: g[p].append([i, c]) heap = [] for i in range(1, n + 1): if pred[i][1] == 1: ok = True for x in g[i]: if x[1] == 0: ok = False break if ok: heappush(heap, i) res = [] while heap: v = heappop(heap) res.append(v) if not res: print(-1) else: print(' '.join(map(str, res)))
1553965800
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["fzfsirk", "xxxxxx", "ioi"]
bc3d0d902ef457560e444ec0128f0688
NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si &lt; ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j &lt; i)
The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.
The first line of input contains a string s of length n (1 ≀ n ≀ 3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.
standard output
standard input
Python 3
Python
1,800
train_027.jsonl
beafbd9cc504a3d4b02f60ea9511b432
256 megabytes
["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"]
PASSED
s1 = input() s2 = input() n = len(s1) s1 = sorted(s1) s2 = sorted(s2)[::-1] i = 0 j = 0 res = ["?"]*n rear = n-1 front = 0 Neven = n % 2 == 0 n1 = (n+1)//2 - 1 n2 = n//2 - 1 for k in range(n): if k % 2 == 0: if s1[i] < s2[j]: res[front] = s1[i] front += 1 i += 1 else: res[rear] = s1[n1] rear -= 1 n1 -= 1 else: if s1[i] < s2[j]: res[front] = s2[j] front += 1 j += 1 else: res[rear] = s2[n2] rear -= 1 n2 -= 1 print("".join(res))
1494668100
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["Yes", "No"]
82ff8ae62e39b8e64f9a273b736bf59e
NoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings: $$$1, 2, 3, 4$$$, $$$1, 3, 2, 4$$$. The ordering $$$1, 2, 4, 3$$$ doesn't correspond to any valid BFS order.
The BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from $$$1$$$ to $$$n$$$. Initialize $$$q$$$ as a new queue containing only vertex $$$1$$$, mark the vertex $$$1$$$ as used. Extract a vertex $$$v$$$ from the head of the queue $$$q$$$. Print the index of vertex $$$v$$$. Iterate in arbitrary order through all such vertices $$$u$$$ that $$$u$$$ is a neighbor of $$$v$$$ and is not marked yet as used. Mark the vertex $$$u$$$ as used and insert it into the tail of the queue $$$q$$$. If the queue is not empty, continue from step 2. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $$$1$$$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.
Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) which denotes the number of nodes in the tree. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$)Β β€” the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)Β β€” the sequence to check.
standard output
standard input
PyPy 3
Python
1,700
train_036.jsonl
006986bc020f21e59863137886e85a15
256 megabytes
["4\n1 2\n1 3\n2 4\n1 2 3 4", "4\n1 2\n1 3\n2 4\n1 2 4 3"]
PASSED
from collections import deque from sys import stdin input = stdin.readline class N: def __init__(self, v) -> None: self.c = [] self.v = v if __name__ == '__main__': n = int(input()) arr = [N(i + 1) for i in range(n)] for _ in range(n - 1): x, y = map(int, input().split()) x -= 1 y -= 1 arr[x].c.append(arr[y]) arr[y].c.append(arr[x]) narr = list(map(int, input().split())) q = deque() s = {1} v = set() v.add(1) good = True for x in narr: if x not in s: good = False break s.remove(x) ns = set() for c in arr[x - 1].c: if c.v not in v: v.add(c.v) ns.add(c.v) if ns: q.append(ns) if not s: if q: s = q.popleft() else: s = set() print('Yes' if good else 'No')
1535898900
[ "trees", "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 1 ]
2 seconds
["Yes\n0 2\n2 0", "Yes\n0 -1\n-1 0", "Yes\n0 1\n1 0", "No"]
6527406424b003cab6a1defdddb53525
null
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from to .With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k × k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
If Dima's type-distribution is correct, print string Β«YesΒ», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print Β«NoΒ».
The first line contains three integers n, m, k (1 ≀ n ≀ 105;Β 0 ≀ m ≀ 105;Β 1 ≀ k ≀ 500). The next line contains k integers c1, c2, ..., ck (1 ≀ ci ≀ n). Each of the next m lines contains three integers ui, vi, xi (1 ≀ ui, vi ≀ 105;Β 0 ≀ xi ≀ 104). It is guaranteed that .
standard output
standard input
PyPy 3
Python
2,000
train_064.jsonl
3ccce024c031eff1a6ace78e7fdd33ea
256 megabytes
["4 4 2\n1 3\n2 3 0\n3 4 0\n2 4 1\n2 1 2", "3 1 2\n2 1\n1 2 0", "3 2 2\n2 1\n1 2 0\n2 3 1", "3 0 2\n1 2"]
PASSED
#!/usr/bin/env python3 from sys import stdin from bisect import bisect_left, bisect_right INF = int(1e9) def find(par, a): if par[a] == a: return a par[a] = find(par, par[a]) return par[a] def union(par, rnk, a, b): a = find(par,a) b = find(par,b) if a==b: return if rnk[a]<rnk[b]: par[a] = b else: par[b] = a if rnk[a]==rnk[b]: rnk[a] += 1 def solve(): n, m, k = map(int, stdin.readline().split()) cnts = list(map(int, stdin.readline().split())) for i in range(1,k): cnts[i] += cnts[i-1] group = list(range(n)) rnk = [0 for i in range(n)] adj = [[INF for j in range(k)] for i in range(k)] for i in range(m): u, v, x = map(int, stdin.readline().split()) if x==0: union(group, rnk, u-1, v-1) tu = bisect_left(cnts, u) tv = bisect_left(cnts, v) adj[tu][tv] = min(adj[tu][tv], x) adj[tv][tu] = min(adj[tv][tu], x) p = 0 for i in range(k): cur = group[p] while p<cnts[i]: if group[p]!=cur: print("No") return p += 1 print("Yes") for p in range(k): for i in range(k): for j in range(k): adj[i][j] = min(adj[i][j], adj[i][p]+adj[p][j]) for i in range(k): adj[i][i] = 0 for j in range(k): if adj[i][j] == INF: adj[i][j] = -1 for i in range(k): print(' '.join(map(lambda x: str(x), adj[i]))) solve()
1394033400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["9"]
f9a691cdf7047ab82d2e2c903a53fc7e
null
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are n jars of honey lined up in front of Winnie-the-Pooh, jar number i contains ai kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that k kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly k kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.
Print a single number β€” how many kilos of honey gets Piglet.
The first line contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 100). The second line contains n integers a1, a2, ..., an, separated by spaces (1 ≀ ai ≀ 100).
output.txt
input.txt
Python 3
Python
1,100
train_060.jsonl
2f7865ae44a3f5c4fa43aed9efb9b637
256 megabytes
["3 3\n15 8 10"]
PASSED
import sys sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") x,y = map(int,input().split()) l = list(map(int,input().split())) for i in range(x): if l[i]//y>=3: l[i] = l[i] - y*3 else: l[i] = l[i] -y*(l[i]//y) print(sum(l))
1318919400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["YES\nYES\nYES\nYES\nNO\nYES\nYES\nYES"]
7e23e222ce40547ed8a4f7f1372082d9
null
You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways: set (assign) $$$a := |a - b|$$$; set (assign) $$$b := |a - b|$$$, where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.
For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).
standard output
standard input
PyPy 3-64
Python
1,600
train_098.jsonl
e80e36cb80590832936472243f0f39fc
512 megabytes
["8\n6 9 3\n15 38 7\n18 8 8\n30 30 30\n40 50 90\n24 28 20\n365 216 52\n537037812705867558 338887693834423551 3199921013340"]
PASSED
# def naiveGetPossible(a, b): # st = [(a, b)] # possible = set() # possible.add((a, b)) # while st: # a, b = st.pop() # diff = abs(a - b) # if (diff, b) not in possible: # possible.add((diff, b)) # st.append((diff, b)) # if (a, diff) not in possible: # possible.add((a, diff)) # st.append((a, diff)) # possible2 = set() # for a, b in possible: # possible2.add(a); possible2.add(b) # return possible, sorted(possible2) def main(): t = int(input()) allans = [] for _ in range(t): a, b, x = readIntArr() if b > a: temp = b; b = a; a = temp # a >= b while True: # Similar to Euclidean algorithm if x > a: allans.append('NO'); break if b <= x <= a: diff = a - x if x == b or diff % b == 0: # x is b or x is a - some multiple of b allans.append('YES') else: allans.append('NO') break diff = a - b mul = diff // b + 1 temp = a - b * mul a = b b = temp if b == 0: allans.append('NO') break multiLineArrayPrint(allans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(i,j,k): print('! {} {} {}'.format(i,j,k)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil import math # from math import floor,ceil # for Python2 for _abc in range(1): main()
1637573700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["4", "-1", "-1", "24"]
35b9acbe61226923a0c45452f23166c8
NoteIn the first example we can shift upper sunbed to the left and lower sunbedΒ β€” to the right. Andrew will be able to put his sunbed vertically in the middle of the beach. We well cause $$$2 + 2 = 4$$$ units of discomfort. It is easy to prove that it is an optimal answer. Optimal strategy in the first example (Andrew's sunbed is colored white). In the second example it is impossible to free a space for Andrew's sunbed. All possible states of the beach after any rotates and shifts are illustrated in the problem statement.
Andrew loves the sea. That's why, at the height of the summer season, he decided to go to the beach, taking a sunbed with him to sunbathe.The beach is a rectangular field with $$$n$$$ rows and $$$m$$$ columns. Some cells of the beach are free, some have roads, stones, shops and other non-movable objects. Some of two adjacent along the side cells can have sunbeds located either horizontally or vertically.Andrew hopes to put his sunbed somewhere, but that's a bad luck, there may no longer be free places for him! That's why Andrew asked you to help him to find a free place for his sunbed. Andrew's sunbed also should be places on two adjacent cells. If there are no two adjacent free cells, then in order to free some place for a sunbed, you will have to disturb other tourists. You can do the following actions: Come to some sunbed and, after causing $$$p$$$ units of discomfort to its owner, lift the sunbed by one of its sides and rotate it by $$$90$$$ degrees. One half of the sunbed must remain in the same cell and another half of the sunbed must move to the free cell. At the same time, anything could be on the way of a sunbed during the rotation . Rotation of the sunbed by $$$90$$$ degrees around cell $$$(1, 2)$$$. Come to some sunbed and, after causing $$$q$$$ units of discomfort to its owner, shift the sunbed along its long side by one cell. One half of the sunbed must move to the place of another, and anotherΒ β€” to the free cell. Shift of the sunbed by one cell to the right. In any moment each sunbed occupies two adjacent free cells. You cannot move more than one sunbed at a time.Help Andrew to free a space for his sunbed, causing the minimum possible number of units of discomfort to other tourists, or detect that it is impossible.
Print one integerΒ β€” the minimum possible number of units of discomfort, caused to other tourists, to free a space for a sunbed. If it is impossible to free a space for a sunbed, print $$$-1$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 300\,000$$$, $$$1 \le n \cdot m \le 300\,000$$$)Β β€” the number of rows and columns in rectangle. The second line contains two integers $$$p$$$ and $$$q$$$ ($$$1 \le p, q \le 10^9$$$)Β β€” the number of units of discomfort caused by rotation and shift of a sunbed, respectively. Each of the following $$$n$$$ lines contains $$$m$$$ characters, describing cells of the rectangle. Each lines consists of characters "L", "R", "D", "U", "." and "#", denoting the type of the cell. Characters "L", "R", "D" and "U" denote a half of a sunbed placed in the cellΒ β€” left, right, bottom and top half, respectively. Character "." denotes a free cell and character "#"Β β€” a cell, occupied by some non-movable object.
standard output
standard input
PyPy 3-64
Python
2,400
train_100.jsonl
4ac5d49ada70d5e80a4e6a60eb15c0aa
256 megabytes
["2 5\n\n5 2\n\n.LR##\n\n##LR.", "2 3\n\n4 5\n\nLR.\n\n#.#", "4 3\n\n10 10\n\n.LR\n\n###\n\nUU#\n\nDD.", "3 6\n\n10 7\n\n.U##.#\n\n#DLR##\n\n.##LR."]
PASSED
import heapq import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u * m + v def dijkstra(): dist = [inf] * l visit = [0] * l h = [] for i in range(n): si = s[i] for j in range(m): if si[j] == 46: u = f(i, j) dist[u] = 0 heapq.heappush(h, (dist[u], u)) while h: d, u = heapq.heappop(h) if dist[u] < d: continue visit[u] = 1 for v in G[u]: c = q if u // m == v // m or not (u - v) % m else p nd = dist[u] + c if not visit[v] and nd < dist[v]: dist[v] = nd heapq.heappush(h, (dist[v], v)) return dist n, m = map(int, input().split()) p, q = map(int, input().split()) s = [list(input().rstrip()) for _ in range(n)] l = n * m G = [[] for _ in range(l)] v = [(1, 0), (-1, 0), (0, 1), (0, -1)] for i in range(n): si = s[i] for j in range(m): if si[j] == 76: x, y = f(i, j), f(i, j + 1) for k in range(2): for di, dj in v: ni, nj = i + di, j + k + dj if not 0 <= ni < n or not 0 <= nj < m: continue z = f(ni, nj) if x == z or y == z or s[ni][nj] == 35: continue if not k: G[z].append(y) else: G[z].append(x) elif si[j] == 85: x, y = f(i, j), f(i + 1, j) for k in range(2): for di, dj in v: ni, nj = i + k + di, j + dj if not 0 <= ni < n or not 0 <= nj < m: continue z = f(ni, nj) if x == z or y == z or s[ni][nj] == 35: continue if not k: G[z].append(y) else: G[z].append(x) inf = pow(10, 15) + 1 dist = dijkstra() ans = inf for i in range(n): for j in range(m - 1): ans = min(ans, dist[f(i, j)] + dist[f(i, j + 1)]) for i in range(n - 1): for j in range(m): ans = min(ans, dist[f(i, j)] + dist[f(i + 1, j)]) ans = (ans + 1) % (inf + 1) - 1 print(ans)
1666511400
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["1\n0\n0\n0\n9"]
e094a3451b8b28be90cf54a4400cb916
null
You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if $$$n=6$$$ and the level is described by the string "**.*..", then the following game scenario is possible: the sheep at the $$$4$$$ position moves to the right, the state of the level: "**..*."; the sheep at the $$$2$$$ position moves to the right, the state of the level: "*.*.*."; the sheep at the $$$1$$$ position moves to the right, the state of the level: ".**.*."; the sheep at the $$$3$$$ position moves to the right, the state of the level: ".*.**."; the sheep at the $$$2$$$ position moves to the right, the state of the level: "..***."; the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.
For each test case output the minimum number of moves you need to make to complete the level.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep)Β β€” the description of the level. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.
standard output
standard input
Python 3
Python
1,400
train_083.jsonl
d13b3dfc8cb4966afece76d6536b266e
256 megabytes
["5\n6\n**.*..\n5\n*****\n3\n.*.\n3\n...\n10\n*.*...*.**"]
PASSED
def get_shifts(sheep_row): sheep_count = 0 last_sheep_position = None shifts = [] for idx in range(len(sheep_row)-1, -1, -1): if sheep_row[idx] == '*': if sheep_count > 0: diff = last_sheep_position - idx - 1 shift = diff * sheep_count + shifts[-1] shifts.append(shift) else: shifts.append(0) sheep_count += 1 last_sheep_position = idx return list(reversed(shifts)) def sort_sheeps_min(sheep_row): result = float('inf') min_operations = 0 shifts = get_shifts(sheep_row) sheep_count = 0 last_sheep_position = -1 for idx, item in enumerate(sheep_row): if item == '*': if sheep_count > 0: diff = idx - last_sheep_position - 1 left_shift = diff * sheep_count + min_operations result = min(result, left_shift + shifts[sheep_count]) min_operations = left_shift last_sheep_position = idx sheep_count += 1 return result if result != float('inf') else 0 if __name__ == '__main__': results = [] for idx in range(int(input())): _ = input() results.append(str(sort_sheeps_min(input()))) print("\n".join(results))
1620225300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 8", "1 1", "23 128"]
7eb2089c972cdf668a33a53e239da440
NoteIn the first sample case, there are 23 = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly , so A = 1, B = 8.In the second sample case, there are only 21 = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and A = B = 1.
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.In Udayland, there are 2n days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2n days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction . He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him?
If the probability of at least two k people having the same birthday in 2n days long year equals (A β‰₯ 0, B β‰₯ 1, ), print the A and B in a single line. Since these numbers may be too large, print them modulo 106 + 3. Note that A and B must be coprime before their remainders modulo 106 + 3 are taken.
The first and only line of the input contains two integers n and k (1 ≀ n ≀ 1018, 2 ≀ k ≀ 1018), meaning that there are 2n days in a year and that ZS the Coder wants to interview exactly k people.
standard output
standard input
Python 3
Python
2,300
train_046.jsonl
1809996785ac8380ebb6189fa9860e49
256 megabytes
["3 2", "1 3", "4 3"]
PASSED
import math n, k = [int(x) for x in input().split()] if n<70 and k>2**n: print(1,1) exit(0) mod = int(1e6)+3 def fastpow(a,b): t, ans = a, 1 while b: if(b&1): ans = ans*t%mod t = t*t %mod b>>=1 return ans t=k-1 cnt=0 while t: cnt += t>>1 t>>=1 x=0 t=fastpow(2,n) if k<mod: x=1 for i in range(1,k): x = x*(t-i)%mod y=fastpow(2,n*(k-1)) inv = fastpow(2,mod-2) inv = fastpow(inv,cnt) x=(x*inv%mod+mod)%mod y=(y*inv%mod+mod)%mod x=(y-x+mod)%mod print(x,y)
1472472300
[ "number theory", "math", "probabilities" ]
[ 0, 0, 0, 1, 1, 1, 0, 0 ]
2 seconds
["2", "3", "0"]
2bb43eb088051e08a678f7a97ef1eeff
NoteIn the first sample, it is possible to move to the right at maximum speed for the first $$$3.5$$$ seconds and stay at position $$$7$$$ until the first kick happens, and then immediately move right also at maximum speed to watch the second kick at position $$$17$$$. There is no way to monitor closely the third kick after the second kick, so at most $$$2$$$ kicks can be seen.
The derby between Milan and Inter is happening soon, and you have been chosen as the assistant referee for the match, also known as linesman. Your task is to move along the touch-line, namely the side of the field, always looking very carefully at the match to check for offside positions and other offences.Football is an extremely serious matter in Italy, and thus it is fundamental that you keep very close track of the ball for as much time as possible. This means that you want to maximise the number of kicks which you monitor closely. You are able to monitor closely a kick if, when it happens, you are in the position along the touch-line with minimum distance from the place where the kick happens.Fortunately, expert analysts have been able to accurately predict all the kicks which will occur during the game. That is, you have been given two lists of integers, $$$t_1, \ldots, t_n$$$ and $$$a_1, \ldots, a_n$$$, indicating that $$$t_i$$$ seconds after the beginning of the match the ball will be kicked and you can monitor closely such kick if you are at the position $$$a_i$$$ along the touch-line. At the beginning of the game you start at position $$$0$$$ and the maximum speed at which you can walk along the touch-line is $$$v$$$ units per second (i.e., you can change your position by at most $$$v$$$ each second). What is the maximum number of kicks that you can monitor closely?
Print the maximum number of kicks that you can monitor closely.
The first line contains two integers $$$n$$$ and $$$v$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le v \le 10^6$$$) β€” the number of kicks that will take place and your maximum speed. The second line contains $$$n$$$ integers $$$t_1, \ldots, t_n$$$ ($$$1 \le t_i \le 10^9$$$) β€” the times of the kicks in the match. The sequence of times is guaranteed to be strictly increasing, i.e., $$$t_1 &lt; t_2 &lt; \cdots &lt; t_n$$$. The third line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) β€” the positions along the touch-line where you have to be to monitor closely each kick.
standard output
standard input
PyPy 3-64
Python
-1
train_085.jsonl
6c14a0516ede60d51a73473c1a96ccc1
256 megabytes
["3 2\n5 10 15\n7 17 29", "5 1\n5 7 8 11 13\n3 3 -2 -2 4", "1 2\n3\n7"]
PASSED
from bisect import bisect_right,bisect_left n,v = map(int,input().split()) t = [*map(int,input().split())] a = [*map(int,input().split())] res = [] for i in range(n): xi,yi = t[i]*v+a[i],t[i]*v-a[i] if(xi>=0 and yi>=0): res.append((xi,yi)) res.sort() dp = [float("inf")]*(n+3) dp[0] = 0 dp[n+2] = 0 for i in range(len(res)): pos = bisect_right(dp,res[i][1],0,n+2) dp[pos] = res[i][1] for i in range(n,-1,-1): if(dp[i]!=float("inf")): print(i) break
1650798300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\n0\n2\n2\n1"]
fcd55a1ca29e96c05a3b65b7a8103842
NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.
You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way: Choose any positive odd integer $$$x$$$ ($$$x &gt; 0$$$) and replace $$$a$$$ with $$$a+x$$$; choose any positive even integer $$$y$$$ ($$$y &gt; 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.
For each test case, print the answer β€” the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
standard output
standard input
Python 3
Python
800
train_001.jsonl
b30489b19004696f28726ff02b504522
256 megabytes
["5\n2 3\n10 10\n2 4\n7 4\n9 3"]
PASSED
if __name__ == "__main__": n = int(input()) k = 0 s = [] for i in range(n): s.append(list(map(int,input().split()))) while k<n: count = 0 if s[k][0]==s[k][1]: pass elif s[k][0]>s[k][1]: diff = s[k][0]-s[k][1] count+=1 if diff % 2 != 0: count+=1 elif s[k][0]<s[k][1]: diff = s[k][1]-s[k][0] count+=1 if diff % 2 != 1: count+=1 print(count) count = 0 k+=1
1582554900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
5 seconds
["3 3", "9 7", "2000000000 1", "1393 3876"]
3317413b2c38fff76f7816c3554e9862
NoteThe first test case was explained in the statement.In the second test case $$$p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108]$$$.In the third test case $$$p = [1, 2, \ldots, 2000000000]$$$.
Igor had a sequence $$$d_1, d_2, \dots, d_n$$$ of integers. When Igor entered the classroom there was an integer $$$x$$$ written on the blackboard.Igor generated sequence $$$p$$$ using the following algorithm: initially, $$$p = [x]$$$; for each $$$1 \leq i \leq n$$$ he did the following operation $$$|d_i|$$$ times: if $$$d_i \geq 0$$$, then he looked at the last element of $$$p$$$ (let it be $$$y$$$) and appended $$$y + 1$$$ to the end of $$$p$$$; if $$$d_i &lt; 0$$$, then he looked at the last element of $$$p$$$ (let it be $$$y$$$) and appended $$$y - 1$$$ to the end of $$$p$$$. For example, if $$$x = 3$$$, and $$$d = [1, -1, 2]$$$, $$$p$$$ will be equal $$$[3, 4, 3, 4, 5]$$$.Igor decided to calculate the length of the longest increasing subsequence of $$$p$$$ and the number of them.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A sequence $$$a$$$ is an increasing sequence if each element of $$$a$$$ (except the first one) is strictly greater than the previous element.For $$$p = [3, 4, 3, 4, 5]$$$, the length of longest increasing subsequence is $$$3$$$ and there are $$$3$$$ of them: $$$[\underline{3}, \underline{4}, 3, 4, \underline{5}]$$$, $$$[\underline{3}, 4, 3, \underline{4}, \underline{5}]$$$, $$$[3, 4, \underline{3}, \underline{4}, \underline{5}]$$$.
Print two integers: the first integer should be equal to the length of the longest increasing subsequence of $$$p$$$; the second should be equal to the number of them modulo $$$998244353$$$. You should print only the second number modulo $$$998244353$$$.
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$)Β β€” the length of the sequence $$$d$$$. The second line contains a single integer $$$x$$$ ($$$-10^9 \leq x \leq 10^9$$$)Β β€” the integer on the blackboard. The third line contains $$$n$$$ integers $$$d_1, d_2, \ldots, d_n$$$ ($$$-10^9 \leq d_i \leq 10^9$$$).
standard output
standard input
PyPy 3
Python
3,000
train_100.jsonl
981b4dee6842c267e1d973d3bfa1535b
256 megabytes
["3\n3\n1 -1 2", "3\n100\n5 -3 6", "3\n1\n999999999 0 1000000000", "5\n34\n1337 -146 42 -69 228"]
PASSED
import sys, io, os if os.environ['USERNAME']=='kissz': inp=open('in55.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def debug(*args): pass def mexp(size,power): A=[] for i in range(size): A.append([int(j<=(i//2)*2) for j in range(size)]) powers={1: A} p=1 while p*2<=power: powers[p*2]=mmmult(powers[p],powers[p]) p*=2 A=powers[p] power-=p while power>0: p=p//2 if p<=power: A=mmmult(A,powers[p]) power-=p return A def mvmult(A,V): res=[] for i in range(len(A)): res.append(sum(a*v for a,v in zip(A[i],V)) % 998244353 ) return res def mmmult(A,B): res=[] for i in range(len(A)): res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))]) return res def get_rep(corners): corners[0]-=1 corners[-1]+=1 bps=sorted(list(set(corners))) m=len(bps) X=[1] active=[1] for i in range(1,m): x,y=bps[i-1],bps[i] d=y-x A=mexp(len(active),d) X=mvmult(A,X) #debug(active,X) #debug(A) if i<m-1: for j,c in enumerate(corners): if c==y: if j%2: # top: j and j+1 in active idx=active.index(j) X[idx+2]+=X[idx] active.pop(idx) active.pop(idx) X.pop(idx) X.pop(idx) else: # bottom active+=[j,j+1] active.sort() idx=active.index(j) X=X[:idx]+[0,X[idx-1]]+X[idx:] else: return X[0] n=int(inp()) inp() d,*D=map(int,inp().split()) if d==0 and all(dd==0 for dd in D): print(1,1) else: while d==0: d,*D=D up=(d>=0) corners=[0,d] for d in D: x=corners[-1]+d if up==(d>=0): corners[-1]=x if up!=(d>=0): up=(d>=0) corners.append(x) debug(corners) cands=[(-1,0,0)] low=(0,0) maxdiff=(0,0,0) for i,corner in enumerate(corners): if corner<low[0]: low=(corner,i) if corner-low[0]>=cands[0][0]: if corner-low[0]==cands[0][0] and low[1]>cands[0][1]: cands+=[(corner-low[0],low[1],i)] else: cands=[(corner-low[0],low[1],i)] L=cands[0][0]+1 if L>1: X=0 debug(cands) for _, starti, endi in cands: #debug(corners[starti:endi+1]) X+=get_rep(corners[starti:endi+1]) else: X=1-corners[-1] print(L,X % 998244353)
1611066900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
3 seconds
["8\n-1\n6\n0"]
f3c097872643f6fce645c05824b574e5
NoteIn the first test case, selecting indices $$$2$$$ and $$$3$$$ costs $$$8$$$, which is the minimum possible cost.In the second test case, we cannot make $$$a$$$ equal to $$$b$$$ using any number of operations.In the third test case, we can perform the following operations: Select indices $$$3$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0101011 now. Select indices $$$4$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0100001 now. The total cost is $$$6$$$.In the fourth test case, we don't have to perform any operations.
This is the easy version of the problem. In this version, $$$n \le 3000$$$, $$$x \ge y$$$ holds. You can make hacks only if both versions of the problem are solved.You are given two binary strings $$$a$$$ and $$$b$$$, both of length $$$n$$$. You can do the following operation any number of times (possibly zero). Select two indices $$$l$$$ and $$$r$$$ ($$$l &lt; r$$$). Change $$$a_l$$$ to $$$(1 - a_l)$$$, and $$$a_r$$$ to $$$(1 - a_r)$$$. If $$$l + 1 = r$$$, the cost of the operation is $$$x$$$. Otherwise, the cost is $$$y$$$. You have to find the minimum cost needed to make $$$a$$$ equal to $$$b$$$ or say there is no way to do so.
For each test case, if there is no way to make $$$a$$$ equal to $$$b$$$, print $$$-1$$$. Otherwise, print the minimum cost needed to make $$$a$$$ equal to $$$b$$$.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$)Β β€” the number of test cases. Each test case consists of three lines. The first line of each test case contains three integers $$$n$$$, $$$x$$$, and $$$y$$$ ($$$5 \le n \le 3000$$$, $$$1 \le y \le x \le 10^9$$$)Β β€” the length of the strings, and the costs per operation. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. The third line of each test case contains the string $$$b$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3000$$$.
standard output
standard input
PyPy 3-64
Python
1,400
train_104.jsonl
76fef8a51c5622b801e5f33b9e824dc3
512 megabytes
["4\n\n5 8 7\n\n01001\n\n00101\n\n5 7 2\n\n01000\n\n11011\n\n7 8 3\n\n0111001\n\n0100001\n\n5 10 1\n\n01100\n\n01100"]
PASSED
t=int(input()) while t>0: n,x,y=input().split(' ') a=input() b=input() n=int(n) x=int(x) y=int(y) indexes=[] for i in range(n): if a[i]!=b[i]: indexes.append(i) if len(indexes)==0: print(0) elif len(indexes)%2==1: print(-1) elif len(indexes)==2: if n==2 or n==3 and indexes[0]+1==indexes[1]: print(x) elif n==3: print(y) elif indexes[0]+1==indexes[1]: print(min(2*y,x)) else: print(min(y,x)) else: print(int(len(indexes)/2*y)) t-=1
1663598100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2\n3 3 2 1"]
01703877719e19dd8551e4599c3e1c85
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ β€” describing the array $$$b$$$. If there are multiple answers, you may print any.
Each test contains multiple test cases. The first line contains a single 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 a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) Β β€” the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$) Β β€” elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
2,000
train_108.jsonl
7dff26ed019f67ef30f11afa78e86cd6
256 megabytes
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
PASSED
import sys def solve(): inp = sys.stdin.readline n = int(inp()) a = list(map(int, inp().split())) c = [[] for i in range(n + 1)] p = [None] * (n + 1) for i in range(n): c[a[i]].append(i) for i in range(n + 1): p[i] = (-len(c[i]), i) p.sort() b = [None] * n for k in range(-p[0][0]): pr = p[0][1] for i in range(1, n + 5): sz, v = p[i] #print(k, pr, v, sz) if -sz > k: b[c[pr][k]] = v pr = v else: #print(c[pr]) b[c[pr][k]] = p[0][1] break print(' '.join(map(str, b))) def main(): for i in range(int(sys.stdin.readline())): solve() if __name__ == '__main__': main()
1650722700
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3.5 seconds
["0 0 0 2 4 \n0 91"]
a1effd6a0f6392f46f6aa487158fef7d
null
You are given two integers $$$a$$$ and $$$b$$$, and $$$q$$$ queries. The $$$i$$$-th query consists of two numbers $$$l_i$$$ and $$$r_i$$$, and the answer to it is the number of integers $$$x$$$ such that $$$l_i \le x \le r_i$$$, and $$$((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$$$. Calculate the answer for each query.Recall that $$$y \bmod z$$$ is the remainder of the division of $$$y$$$ by $$$z$$$. For example, $$$5 \bmod 3 = 2$$$, $$$7 \bmod 8 = 7$$$, $$$9 \bmod 4 = 1$$$, $$$9 \bmod 9 = 0$$$.
For each test case, print $$$q$$$ integersΒ β€” the answers to the queries of this test case in the order they appear.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$)Β β€” the number of test cases. Then the test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$q$$$ ($$$1 \le a, b \le 200$$$; $$$1 \le q \le 500$$$). Then $$$q$$$ lines follow, each containing two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^{18}$$$) for the corresponding query.
standard output
standard input
PyPy 3
Python
1,600
train_002.jsonl
e2ec8e8ce7c4e0e8f91c89e2b574231f
256 megabytes
["2\n4 6 5\n1 1\n1 3\n1 5\n1 7\n1 9\n7 10 2\n7 8\n100 200"]
PASSED
import math t = int(input()) def get(A,B,N): if(N==-1): return 0; if(max(A,B) > N): return N + 1 GCD = int(math.gcd(A,B)) X = GCD * (A//GCD) * (B//GCD) Delta = min(max(A,B), N - N//X*X + 1) return max(A,B) + max(N//X-1,0)*max(A,B) + (Delta * int(N>=X)) for _ in range(t): a,b,q = map(int,input().split()) for _ in range(q): l,r = map(int,input().split()) ans = abs(l-r) + 1 - (get(a,b,r) - get(a,b,l-1)) print(int(ans),end=' ') print()
1587911700
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["13\n1000000001000000000"]
ec8060260a6c7f4ff3e6afc9fd248afc
NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars.
There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!
Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \le s, a, b, c \le 10^9)$$$ β€” the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.
standard output
standard input
PyPy 3
Python
800
train_017.jsonl
3d3721be0db959d00108ab8da3a55101
256 megabytes
["2\n10 3 1 1\n1000000000 1 1000000000 1"]
PASSED
t = int(input()) for i in range(t): s, a, b, c = map(int, input().split()) e = s//c print((a + b) * (s // (c * a)) + e%a)
1539269400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["1 2 3", "1 3"]
e54f8aff8ede309bd591cb9fbd565d1f
null
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
The first line of input contains a single integer n (1 ≀ n ≀ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≀ si, ri ≀ 104).
standard output
standard input
PyPy 2
Python
2,600
train_001.jsonl
359fb4560b4295ccec3833b61cc4659d
256 megabytes
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
PASSED
from itertools import imap import sys n = input() def parseints(s, n): r, i, x = [0] * n, 0, 0 for c in imap(ord, s): if c == 32: r[i], i, x = x, i + 1, 0 else: x = x * 10 + c - 48 return r z = parseints(sys.stdin.read().replace('\n', ' '), n * 2) # p = zip(z[::2], z[1::2], range(1, n)) p = zip(z[::2], z[1::2]) def convex_hull(points): # points = list(set(points)) # points.sort(reverse=True) if len(points) <= 1: return points pindex = range(len(points)) pkey = [x * 10001 + y for x, y in points] pindex.sort(key=lambda i: pkey[i], reverse=True) def cross(o, a, b): ax, ay = a bx, by = b ox, oy = o return (oy * (ox * (ay * bx - ax * by) + ax * bx * (by - ay)) - ox * ay * by * (bx - ax)) # def cross(o, a, b): # return (o[1] * (o[0] * (a[1] * b[0] - a[0] * b[1]) + # a[0] * b[0] * (b[1] - a[1])) - # o[0] * a[1] * b[1] * (b[0] - a[0])) lower = [] for pi in pindex: p = points[pi] while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0: lower.pop() if not lower or lower[-1][1] < p[1]: lower.append(p) return lower pdic = {} for i, x in enumerate(p, 1): pdic.setdefault(x, []).append(i) ch = convex_hull(p) res = [] for x in ch: res.extend(pdic[x]) res.sort() print ' '.join(map(str, res))
1429029300
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1\nabacaba", "4\naaaa", "0\nab"]
d467f457a462c83a1a0a6320494da811
NoteIn the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.In the second sample there is only one way to compose a necklace.
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
In the first line print a single numberΒ β€” the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace. Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
The first line of the input contains a single number n (1 ≀ n ≀ 26) β€” the number of colors of beads. The second line contains after n positive integers ai Β  β€” the quantity of beads of i-th color. It is guaranteed that the sum of ai is at least 2 and does not exceed 100 000.
standard output
standard input
Python 3
Python
2,500
train_007.jsonl
068c5c9991a9f854fc8287d1065d79d9
256 megabytes
["3\n4 2 1", "1\n4", "2\n1 1"]
PASSED
import math #import fractions from functools import reduce n = int(input()) odd = -1 beads = [int(x) for x in input().split()] for i in range(n): if beads[i]%2: if odd >= 0: print(0) print(''.join(chr(ord('a') + i)*beads[i] for i in range(n))) break else: odd = i else: gcd = reduce(lambda x,y: math.gcd(x,y), beads) print(gcd) if odd >= 0: s = ''.join(chr(ord('a') + i)*(beads[i]//(2*gcd)) for i in range(n) if i != odd) p = s + chr(ord('a') + odd)*(beads[odd]//gcd) + s[::-1] print(p*gcd) else: s = ''.join(chr(ord('a') + i)*(beads[i]//gcd) for i in range(n)) p = s + s[::-1] print(p*(gcd//2))
1452789300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2 4", "2", "-1", "3", "-1"]
aa1ed95ea1a0b7b7de62673625f38132
null
Dima is a good person. In fact, he's great. But all good things come to an end...Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle n × m consisting of unit squares.For the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes k (k &gt; 1) unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice.Seryozha kicks Dima for a long time, but Dima is not vindictive β€” Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the k value, so he asks you to find all possible values which matches to the Dima's records.
In a single line in accending order print all k (k &gt; 1), which matches the Dima's notes. If there are no such k and Dima invented this story with kicks, print -1.
The first line contains n and m (1 ≀ n, m ≀ 103) β€” size of the room. Next n lines goes, each contains m numbers aij β€” Dima's notes: aij = 1, if Dima was staying in the square (i, j) or was flying above it. Otherwise aij = 0. At least one aij equals 1.
standard output
standard input
Python 2
Python
2,300
train_069.jsonl
9ade274969c0afaac2c9dd8806bc8d38
256 megabytes
["5 5\n1 1 1 1 1\n1 0 0 0 1\n1 0 0 0 1\n1 0 0 0 1\n1 1 1 1 1", "7 7\n0 0 1 1 1 0 0\n0 0 1 0 1 0 0\n1 1 1 1 1 1 1\n1 0 1 0 1 0 1\n1 1 1 1 1 1 1\n0 0 1 0 1 0 0\n0 0 1 1 1 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1", "4 4\n1 1 1 1\n0 0 0 0\n0 0 0 0\n0 0 0 0", "5 5\n0 0 1 0 0\n0 0 1 0 0\n1 1 1 1 1\n0 0 1 0 0\n0 0 1 0 0"]
PASSED
import sys sys.setrecursionlimit(10**6) def main(): n, m = map(int, raw_input().split()) a = [raw_input().split() for _ in xrange(n)] dd = [(1,0), (0,1)] od = 0 D = [[[] for _ in xrange(m)] for _ in xrange(n)] done = [[False] * m for _ in xrange(n)] par = range(n * m) rank = [0] * (n * m) def find(x): if x == par[x]: return x else: par[x] = find(par[x]) return par[x] def union(x, y): x, y = find(x), find(y) if x == y: return if rank[x] < rank[y]: par[y] = x else: par[x] = y if rank[x] == rank[y]: rank[x] += 1 for i in xrange(n): for j in xrange(m): if a[i][j] == '0': continue deg = 0 for d in dd: ni, nj = i + d[0], j + d[1] if 0 <= ni < n and 0 <= nj < m and a[ni][nj] == '1': deg += 1 D[i][j].append(d) union(i * m + j, ni * m + nj) ni, nj = i - d[0], j - d[1] if 0 <= ni < n and 0 <= nj < m and a[ni][nj] == '1': deg += 1 if deg % 2: od += 1 if od > 2: print -1 return deg = 0 S = set() for i in xrange(n): for j in xrange(m): if a[i][j] == '0': continue deg += 1 S.add(find(i * m + j)) if deg == 1 or len(S) != 1: print -1 return def gcd(x, y): if y == 0: return x else: return gcd(y, x%y) p = 0 for i in xrange(n): for j in xrange(m): if a[i][j] == '0' or done[i][j]: continue for d in D[i][j]: t = 1 while 1: ni, nj = i + t * d[0], j + t * d[1] if 0 <= ni < n and 0 <= nj < m and a[ni][nj] == '1' and [d] == D[ni][nj]: pass else: break done[ni][nj] = 1 t += 1 p = gcd(t, p) if p == 1: print -1 return for i in xrange(2, p+1): if p % i == 0: print i, main()
1382715000
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["4427477", "4478"]
8ce1ba0a98031c1bc28f53c11905391c
NoteIn the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477.In the second sample: 4478 → 4778 → 4478.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≀ x &lt; n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.
In the single line print the result without spaces β€” the number after the k operations are fulfilled.
The first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 109) β€” the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.
standard output
standard input
Python 3
Python
1,500
train_021.jsonl
f1e020a8afc8535f9b870a7df58949d8
256 megabytes
["7 4\n4727447", "4 2\n4478"]
PASSED
# 447 or 477 start with odd n, k = map(int, input().split()) s = input() s = list(s) for i in range(n - 1): if not k: break if s[i] != '4': continue tt = ''.join(s[i:i + 3]) if tt in ('447', '477') and i % 2 == 0: if k % 2 == 1 and tt == '447': s[i + 1] = '7' if k % 2 == 1 and tt == '477': s[i + 1] = '4' break if s[i] == '4' and s[i + 1] == '7': if i % 2 == 0: s[i + 1] = '4' else: s[i] = '7' k -= 1 print(''.join(s))
1319727600
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
1 second
["45", "-1"]
64625b26514984c4425c2813612115b3
NoteIn the first test, the optimal route is: Β Β Β Β  for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light. Β Β Β Β  for the second green light reaches $$$14$$$. Wait for the red light again. Β Β Β Β  for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules.
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$ Β β€” are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
Output a single integer Β β€” the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$.
The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$ Β β€” road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$ Β β€” the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$ Β β€” the time that the green light stays on and the time that the red light stays on.
standard output
standard input
PyPy 3
Python
2,400
train_000.jsonl
9f6be0f2190dd59bef5b14e895e712b1
256 megabytes
["15 5\n0 3 7 14 15\n11 11", "13 4\n0 3 7 13\n9 9"]
PASSED
import collections n,m=map(int,input().split()) m+=2 arr=list(map(int,input().split())) arr.append(0) arr.append(n) arr=sorted(arr) g,r=map(int,input().split()) q=collections.deque() q.append((0,0)) dist=[[0]*(g+1) for _ in range(m+2)] checked=[[0]*(g+1) for _ in range(m+2)] checked[0][0]=1 ans=-1 while len(q)!=0: v,t=q.popleft() if t==0: if n-arr[v]<=g: tmp=dist[v][t]*(g+r)+n-arr[v] if ans==-1 or ans>tmp: ans=tmp if t==g: if checked[v][0]==0: checked[v][0]=1 dist[v][0]=dist[v][t]+1 q.append((v,0)) continue if v!=0: cost=t+arr[v]-arr[v-1] if cost<=g and checked[v-1][cost]==0: checked[v-1][cost]=1 dist[v-1][cost]=dist[v][t] q.appendleft((v-1,cost)) if v!=m-1: cost=t+arr[v+1]-arr[v] if cost<=g and checked[v+1][cost]==0: checked[v+1][cost]=1 dist[v+1][cost]=dist[v][t] q.appendleft((v+1,cost)) print(ans)
1587653100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1.5 seconds
["1\n3\n3"]
107773724bd8a898f9be8fb3f9ee9ac9
NoteFor first test case, $$$1$$$ is the only number and therefore lonely.For second test case where $$$n=5$$$, numbers $$$1$$$, $$$3$$$ and $$$5$$$ are lonely.For third test case where $$$n=10$$$, numbers $$$1$$$, $$$5$$$ and $$$7$$$ are lonely.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.More precisely, two different numbers $$$a$$$ and $$$b$$$ are friends if $$$gcd(a,b)$$$, $$$\frac{a}{gcd(a,b)}$$$, $$$\frac{b}{gcd(a,b)}$$$ can form sides of a triangle.Three numbers $$$a$$$, $$$b$$$ and $$$c$$$ can form sides of a triangle if $$$a + b &gt; c$$$, $$$b + c &gt; a$$$ and $$$c + a &gt; b$$$.In a group of numbers, a number is lonely if it doesn't have any friends in that group.Given a group of numbers containing all numbers from $$$1, 2, 3, ..., n$$$, how many numbers in that group are lonely?
For each test case, print the answer on separate lines: number of lonely numbers in group $$$1, 2, 3, ..., n_i$$$.
The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^6)$$$ - number of test cases. On next line there are $$$t$$$ numbers, $$$n_i$$$ $$$(1 \leq n_i \leq 10^6)$$$ - meaning that in case $$$i$$$ you should solve for numbers $$$1, 2, 3, ..., n_i$$$.
standard output
standard input
PyPy 2
Python
1,600
train_007.jsonl
c1129e2b38ea6d6b71930c4bc4dc5f66
256 megabytes
["3\n1 5 10"]
PASSED
from sys import stdin def count_prime(n): for i in range(2, n): if prim[i] == 1: if i * i < Max: prim[i * i] = -1 for j in range(i * i + i, n, i): prim[j] = 0 for i in range(2, n): prim[i] += prim[i - 1] n, a, Max = int(input()), [int(x) for x in stdin.readline().split()], 1000001 prim = [1] * Max count_prime(Max) print('\n'.join(map(str, [prim[i] for i in a])))
1601903100
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["4\n55\n15000000000000000\n51"]
d9e4a9a32d60e75f3cf959ef7f894fc6
null
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to BobΒ β€” then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candyΒ β€” and after that, she has $$$55$$$ candies too.
Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th queryΒ β€” the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$)Β β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^{16}$$$)Β β€” the number of candies in the first, second and third piles correspondingly.
standard output
standard input
Python 3
Python
800
train_003.jsonl
4610db81e9d80e78b37c63d70ae6a31a
256 megabytes
["4\n1 3 4\n1 10 100\n10000000000000000 10000000000000000 10000000000000000\n23 34 45"]
PASSED
import math q_count = int(input()) for i in range(q_count): nums = input().split(' ') piles_fair = sum(map(lambda x: int(x), nums))//2 print(piles_fair)
1563978900
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["2\n10\n3"]
9a2e734bd78ef1e50140f2bb4f57d611
Note Graph from the first test case. Ority of this tree equals to 2 or 2 = 2 and it's minimal. Without excluding edge with weight $$$1$$$ ority is 1 or 2 = 3.
Recently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of $$$n$$$ vertices and $$$m$$$ edges for his birthday.Vlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum possible ority that can be achieved by choosing a certain spanning tree. A spanning tree is a connected subgraph of a given graph that does not contain cycles.In other words, you want to keep $$$n-1$$$ edges so that the graph remains connected and the bitwise OR weights of the edges are as small as possible. You have to find the minimum bitwise OR itself.
Print $$$t$$$ lines, each of which contains the answer to the corresponding set of input dataΒ β€” the minimum possible spanning tree ority.
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. An empty line is written in front of each test case. This is followed by two numbers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) β€” the number of vertices and edges of the graph, respectively. The next $$$m$$$ lines contain the description of the edges. Line $$$i$$$ contains three numbers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$1 \le w_i \le 10^9$$$, $$$v_i \neq u_i$$$) β€” the vertices that the edge connects and its weight. It is guaranteed that the sum $$$m$$$ and the sum $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ and each test case contains a connected graph.
standard output
standard input
PyPy 3-64
Python
1,900
train_102.jsonl
ca247fd48319c4d12f7df489f8db1c1c
256 megabytes
["3\n\n\n\n\n3 3\n\n1 2 1\n\n2 3 2\n\n1 3 2\n\n\n\n\n5 7\n\n4 2 7\n\n2 5 8\n\n3 4 2\n\n3 2 1\n\n2 4 2\n\n4 1 2\n\n1 2 2\n\n\n\n\n3 4\n\n1 2 1\n\n2 3 2\n\n1 3 3\n\n3 1 4"]
PASSED
import sys ip=sys.stdin.readline class Graph: def __init__(self,n,m,edge,tot): self.n=n self.m=m self.edge=edge self.tot=tot self.par=[-1 for _ in range(n+1)] def findParent(self,x,c1): if self.par[x]==-1:return x,c1 else:return self.findParent(self.par[x],c1+1) def union(self,x,y): par1,c1=self.findParent(x,0) par2,c2=self.findParent(y,0) if par1==par2:return else: if c1>=c2:self.par[par2]=par1 else:self.par[par1]=par2 return def isPossible(self): for u,v,w in self.edge: if self.tot|w==self.tot: self.union(u,v) c=0 for i in range(1,self.n+1): if self.par[i]==-1:c+=1 if c>1:return False else:return True for _ in range(int(ip())): _=ip() n,m=map(int,ip().split()) edges=[tuple(map(int,ip().split())) for _ in range(m)] tot=(1<<31)-1 for i in range(30,-1,-1): tot-=(1<<i) g=Graph(n,m,edges,tot) pr=g.isPossible() if pr:continue else:tot+=(1<<i) print(tot)
1641825300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["640"]
29639971c98dd98f0292d994d4433e3a
NoteNote to the sample:The total length of the walls (the perimeter) of the room is 20 m.One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.
Print a single number β€” the minimum total cost of the rolls.
The first line contains a positive integer n (1 ≀ n ≀ 500) β€” the number of rooms in Boris's apartment. Each of the next n lines contains three space-separated positive integers β€” the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer m (1 ≀ m ≀ 500) β€” the number of available wallpaper types. Each of the following m lines contains three space-separated positive integers β€” the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.
standard output
standard input
Python 3
Python
1,600
train_004.jsonl
680319ec3ed223a0d91df4f31d879193
256 megabytes
["1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500"]
PASSED
n = int(input()) rooms = [[int(i) for i in input().split()] for i in range(n)] m = int(input()) papers = [[int(i) for i in input().split()] for i in range(m)] ans = 0 for room in rooms: per = (room[0]+room[1])*2 prices = [] for cur in papers: power = cur[0]//room[2]*cur[1] if(power == 0): continue prices.append((per+power-1)//power*cur[2]) ans += min(prices) print(ans)
1324728000
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
1 second
["Yes", "No"]
e72fa6f8a31c34fd3ca0ce3a3873ff50
NoteIn the first sample, Arya can understand because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.
Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value for any positive integer x?Note, that means the remainder of x after dividing it by y.
Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.
The first line of the input contains two integers n and k (1 ≀ n,  k ≀ 1 000 000)Β β€” the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 1 000 000).
standard output
standard input
Python 3
Python
1,800
train_000.jsonl
5052386e91fc1fe0d05d0df22ed00077
256 megabytes
["4 5\n2 3 5 12", "2 7\n2 3"]
PASSED
import math def main(): n,k = map(int,input().split()) C = list(map(int,input().split())) l=C[0] for c in C: l = l*c//math.gcd(l,c)%k if(l==0): print("Yes") return print("No") main()
1467219900
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["YES\n1 2 4 5 6 8", "NO", "YES\n1", "NO"]
df801ebbe05c17bb1d157108d523d1f8
null
Polycarp has to solve exactly $$$n$$$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $$$k$$$ days. It means that Polycarp has exactly $$$k$$$ days for training!Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $$$k$$$ days. He also doesn't want to overwork, so if he solves $$$x$$$ problems during some day, he should solve no more than $$$2x$$$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $$$x$$$ problems during some day, he should solve at least $$$x+1$$$ problem during the next day.More formally: let $$$[a_1, a_2, \dots, a_k]$$$ be the array of numbers of problems solved by Polycarp. The $$$i$$$-th element of this array is the number of problems Polycarp solves during the $$$i$$$-th day of his training. Then the following conditions must be satisfied: sum of all $$$a_i$$$ for $$$i$$$ from $$$1$$$ to $$$k$$$ should be $$$n$$$; $$$a_i$$$ should be greater than zero for each $$$i$$$ from $$$1$$$ to $$$k$$$; the condition $$$a_i &lt; a_{i + 1} \le 2 a_i$$$ should be satisfied for each $$$i$$$ from $$$1$$$ to $$$k-1$$$. Your problem is to find any array $$$a$$$ of length $$$k$$$ satisfying the conditions above or say that it is impossible to do it.
If it is impossible to find any array $$$a$$$ of length $$$k$$$ satisfying Polycarp's rules of training, print "NO" in the first line. Otherwise print "YES" in the first line, then print $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ in the second line, where $$$a_i$$$ should be the number of problems Polycarp should solve during the $$$i$$$-th day. If there are multiple answers, you can print any.
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9, 1 \le k \le 10^5$$$) β€” the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.
standard output
standard input
Python 3
Python
1,900
train_036.jsonl
5490ac684ee3f588bd65d8a1899f995e
256 megabytes
["26 6", "8 3", "1 1", "9 4"]
PASSED
n, k = [int(x) for x in input().split()] a = [i for i in range(1, k+1)] s = (k*(k+1))//2 p = 0 if n == s: p = 0 elif n > s: if n - s == k: p = 0 for i in range(k): a[i] += 1 elif n - s > k: d = (n - s) // k for i in range(k): a[i] += d p = (n-s) - (d*k) for i in range(k-2, -1, -1): c = (2 * a[i]) - a[i+1] if p <= 0: break elif p >= c: a[i+1] += c p -= c elif p < c: a[i+1] += p p = 0 elif n - s < k: p = n - s for i in range(k-2, -1, -1): c = (2 * a[i]) - a[i + 1] if p <= 0: break elif p >= c: a[i+1] += c p -= c elif p < c: a[i+1] += p p = 0 else: p = 1 if p <= 0: print('YES') for i in range(k): print(a[i], end=' ') else: print('NO')
1556289300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
0.5 seconds
["50", "110", "0"]
9b1b082319d045cf0ec6d124f97a8184
NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful.
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
Print a single number without leading zeroesΒ β€” the product of the number of tanks presented by each country.
The first line of the input contains the number of countries n (1 ≀ n ≀ 100 000). The second line contains n non-negative integers ai without leading zeroesΒ β€” the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.
standard output
standard input
PyPy 3
Python
1,400
train_005.jsonl
31da23fc0f4086926cd12c10c0062e82
256 megabytes
["3\n5 10 1", "4\n1 1 10 11", "5\n0 3 1 100 1"]
PASSED
def check(string): if len(string) == 1: return string[0] != '1' if string[0] != '1': return True if any(s != '0' for s in string[1:]): return True return False if __name__ == "__main__": n = int(input()) if n == 1: print(input()) exit(0) tanks = [str(x) for x in input().split(' ')] for x in tanks: if x == '0': print(0) exit(0) not_b = '1' for i in range(n): if check(tanks[i]): not_b = tanks[i] tanks[i] = '_' break result = [not_b] for i, x in enumerate(tanks): if x != '_': result.append('0' * (len(x) - 1)) print(''.join(result))
1452789300
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"]
da517ae908ba466da8ded87cec12a9fa
NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≀ l ≀ r ≀ n), such that the following conditions hold: there is integer j (l ≀ j ≀ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.
Print two integers in the first line β€” the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.
The first line contains integer n (1 ≀ n ≀ 3Β·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 106).
standard output
standard input
Python 3
Python
2,000
train_071.jsonl
5d33e4b2afcf37b9bfe8edd258861d19
256 megabytes
["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"]
PASSED
n = int(input()) + 1 t = [1] + list(map(int, input().split())) + [1] p = [True] * n s, q = 0, list(range(1, n)) for i in range(1, n): if p[i]: a = b = i d = t[i] if d == 1: s, q = n - 2, [1] break while t[a - 1] % d == 0: a -= 1 while t[b + 1] % d == 0: b += 1 p[b] = False d = b - a if d > s: s, q = d, [a] elif d == s != 0: q.append(a) print(len(q), s) print(' '.join(map(str, q)))
1383379200
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162"]
a65e12186430f74c18c50d2eb55a9794
NoteLet's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.
Output the initial array, which was used to produce text, one integer per line.
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
standard output
standard input
Python 2
Python
1,300
train_003.jsonl
e6ec86b3c31b72be25dc4d620cea4f2a
256 megabytes
["Hello, World!"]
PASSED
s = raw_input() pre = 0 for i in s: nxt = format(ord(i), "b")[::-1] while (len(nxt) < 8): nxt += "0" print (pre - int(nxt, 2)) % 256 pre = int(nxt, 2)
1322924400
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]
2 seconds
["7", "36"]
8aaabe089d2512b76e5de938bac5c3bf
NoteIn the first sample one of the optimum behavior of the players looks like that: Vova bans the position at coordinate 15; Lesha bans the position at coordinate 3; Vova bans the position at coordinate 31; Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.In the second sample there are only two possible positions, so there will be no bans.
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.
Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.
The first line on the input contains a single integer n (2 ≀ n ≀ 200 000, n is even)Β β€” the number of positions available initially. The second line contains n distinct integers x1, x2, ..., xn (0 ≀ xi ≀ 109), giving the coordinates of the corresponding positions.
standard output
standard input
Python 3
Python
2,300
train_037.jsonl
4e9e29bd088f05333e926af671963b9c
256 megabytes
["6\n0 1 3 7 15 31", "2\n73 37"]
PASSED
n = int(input()) x = sorted(list(map(int, input().split()))) print(min([x[i + n // 2] - x[i] for i in range(n // 2)]))
1447000200
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
2 seconds
["4 4 1 4 4 2 2"]
a7e75ff150d300b2a8494dca076a3075
null
In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it.
Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) β€” the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \le k_i \le n$$$) β€” the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$$$.
standard output
standard input
Python 3
Python
1,400
train_005.jsonl
85547c63cb47b60b13670848592de960
256 megabytes
["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"]
PASSED
import sys,bisect from sys import stdin,stdout from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right from math import gcd,ceil,floor,sqrt from collections import Counter,defaultdict,deque,OrderedDict from queue import Queue,PriorityQueue from string import ascii_lowercase from heapq import * from itertools import islice sys.setrecursionlimit(10**6) INF = float('inf') MOD = 998244353 mod = 10**9+7 def st(): return list(stdin.readline().strip()) def inp(): return int(stdin.readline()) def li(): return list(map(int,stdin.readline().split())) def mp(): return map(int,stdin.readline().split()) def solve(): n,m=mp() d={i:[] for i in range(1,n+1)} for _ in range(m): l=li() x=l[0] if x>1: for i in range(1,x): d[l[i]].append(l[i+1]) d[l[i+1]].append(l[i]) ans=[-1 for i in range(n+1)] vi=[-1 for i in range(n+1)] for i in range(1,n+1): if vi[i]==-1: vi[i]=i stack=[i] ans[i]=1 while stack: a=stack.pop() for x in d[a]: if vi[x]==-1: ans[i]+=1 vi[x]=i stack.append(x) print(' '.join((str(ans[vi[i]]) for i in range(1,n+1)))) for _ in range(1): solve() ## print("Case #{}:".format(_+1),c) ##
1557930900
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
3 seconds
["2", "0"]
0600b8401c8e09978661bc02691bda5d
NoteIn the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree and apply operation paint(3) to get the following: Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
Print one integerΒ β€” the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
The first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of vertices in the tree. The second line contains n integers colori (0 ≀ colori ≀ 1)Β β€” colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black. Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
standard output
standard input
Python 3
Python
2,100
train_018.jsonl
0bc4c6ecffb09e694d0b261021ad1d04
256 megabytes
["11\n0 0 0 1 1 0 1 0 0 1 1\n1 2\n1 3\n2 4\n2 5\n5 6\n5 7\n3 8\n3 9\n3 10\n9 11", "4\n0 0 0 0\n1 2\n2 3\n3 4"]
PASSED
from collections import defaultdict, deque class DSU: def __init__(self, n): self.parents = [i for i in range(n)] self.ranks = [0 for i in range(n)] def find_parent(self, v): if self.parents[v] == v: return v self.parents[v] = self.find_parent(self.parents[v]) return self.parents[v] def join_sets(self, u, v): u = self.find_parent(u) v = self.find_parent(v) if u != v: if self.ranks[u] < self.ranks[v]: u, v = v, u self.parents[v] = u if self.ranks[v] == self.ranks[u]: self.ranks[u] += 1 n = int(input()) dsu = DSU(n) colors = list(map(int, input().split(' '))) vertices = [] for i in range(n-1): u, v = map(lambda x: int(x)-1, input().split(' ')) if colors[u] == colors[v]: dsu.join_sets(u, v) vertices.append((u,v)) graph = defaultdict(list) for u, v in vertices: if colors[u] != colors[v]: u = dsu.find_parent(u) v = dsu.find_parent(v) graph[u].append(v) graph[v].append(u) def bfs(u): d = dict() d[u] = 0 q = deque() q.append(u) while q: u = q.pop() for v in graph[u]: if v not in d: d[v] = d[u] + 1 q.append(v) return d if graph: v = list(graph.keys())[0] d = bfs(v) u = v for i in d: if d[i] > d[u]: u = i d = bfs(u) w = u for i in d: if d[i] > d[w]: w = i print((d[w]+1)//2) else: print(0)
1479227700
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
4 seconds
["YES\n2 1 3", "NO"]
ff5b3d5fa52c2505556454011e8a0f58
null
Several years ago Tolya had n computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to k. The names didn't overlap.Thus, there is a cyclic string of length nΒ·k written on the CD.Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were g popular games that days. All of the games he burned were among these g games, and no game was burned more than once.You have to restore any valid list of games Tolya could burn to the CD several years ago.
If there is no answer, print "NO" (without quotes). Otherwise, print two lines. In the first line print "YES" (without quotes). In the second line, print n integersΒ β€” the games which names were written on the CD. You should print games in the order they could have been written on the CD, it means, in clockwise order. You can print games starting from any position. Remember, that no game was burned to the CD more than once. If there are several possible answers, print any of them.
The first line of the input contains two positive integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 105)Β β€” the amount of games Tolya burned to the CD, and the length of each of the names. The second line of the input contains one string consisting of lowercase English lettersΒ β€” the string Tolya wrote on the CD, split in arbitrary place. The length of the string is nΒ·k. It is guaranteed that the length is not greater than 106. The third line of the input contains one positive integer g (n ≀ g ≀ 105)Β β€” the amount of popular games that could be written on the CD. It is guaranteed that the total length of names of all popular games is not greater than 2Β·106. Each of the next g lines contains a single stringΒ β€” the name of some popular game. Each name consists of lowercase English letters and has length k. It is guaranteed that the names are distinct.
standard output
standard input
PyPy 2
Python
2,300
train_004.jsonl
c0e45f7091360a9c77189ba8551070c8
512 megabytes
["3 1\nabc\n4\nb\na\nc\nd", "4 2\naabbccdd\n4\ndd\nab\nbc\ncd"]
PASSED
n, k = map(int, raw_input().split()) s = raw_input() g = int(raw_input()) games = [raw_input() for i in range(g)] MOD_1 = 1000000007 BASE_1 = 31 MOD_2 = 1000000409 BASE_2 = 29 hashes_1 = [] hashes_2 = [] hash_inv = {} game_inv = {} for i, game in enumerate(games): h_1 = 0 h_2 = 0 for c in game: h_1 *= BASE_1 h_2 *= BASE_2 h_1 += ord(c) - ord('a') h_2 += ord(c) - ord('a') h_1 %= MOD_1 h_2 %= MOD_2 hashes_1.append(h_1) hashes_2.append(h_2) hash_inv[(h_1, h_2)] = i game_inv[game] = i # assert len(hash_inv) == g # compute rolling hash on cd string # find all residues (mod k) at which each game appears s = s + s h_1 = 0 h_2 = 0 for i in range(k): h_1 *= BASE_1 h_2 *= BASE_2 h_1 += ord(s[i]) - ord('a') h_2 += ord(s[i]) - ord('a') h_1 %= MOD_1 h_2 %= MOD_2 coef_1 = pow(BASE_1, k - 1, MOD_1) coef_2 = pow(BASE_2, k - 1, MOD_2) residues = [set() for i in range(g)] for i in range(k, len(s)): # first, consider the word at [i - k, i) # (h = hash of that word) if (h_1, h_2) in hash_inv: residues[hash_inv[(h_1, h_2)]].add(i % k) # update h for next word h_1 -= coef_1 * (ord(s[i - k]) - ord('a')) h_2 -= coef_2 * (ord(s[i - k]) - ord('a')) h_1 *= BASE_1 h_2 *= BASE_2 h_1 += ord(s[i]) - ord('a') h_2 += ord(s[i]) - ord('a') h_1 %= MOD_1 h_2 %= MOD_2 res_freq = [0]*k for i in range(g): for res in residues[i]: res_freq[res] += 1 use = -1 for i in range(k): # if s.startswith("muytqaevcsnqpkfxq"): # print i, res_freq[i], n if res_freq[i] >= n: use = i break if use == -1: print "NO" else: print "YES" ans = [] for i in range(n): idx = k*i + use ss = s[idx:idx+k] ans.append(game_inv[ss] + 1) print " ".join(map(str, ans))
1476522300
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2 seconds
["Success\nConflict with 6\nSuccess\nAlready off\nSuccess\nSuccess\nSuccess\nSuccess\nConflict with 10\nAlready on"]
6cec3662101b419fb734b7d6664fdecd
NoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: "Success" if the activation was successful. "Already on", if the i-th collider was already activated before the request. "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: "Success", if the deactivation was successful. "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.
Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "-Β i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n).
standard output
standard input
Python 3
Python
1,600
train_033.jsonl
0be8335fa0addd77d62a949608dec84f
256 megabytes
["10 10\n+ 6\n+ 10\n+ 5\n- 10\n- 5\n- 6\n+ 10\n+ 3\n+ 6\n+ 3"]
PASSED
n, m = map(int, input().split()) n += 1 s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(m): t = input() i = int(t[2: ]) if t[0] == '+': if i in d: r[j] = 'Already on' continue for q in s[i]: if q in p: r[j] = 'Conflict with ' + str(p[q]) break else: r[j] = 'Success' d.add(i) for q in s[i]: p[q] = i else: if i in d: r[j] = 'Success' for q in s[i]: p.pop(q) d.remove(i) else: r[j] = 'Already off' print('\n'.join(r)) # Made By Mostafa_Khaled
1330095600
[ "number theory", "math" ]
[ 0, 0, 0, 1, 1, 0, 0, 0 ]
1 second
["3", "4"]
7c41fb6212992d1b3b3f89694b579fea
NoteIllustration for the first example: Illustration for the second example:
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
standard output
standard input
Python 3
Python
900
train_017.jsonl
39db005ea406d9369c68e9c5f86ee466
256 megabytes
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
PASSED
n = int(input()) s=0 m=0 for i in range(n): a = [ int(i) for i in input().split() ] s = sum(a) if s>=m: m=s print(m)
1537540500
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["2 3 3 0 1 2\n\n1 0 1\n\n1 0 2\n\n2 2 1 1\n\n3\n1111\n1111\n1111\n0001"]
beae75b649ca6ed26180954faf73e5a3
NoteIn the given example:The first query asks whether there's a passage from room $$$3$$$ to any of the other rooms.The second query asks about the direction of the passage between rooms $$$0$$$ and $$$1$$$.After a couple other queries, we concluded that you can go from any room to any other room except if you start at room $$$3$$$, and you can't get out of this room, so we printed the matrix:1111111111110001The interactor answered with $$$1$$$, telling us the answer is correct.
This is an interactive problem.Baby Ehab loves crawling around his apartment. It has $$$n$$$ rooms numbered from $$$0$$$ to $$$n-1$$$. For every pair of rooms, $$$a$$$ and $$$b$$$, there's either a direct passage from room $$$a$$$ to room $$$b$$$, or from room $$$b$$$ to room $$$a$$$, but never both.Baby Ehab wants to go play with Baby Badawy. He wants to know if he could get to him. However, he doesn't know anything about his apartment except the number of rooms. He can ask the baby sitter two types of questions: is the passage between room $$$a$$$ and room $$$b$$$ directed from $$$a$$$ to $$$b$$$ or the other way around? does room $$$x$$$ have a passage towards any of the rooms $$$s_1$$$, $$$s_2$$$, ..., $$$s_k$$$? He can ask at most $$$9n$$$ queries of the first type and at most $$$2n$$$ queries of the second type.After asking some questions, he wants to know for every pair of rooms $$$a$$$ and $$$b$$$ whether there's a path from $$$a$$$ to $$$b$$$ or not. A path from $$$a$$$ to $$$b$$$ is a sequence of passages that starts from room $$$a$$$ and ends at room $$$b$$$.
To print the answer for a test case, print a line containing "3", followed by $$$n$$$ lines, each containing a binary string of length $$$n$$$. The $$$j$$$-th character of the $$$i$$$-th string should be $$$1$$$ if there's a path from room $$$i$$$ to room $$$j$$$, and $$$0$$$ if there isn't. The $$$i$$$-th character of the $$$i$$$-th string should be $$$1$$$ for each valid $$$i$$$. After printing the answer, we will respond with a single integer. If it's $$$1$$$, you printed a correct answer and should keep solving the test cases (or exit if it is the last one). If it's $$$-1$$$, you printed a wrong answer and should terminate to get Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.
The first line contains an integer $$$t$$$ ($$$1 \le t \le 30$$$)Β β€” the number of test cases you need to solve. Then each test case starts with an integer $$$n$$$ ($$$4 \le n \le 100$$$)Β β€” the number of rooms. The sum of $$$n$$$ across the test cases doesn't exceed $$$500$$$.
standard output
standard input
Python 3
Python
2,700
train_110.jsonl
371b7ee024837c275765f903b8431928
256 megabytes
["1\n4\n\n0\n\n0\n\n1\n\n1\n\n1"]
PASSED
def ask1(i, j):print('1', i, j);return int(input()) != 0 def ask2(i, a):print('2', i, len(a), *a);return int(input()) != 0 def answer(a): print('3') for x in a: print(*x, sep = '') assert(int(input()) != -1) for _ in range(int(input())): n = int(input());ans = [[0] * n for i in range(n)];path = [] for i in range(n): l, r = -1, i while r - l > 1: m = (l + r) >> 1 if ask1(path[m], i):l = m else:r = m path = path[:r] + [i] + path[r:] for i in range(n): for j in range(i, n):ans[path[i]][path[j]] = 1 l, r = n - 1, n - 1 for i in range(n - 1, -1, -1): while l > 0 and ask2(path[i], path[:l]):l -= 1 if i == l: for x in range(l, r + 1): for y in range(x, r + 1):ans[path[y]][path[x]] = 1 l, r = i - 1, i - 1 answer(ans)
1618839300
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
2 seconds
["-1\n2\n1\n2"]
09a0bad93090b65b5515abf0ccb96bd4
NoteIn the first set of inputs, even if all the friends stay in the maze, Vlad can still win. Therefore, the answer is "-1".In the second set of inputs it is enough to leave friends from rooms $$$6$$$ and $$$7$$$. Then Vlad will not be able to win. The answer is "2".In the third and fourth sets of inputs Vlad cannot win only if all his friends stay in the maze. Therefore the answers are "1" and "2".
The only difference with E1 is the question of the problem.Vlad built a maze out of $$$n$$$ rooms and $$$n-1$$$ bidirectional corridors. From any room $$$u$$$ any other room $$$v$$$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited $$$k$$$ friends to play a game with them.Vlad starts the game in the room $$$1$$$ and wins if he reaches a room other than $$$1$$$, into which exactly one corridor leads. Friends are placed in the maze: the friend with number $$$i$$$ is in the room $$$x_i$$$, and no two friends are in the same room (that is, $$$x_i \neq x_j$$$ for all $$$i \neq j$$$). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.Friends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what minimum number of friends must remain in the maze so that they can always catch Vlad.In other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.
Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be $$$-1$$$ if Vlad wins anyway and a minimal number of friends otherwise.
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β€” the number of test cases in the input. The input contains an empty string before each test case. The first line of the test case contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le k &lt; n \le 2\cdot 10^5$$$) β€” the number of rooms and friends, respectively. The next line of the test case contains $$$k$$$ integers $$$x_1, x_2, \dots, x_k$$$ ($$$2 \le x_i \le n$$$) β€” numbers of rooms with friends. All $$$x_i$$$ are different. The next $$$n-1$$$ lines contain descriptions of the corridors, two numbers per line $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) β€” numbers of rooms that connect the $$$j$$$ corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test is not greater than $$$2\cdot10^5$$$.
standard output
standard input
PyPy 3-64
Python
1,900
train_093.jsonl
490b449b4b194ce92c4646280af4d08d
256 megabytes
["4\n\n8 2\n5 3\n4 7\n2 5\n1 6\n3 6\n7 2\n1 7\n6 8\n\n8 4\n6 5 7 3\n4 7\n2 5\n1 6\n3 6\n7 2\n1 7\n6 8\n\n3 1\n2\n1 2\n2 3\n\n3 2\n2 3\n3 1\n1 2"]
PASSED
from collections import defaultdict, deque import sys input = sys.stdin.buffer.readline for _ in range(int(input())): input() n, k = map(int, input().split()) fl = input() d = defaultdict(list) for _ in range(n-1): a, b = map(int, input().split()) d[a].append(b) d[b].append(a) p = dict() c = defaultdict(list) vis = set() q = deque([(1, None)]) while q: curr, prev = q.popleft() if curr in vis: continue vis.add(curr) if prev: p[curr] = prev c[prev].append(curr) for v in d[curr]: if v not in vis: q.append((v, curr)) dist = dict() # q = deque([(x,0) for x in fl]) q = deque(map(lambda x: (int(x),0), fl.split())) while q: curr, dis = q.popleft() if curr in dist: continue dist[curr] = dis if curr != 1 and p[curr] not in dist: q.append((p[curr], dis+1)) # vis = set() q = deque([(1,0)]) ans = 0 while q: curr, dis = q.popleft() if curr not in dist: ans = -1 break elif dis == dist[curr] or dis == dist[curr]+1: ans += 1 continue elif not c[curr]: ans = -1 break else: for v in c[curr]: q.append((v,dis+1)) print(ans)
1637850900
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
2 seconds
["3"]
f3c26aa520f6bfa6b181ec40bde7ee1b
null
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
The first line of the input contains n (1 ≀ n ≀ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≀ 109).
standard output
standard input
PyPy 3
Python
1,800
train_039.jsonl
740c09a3634b5e5d1de8f86ab2e22805
256 megabytes
["3\n1 2\n1 3\n1 -1 1"]
PASSED
from sys import stdin, stdout,setrecursionlimit from collections import defaultdict,deque,Counter,OrderedDict from heapq import heappop,heappush import threading n = int(stdin.readline()) graph = [set() for x in range(n)] for x in range(n-1): a,b = [int(x) for x in stdin.readline().split()] a -= 1 b -= 1 graph[a].add(b) graph[b].add(a) vals = [int(x) for x in stdin.readline().split()] bruh = [(0,-1)] for x in range(n): num,p = bruh[x] for y in graph[num]: if y != p: bruh.append((y,num)) result = [-1 for x in range(n)] for v,parent in bruh[::-1]: nP = 0 nN = 0 for x in graph[v]: if x != parent: p,n = result[x] nP = max(nP,p) nN = max(nN, n) nN = max(nN, nP+vals[v]) nP = max(nP, nN-vals[v]) result[v] = (nP,nN) ng, ps = result[0] vals[0] += ps - ng stdout.write(str(ng+ps))
1361374200
[ "trees" ]
[ 0, 0, 0, 0, 0, 0, 0, 1 ]
1 second
["cc\ncbaabc\naa\nbb"]
dd7faacff9f57635f8e00c2f8f5a4650
NoteIn the first test case choose $$$k = 1$$$ to obtain "cc".In the second test case choose $$$k = 3$$$ to obtain "cbaabc".In the third test case choose $$$k = 1$$$ to obtain "aa".In the fourth test case choose $$$k = 1$$$ to obtain "bb".
You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?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$$$.
For each test case print the lexicographically smallest string you can see.
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. 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,100
train_101.jsonl
9ba2a3d400e2452bc13b5360b2f2e884
256 megabytes
["4\n10\ncodeforces\n9\ncbacbacba\n3\naaa\n4\nbbaa"]
PASSED
for s in[*open(0)][2::2]: a=*map(ord,s[:-1]),123;i=1 while(i>1)+a[i-1]>a[i]:i+=1 s=s[:i];print(s+s[::-1])
1640792100
[ "strings" ]
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
2.5 seconds
["0\n250000002\n250000002\n500000004\n0\n250000002\n250000002\n250000002\n250000002\n0\n1"]
1759fabd248d2b313ecfb8e1b3e7b0db
NoteHere is the example of $$$6$$$ ants moving on the branch. An ant's movement will be denoted by either a character $$$L$$$ or $$$R$$$. Initially, the pack of ants on the branch will move as $$$RLRRLR$$$. Here's how the behavior of the pack demonstrated: Initially, the ants are positioned as above. After a while, the ant with index $$$2$$$ (walking to the left) will crash with the ant with index $$$1$$$ (walking to the right). The two ants have the same weight, therefore, ant $$$2$$$ will eat ant $$$1$$$ and gain its weight to $$$2$$$. The same thing happens with ant $$$5$$$ and ant $$$4$$$.The ant $$$6$$$ will walk to the end of the stick, therefore changing its direction. After that, the ant with index $$$5$$$ will crash with the ant with index $$$3$$$. Since ant $$$5$$$ is more heavy (weight=$$$2$$$) than ant $$$3$$$ (weight=$$$1$$$), ant $$$5$$$ will eat ant $$$3$$$ and gain its weight to $$$3$$$.Ant $$$2$$$ will walk to the end of the stick, therefore changing its direction. After that, the ant with index $$$5$$$ will crash with the ant with index $$$2$$$. Since ant $$$5$$$ is more heavy (weight=$$$3$$$) than ant $$$2$$$ (weight=$$$2$$$), ant $$$5$$$ will eat ant $$$2$$$ and gain its weight to $$$5$$$. Lastly, after ant $$$5$$$ walk to the end of the branch and changes its direction, ant $$$5$$$ will eat ant $$$6$$$ and be the last ant standing.
Ela likes to go hiking a lot. She loves nature and exploring the various creatures it offers. One day, she saw a strange type of ant, with a cannibalistic feature. More specifically, an ant would eat any ants that it sees which is smaller than it.Curious about this feature from a new creature, Ela ain't furious. She conducts a long, non-dubious, sentimental experiment.She puts $$$n$$$ cannibalistic ants in a line on a long wooden stick. Initially, the ants have the same weight of $$$1$$$. The distance between any two consecutive ants is the same. The distance between the first ant in the line to the left end and the last ant in the line to the right end is also the same as the distance between the ants. Each ant starts moving towards the left-end or the right-end randomly and equiprobably, at the same constant pace throughout the experiment. Two ants will crash if they are standing next to each other in the line and moving in opposite directions, and ants will change direction immediately when they reach the end of the stick. Ela can't determine the moving direction of each ant, but she understands very well their behavior when crashes happen. If a crash happens between two ants of different weights, the heavier one will eat the lighter one, and gain the weight of the lighter one. After that, the heavier and will continue walking in the same direction. In other words, if the heavier one has weight $$$x$$$ and walking to the right, the lighter one has weight $$$y$$$ and walking to the left ($$$x &gt; y$$$), then after the crash, the lighter one will diminish, and the heavier one will have weight $$$x + y$$$ and continue walking to the right. If a crash happens between two ants with the same weight, the one walking to the left end of the stick will eat the one walking to the right, and then continue walking in the same direction. In other words, if one ant of weight $$$x$$$ walking to the left, crashes with another ant of weight $$$x$$$ walking to the right, the one walking to the right will disappear, and the one walking to the left will have to weight $$$2x$$$ and continue walking to the left. Please, check the example in the "Note" section, which will demonstrate the ants' behavior as above.We can prove that after a definite amount of time, there will be only one last ant standing. Initially, each ant can randomly and equiprobably move to the left or the right, which generates $$$2^n$$$ different cases of initial movements for the whole pack. For each position in the line, calculate the probability that the ant begins in that position and survives. Output it modulo $$$10^9 + 7$$$.Formally, let $$$M = 10^9 + 7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x &lt; M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
For each test, print $$$n$$$ lines. $$$i$$$-th line contains a single number that denotes the survival probability of the $$$i$$$-th ant in the line modulo $$$10^9 + 7$$$.
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The only line of each test contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) β€” the number of ants in the experiment. It is guaranteed that the sum of $$$n$$$ in all tests will not exceed $$$10^6$$$.
standard output
standard input
PyPy 3-64
Python
2,500
train_094.jsonl
0ab92873a9a92eac654c4316ec46f281
256 megabytes
["3\n\n4\n\n5\n\n2"]
PASSED
import sys import math import heapq import itertools import bisect import random import time from collections import deque input=sys.stdin.readline mod=10**9+7 def power(a,n): if n==0: return 1 x=power(a,n//2) if n%2==0: return x*x%mod else: return x*x*a%mod def d(a): return power(a,mod-2) d2=d(2) pp=[d(power(2,0))] for i in range(1000005): pp.append((pp[-1]*d2)%mod) t=int(input()) for _ in range(t): n=int(input()) ans=[1 for _ in range(n+1)] dp=[0 for _ in range(n+1)] for i in range(n//2+1,n+1): dp[i]=1 dp[n//2]=(1-d(pow(2,n//2-1)))%mod for i in range(n//2-1,0,-1): dp[i]=(dp[i+1]-dp[i*2]*pp[i]-dp[i*2+1]*pp[i+1])%mod for i in range(1,n+1): p=max(0,(i-1)//2) ans[i]=(dp[i]*pp[p])%mod if i!=n: ans[i]=(ans[i]*d2)%mod for i in range(1,n+1): print(ans[i])
1665153300
[ "probabilities", "math" ]
[ 0, 0, 0, 1, 0, 1, 0, 0 ]
2 seconds
["acb"]
b442b73ecb559f0841c0e86f84b5cbb1
null
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.
Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.
First-line contains two integers: $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^3$$$) β€” the number of pages that scientists have found and the number of words present at each page. Following $$$n$$$ groups contain a line with a single integer $$$p_i$$$ ($$$0 \le n \lt 10^3$$$) β€” the number of $$$i$$$-th page, as well as $$$k$$$ lines, each line containing one of the strings (up to $$$100$$$ characters) written on the page numbered $$$p_i$$$.
standard output
standard input
PyPy 3
Python
2,200
train_040.jsonl
a4b560defcec44f69201b47d9eff366f
256 megabytes
["3 3\n2\nb\nb\nbbac\n0\na\naca\nacba\n1\nab\nc\nccb"]
PASSED
import os import io from collections import deque, defaultdict input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def li():return [int(i) for i in input().rstrip().split()] def st():return str(input().rstrip())[2:-1] def val():return int(input().rstrip()) # def li():return [int(i) for i in input().rstrip().split()] # def st():return str(input()) # def val():return int(input()) #Input Reading n,k = li() words = [""] * n * k indeg = {} for i in range(n): p = val() page = [] for j in range(k): word = st() words[p*k+j] = word for c in word: indeg[c] = 0 def match(w1,w2): for i in range(min(len(w1), len(w2))): if w1[i] == w2[i]: continue else: return (w1[i],w2[i]) if len(w1) > len(w2): print("IMPOSSIBLE") exit() #Reading the graph and its indegrees g = defaultdict(set) for i in range(len(words) - 1): out = match(words[i], words[i+1]) if out is not None: c1,c2 = out if c2 not in g[c1]: g[c1].add(c2) indeg[c2] += 1 #Topsort things ts = [] zero = deque() for u in indeg: if indeg[u] == 0: zero.append(u) while len(ts) != len(indeg): if len(zero) == 0: print("IMPOSSIBLE") exit() u = zero.popleft() ts.append(u) for v in g[u]: indeg[v] -= 1 if indeg[v] == 0: zero.append(v) print("".join(ts))
1601903100
[ "graphs" ]
[ 0, 0, 1, 0, 0, 0, 0, 0 ]
1 second
["101 10", "30 15", "18 18", "7000 7000"]
21672f2906f4f821611ab1b6dfc7f081
NoteIn the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game?
Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.
The first line contain an integer n (1 ≀ n ≀ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≀ si ≀ 100) β€” the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≀ ck ≀ 1000) β€” the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.
standard output
standard input
Python 2
Python
2,000
train_015.jsonl
e4cdbbc535cd8f7d16d576616dcc7499
256 megabytes
["2\n1 100\n2 1 10", "1\n9 2 8 6 5 9 4 7 1 3", "3\n3 1 3 2\n3 5 4 6\n2 8 7", "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000"]
PASSED
n = input() cie = jir = 0 mid = [] for i in xrange(n): card = map(int, raw_input().split()) s = card[0] card = card[1:] b = s / 2 e = (s + 1) / 2 if(b != e): mid.append(card[b]) cie += sum(card[:b]) jir += sum(card[e:]) l = (len(mid) + 1) / 2 mid = sorted(mid, reverse = True) for i in xrange(len(mid)): if(i % 2 == 0): cie += mid[i] else: jir += mid[i] print cie,jir
1391442000
[ "games" ]
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
1 second
["NO", "YES\n3.659792366325"]
fc37ef81bb36f3ac07ce2c4c3ec10d98
NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in seconds.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β€” when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom. You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.
If it is impossible to make the cup empty, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line. In the second line print a real number β€” time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
The only line of the input contains four integer numbers d, h, v, e (1 ≀ d, h, v, e ≀ 104), where: d β€” the diameter of your cylindrical cup, h β€” the initial level of water in the cup, v β€” the speed of drinking process from the cup in milliliters per second, e β€” the growth of water because of rain if you do not drink from the cup.
standard output
standard input
PyPy 2
Python
1,100
train_017.jsonl
08c90f295143b9047f663bda52642377
256 megabytes
["1 2 3 100", "1 1 1 1"]
PASSED
from math import pi d, h, v, e = map(int, raw_input().split()) vol = 4 * v /(pi * d * d) if e >= vol : print "NO" else : print "YES" print h / (vol - e)
1461947700
[ "geometry", "math" ]
[ 0, 1, 0, 1, 0, 0, 0, 0 ]
1 second
["1\nGRB", "3\nRGBRGBR"]
e67b79e39511b0107a51edc0179afb82
null
You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' β€” colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
In the first line of the output print one integer $$$r$$$ β€” the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ β€” a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' β€” colors of lamps in the garland.
standard output
standard input
PyPy 2
Python
1,300
train_013.jsonl
7c9d2a770b443418413e1ef9a9ff8d43
256 megabytes
["3\nBRB", "7\nRGBGRBB"]
PASSED
from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip from itertools import permutations def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split(" ")) def msi(): return map(str,input().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() import math def getSum(n): sum = 0 while(n > 0): sum += int(n%10) n = int(n/10) return sum def isPowerOfTwo (x): return (x and (not(x & (x - 1))) ) def gcd(x, y): while y: x, y = y, x % y return x def egcd(a, b): if a == 0 : return b, 0, 1 gcd, x1, y1 = egcd(b%a, a) x = y1 - (b//a) * x1 y = x1 return gcd, x, y def checkPrime(n) : # Check Prime Number or not if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def fib(n): if n==0: return (0,1) p=fib(n>>1) c=p[0]*(2*p[1]-p[0]) d=p[0]*p[0]+p[1]*p[1] if (n&1): return c+2*d else: return c+d def read(): sys.stdin = open('input.txt', 'r') def powLog(x,y): res=1 while y>0: if y&1: res=res*x x=x*x y>>=1 return res def main(): n=ii() s=si() p=['RGB','RBG','BRG','BGR','GBR','GRB'] mcost=n for i in p: c=0 res= (i*(n//3+1))[:n] for x in range(n): if res[x] != s[x]: c+=1 if c < mcost: mcost = c new_r = res print (mcost) print(new_r) # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() main() #dmain() # Comment Read()
1548254100
[ "math" ]
[ 0, 0, 0, 1, 0, 0, 0, 0 ]