prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
⌀ | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
⌀ | prob_desc_input_spec
stringlengths 38
2.42k
⌀ | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
⌀ | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 second
|
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
|
8590f40e7509614694486165ee824587
|
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
|
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) > n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
| null | null |
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,800 |
train_110.jsonl
|
c5d8cd50f4f067925b59f3cf404756a3
|
256 megabytes
|
["1\n\n2\n\n-1"]
|
PASSED
|
for i in range(3, 26):
print(f"? 1 {i}", flush=True)
a = int(input())
if (a == -1):
print(f'! {i - 1}')
exit()
print(f"? {i} 1", flush=True)
b = int(input())
if a != b:
print(f'! {a + b}')
exit()
|
1662993300
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["YES\nNO\nYES\nNO\nYES\nYES"]
|
e5a0005e0832e2ca3dd248f6aefb2238
|
NoteHere's the solution for the first test case. The red square denotes where the crickets need to reach. Note that in chess horizontals are counted from bottom to top, as well as on this picture.
|
Ela likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game.The problem, which involves a non-standard chess pieces type that is described below, reads: given $$$3$$$ white crickets on a $$$n \cdot n$$$ board, arranged in an "L" shape next to each other, there are no other pieces on the board. Ela wants to know with a finite number of moves, can she put any white cricket on the square on row $$$x$$$, column $$$y$$$?An "L"-shape piece arrangement can only be one of the below: For simplicity, we describe the rules for crickets on the board where only three white crickets are. It can move horizontally, vertically, or diagonally, but only to a square in some direction that is immediately after another cricket piece (so that it must jump over it). If the square immediately behind the piece is unoccupied, the cricket will occupy the square. Otherwise (when the square is occupied by another cricket, or does not exist), the cricket isn't allowed to make such a move.See an example of valid crickets' moves on the pictures in the Note section.
|
For each test case, print "YES" or "NO" to denotes whether Ela can put a cricket on the target square.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$4 \le n \le 10^5$$$) — denotes the size of the chessboard. The second line of each test case contains 6 numbers: $$$r_1$$$, $$$c_1$$$, $$$r_2$$$, $$$c_2$$$, $$$r_3$$$, $$$c_3$$$ ($$$1 \le r_1, c_1, r_2, c_2, r_3, c_3 \le n$$$) — coordinates of the crickets. The input ensures that the three crickets are arranged in an "L" shape that the legend stated. The third line of each test case contains 2 numbers: $$$x$$$, $$$y$$$ ($$$1 \le x, y \le n$$$) — coordinates of the target square.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_094.jsonl
|
350f6c381ca6dcf04e7abf300381d9e6
|
256 megabytes
|
["6\n\n8\n\n7 2 8 2 7 1\n\n5 1\n\n8\n\n2 2 1 2 2 1\n\n5 5\n\n8\n\n2 2 1 2 2 1\n\n6 6\n\n8\n\n1 1 1 2 2 1\n\n5 5\n\n8\n\n2 2 1 2 2 1\n\n8 8\n\n8\n\n8 8 8 7 7 8\n\n4 8"]
|
PASSED
|
import math
import collections
import bisect
import heapq
from collections import deque
from math import sqrt,ceil, floor
def inp_arr():
return list(map(int, input().strip().split(" ")))
def inp_int():
return int(input())
def inp_str():
return input()
'''................................................................................'''
def solve():
# cook your dish here
n, = inp_arr()
r1,c1,r2,c2,r3,c3 = inp_arr()
x,y = inp_arr()
r0 = (r1+r2+r3 - (r1^r2^r3))//2
c0 = (c1+c2+c3 - (c1^c2^c3))//2
corners = [[1,1], [1,n], [n,n], [n,1]]
if([r0, c0] in corners):
if(x == r0 or y==c0):
print("YES")
else:
print("NO")
return
def check(x1,y1,x2,y2):
diff1 = abs(x1-x2)
diff2 = abs(y1-y2)
if(diff1%2==0 and diff2%2==0):
return True
return False
if(check(r1,c1,x,y) or check(r2,c2,x,y) or check(r3,c3,x,y)):
print("YES")
return
print("NO")
tt = inp_int()
# tt = 1
for t in range(tt):
solve()
|
1665153300
|
[
"math",
"games"
] |
[
1,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"]
|
dc3848faf577c5a49273020a14b343e1
|
NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment.
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree.
|
In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any.
|
The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_110.jsonl
|
2468b1e1f237837269e5f3138f497cb3
|
256 megabytes
|
["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"]
|
PASSED
|
#!/usr/bin/env python3
import sys
# import getpass # not available on codechef
# import math, random
# import functools, itertools, collections, heapq, bisect
from collections import defaultdict
input = sys.stdin.readline # to read input quickly
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
MAXINT = sys.maxsize
# if testing locally, print to terminal with a different color
# OFFLINE_TEST = getpass.getuser() == "htong"
OFFLINE_TEST = False # codechef does not allow getpass
def log(*args):
if OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def read_matrix(rows):
return [list(map(int,input().split())) for _ in range(rows)]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
# https://codeforces.com/blog/entry/80158?locale=en
from types import GeneratorType
def bootstrap(f, stack=[]):
# usage - please remember to YIELD to call and return
'''
@bootstrap
def recurse(n):
if n <= 0:
yield 0
yield (yield recurse(n-1)) + 2
res = recurse(10**5)
'''
def wrappedfunc(*args):
if stack:
return f(*args)
else:
to = f(*args)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
if stack:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
if True:
total_vertices = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# arr = input().split()
# read one line and parse each word as an integer
# a,b,c = list(map(int,input().split()))
# arr = list(map(int,input().split()))
# arr = minus_one(arr)
# read multiple rows
# arr = read_strings(k) # and return as a list of str
mrr = read_matrix(total_vertices-1) # and return as a list of list of int
mrr = minus_one_matrix(mrr)
# if total_vertices == 2:
# return 2,2,[1,1]
# your solution here
# https://courses.grainger.illinois.edu/cs473/sp2011/lectures/09_lec.pdf
g = defaultdict(set)
for a,b in mrr:
g[a].add(b)
g[b].add(a)
# log(a, b)
degree = defaultdict(int)
for x in range(total_vertices):
degree[x] = len(g[x])
opt = [-1 for _ in range(total_vertices)]
opt1_store = [-1 for _ in range(total_vertices)]
opt2_store = [-1 for _ in range(total_vertices)]
start = allstart = 0
assignment = [0 for _ in range(total_vertices)]
def dfs(start, g, entry_operation, exit_operation):
entered = set([start])
exiting = set()
stack = [start]
prev = {}
null_pointer = "NULL"
prev[start] = null_pointer
while stack:
cur = stack[-1]
if cur not in exiting:
for nex in g[cur]:
if nex in entered:
continue
entry_operation(prev[cur], cur, nex)
entered.add(nex)
stack.append(nex)
prev[nex] = cur
exiting.add(cur)
else:
stack.pop()
exit_operation(prev[cur], cur)
def entry_operation(prev, cur, nex):
pass
def exit_operation(prev, cur):
opt1 = 1_000_000 - degree[cur] + 1
opt2 = 0
for nex in g[cur]:
if nex == prev:
continue
opt2 += opt[nex]
for nex_nex in g[nex]:
if nex_nex == cur:
continue
opt1 += opt[nex_nex]
opt1_store[cur] = opt1
opt2_store[cur] = opt2
opt[cur] = max(opt1, opt2)
dfs(0, g, entry_operation, exit_operation)
color = {}
color[0] = 1 - int(opt[0] == opt2_store[0])
def entry_operation(prev, cur, nex):
if color[cur] == 1 or opt[nex] == opt2_store[nex]:
color[nex] = 0
else:
color[nex] = 1
def exit_operation(prev, cur):
pass
dfs(0, g, entry_operation, exit_operation)
# assert -1 not in assignment
# assert -1 not in opt
# assert -1 not in opt1_store
# assert -1 not in opt2_store
log(opt)
# log(assignment)
assignment = [degree[i] if color[i] else 1 for i in range(total_vertices)]
a = sum(degree[i] == x for i,x in enumerate(assignment))
b = sum(assignment)
print(a,b)
print(" ".join(str(x) for x in assignment))
|
1646408100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1110011110\n0011\n0110001100101011\n10\n0000111\n1111\n000"]
|
4bbb078b66b26d6414e30b0aae845b98
| null |
For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers: $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$; $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$; $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.
|
Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_000.jsonl
|
ab934202d948056f7e8caca09d32dc3d
|
256 megabytes
|
["7\n1 3 5\n1 1 1\n3 9 3\n0 1 0\n3 1 2\n0 0 3\n2 0 0"]
|
PASSED
|
def ans_v2(n_0, n_1, n_2):
ans_left = ''
ans_center = ''
ans_right = ''
if n_1 == 0:
if n_0 > 0:
ans_left = '0'*(n_0 + 1)
else:
ans_right = '1'*(n_2 + 1)
else:
if n_0 == 0:
if (n_1 % 2 == 0):
ans_left = '10'*(n_1 // 2)
else:
ans_left = '0' + '10'*((n_1 - 1) // 2)
ans_center = '1'*(n_2 + 1)
elif n_2 == 0:
if (n_1 % 2 == 0):
ans_left = '01'*(n_1 // 2)
else:
ans_left = '1' + '01'*((n_1 - 1) // 2)
ans_right = '0'*(n_0 + 1)
else: # все ненулевые
ans_right = '0'*(n_0 + 1)
ans_center = '1'*(n_2 + 1)
if (n_1 % 2 == 0): # чётное n_1
ans_left = '0' + '10'*((n_1 - 2) // 2)
else: # нечётное n_1
ans_left = '10'*((n_1 - 1) // 2)
return ans_left + ans_center + ans_right
t = int(input())
for i in range(t):
input_nums = input().split(' ')
answer = ans_v2(int(input_nums[0]), int(input_nums[1]), int(input_nums[2]))
print(answer)
|
1589034900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["codeforces round letter round", "hbnyiyc joll joll un joll"]
|
edd556d60de89587f1b8daa893538530
| null |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.
|
The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,000 |
train_000.jsonl
|
40a2a72adab2d9497e4db77cd8db391c
|
256 megabytes
|
["4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest", "5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll"]
|
PASSED
|
n, m = map(int, raw_input().split())
a = dict()
for i in xrange(m):
s1, s2 = raw_input().split()
if len(s2) < len(s1):
a[s1] = s2
else:
a[s1] = s1
for s in raw_input().split():
print a[s],
|
1419438600
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nNO\nYES", "YES\nNO\nYES\nYES"]
|
e2db2e7470a24c17158772be94eef12c
| null |
This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not. Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.
|
Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
|
The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_089.jsonl
|
d15fdd310b6b0d01b4e2e7f7d4fdc839
|
256 megabytes
|
["5\n1 2\n2 3\n2 4\n4 5\n5\n3\n3 2 5\n5\n1 2 3 4 5\n2\n1 4\n3\n1 3 5\n3\n1 5 4", "5\n1 2\n3 2\n2 4\n5 2\n4\n2\n3 1\n3\n3 4 5\n3\n2 3 5\n1\n1"]
|
PASSED
|
import sys
from typing import List
input = sys.stdin.readline
class LowestCommonAncestor:
def __init__(self, n, E):
assert n >= 1 and len(E) == n - 1
self.n = n
self.adj = [[] for _ in range(self.n)]
for e in E:
u, v = e
self.adj[u].append(v)
self.adj[v].append(u)
self.sz = 1
while 1 << self.sz < n:
self.sz += 1
self.root = None
self.depth = [-1 for _ in range(n)]
self.up = [[-1] * self.sz for _ in range(n)]
def dfs(self, root):
stack = [(root, root, 0)]
while len(stack):
u, prev, d = stack.pop()
self.depth[u] = d
self.up[u][0] = prev
for v in self.adj[u]:
if v == prev:
continue
stack.append((v, u, d + 1))
for j in range(1, self.sz):
for i in range(1, self.n):
if self.up[i][j - 1] == -1:
continue
self.up[i][j] = self.up[self.up[i][j - 1]][j - 1]
def lca(self, u, v):
if self.depth[u] > self.depth[v]:
u, v = v, u
diff = self.depth[v] - self.depth[u]
for i in reversed(range(self.sz)):
if diff >> i & 1:
v = self.up[v][i]
if u == v:
return u
for i in reversed(range(self.sz)):
pu, pv = self.up[u][i], self.up[v][i]
if pu != pv:
u, v = pu, pv
return self.up[u][0]
def query(LCA, p):
depth = LCA.depth
lca = LCA.lca
p.sort(key=lambda idx: -depth[idx])
left_chain_deepest = p[0]
right_chain_deepest = -1
turning_point = 0
for x in p:
if lca(x, left_chain_deepest) != x:
if right_chain_deepest == -1:
right_chain_deepest = x
turning_point = lca(left_chain_deepest, right_chain_deepest)
else:
if lca(x, right_chain_deepest) != x:
# print("Third Chain!")
return False
if right_chain_deepest == -1:
return True
if depth[turning_point] > depth[p[-1]]:
# print("Turning point(%d), deeper than root(%d)" % (turning_point + 1, p[-1] + 1))
return False
return True
# initialize
n = int(input())
E = []
for i in range(n - 1):
u, v = map(lambda s: int(s)-1, input().split())
E.append((u, v))
LCA = LowestCommonAncestor(n, E)
LCA.dfs(1-1)
q = int(input())
for qq in range(q):
k = int(input())
*p, = map(lambda s: int(s)-1, input().split())
print("YES" if query(LCA, p) else "NO")
# n = 5
# E = [(1, 2), (2, 3), (2, 4), (4, 5)]
# *E2, = map(lambda pair: (pair[0]-1, pair[1]-1), E)
#
# LCA = LowestCommonAncestor(n, E2)
# root = 1
# LCA.dfs(root - 1)
# print(LCA.depth)
#
# q = 5
# arr_k
# for qq in range(q):
# k = arr_k[qq]
|
1657463700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["2\n6 3\n2 4", "3\n9 3\n2 4\n6 8", "0"]
|
72d70a1c2e579bf81954ff932a9bc16e
| null |
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
|
The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them.
|
A single integer n (1 ≤ n ≤ 105), the number of the apples.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500 |
train_061.jsonl
|
518b832d348d773e7dad1d2cf87185f5
|
256 megabytes
|
["6", "9", "2"]
|
PASSED
|
"""
Codeforces Round 257 Div 1 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
return [int(x) for x in inputs.split()]
def write(s="\n"):
if isinstance(s, list): s = " ".join(map(str,s))
s = str(s)
print(s, end="")
################################################### SOLUTION
# croft algorithm to generate primes
# from pyprimes library, not built-in, just google it
from itertools import compress
import itertools
def croft():
"""Yield prime integers using the Croft Spiral sieve.
This is a variant of wheel factorisation modulo 30.
"""
# Implementation is based on erat3 from here:
# http://stackoverflow.com/q/2211990
# and this website:
# http://www.primesdemystified.com/
# Memory usage increases roughly linearly with the number of primes seen.
# dict ``roots`` stores an entry x:p for every prime p.
for p in (2, 3, 5):
yield p
roots = {9: 3, 25: 5} # Map d**2 -> d.
primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
for q in compress(
# Iterate over prime candidates 7, 9, 11, 13, ...
itertools.islice(itertools.count(7), 0, None, 2),
# Mask out those that can't possibly be prime.
itertools.cycle(selectors)
):
# Using dict membership testing instead of pop gives a
# 5-10% speedup over the first three million primes.
if q in roots:
p = roots[q]
del roots[q]
x = q + 2*p
while x in roots or (x % 30) not in primeroots:
x += 2*p
roots[x] = p
else:
roots[q*q] = q
yield q
n, = read()
cr = croft()
primes = []
for i in cr:
if i < n:
primes.append(i)
else:
break
primes.reverse()
used = [0] * (n+1)
res = []
for p in primes:
k = n//p
tmp = []
while k:
if not used[k*p]:
tmp.append(k*p)
used[k*p] = 1
if len(tmp) == 2:
res.append(tmp)
tmp = []
k -= 1
if tmp == [p] and p > 2 and p*2 <= n and len(res) and res[-1][1] == p*2:
res[-1][1] = p
used[p*2] = 0
used[p] = 1
print(len(res))
for i in res:
print(" ".join(map(str, i)))
|
1405774800
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["10\n9\n1000\n42000000000000"]
|
beab56c5f7d2996d447320a62b0963c2
| null |
Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop — $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.
|
Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.
|
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$$$) — how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_002.jsonl
|
c534a3f7bd14b891392c8d80a7f09d9a
|
256 megabytes
|
["4\n10 1 3\n7 3 2\n1 1000 1\n1000000000000 42 88"]
|
PASSED
|
q=int(input())
for x in range(q):
price=0
arr = [int(xx) for xx in input().split()]
if arr[1]>=arr[2]:
if arr[0]%2==0:
price=(arr[0]/2)*arr[2]
else:
price=((arr[0]-1)/2)*arr[2]+arr[1]
else:
if arr[0]%2==0:
if arr[0]*arr[1]<=(arr[0]/2)*arr[2]:
price=arr[0]*arr[1]
else:
price=(arr[0]/2)*arr[2]
else:
if arr[0]*arr[1]<=((arr[0]-1)/2)*arr[2]+arr[1]:
price=arr[0]*arr[1]
else:
price=((arr[0]-1)/2)*arr[2]+arr[1]
print(int(price))
|
1550586900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4", "251", "47464146"]
|
4ce699a5633d6d3073c2daa7e10060bd
|
NoteIn the first example, there are $$$4$$$ different mathematical states of this constellation: $$$a_1=1$$$, $$$a_2=1$$$. $$$a_1=1$$$, $$$a_2=2$$$. $$$a_1=2$$$, $$$a_2=1$$$. $$$a_1=3$$$, $$$a_2=1$$$.
|
Mocha wants to be an astrologer. There are $$$n$$$ stars which can be seen in Zhijiang, and the brightness of the $$$i$$$-th star is $$$a_i$$$. Mocha considers that these $$$n$$$ stars form a constellation, and she uses $$$(a_1,a_2,\ldots,a_n)$$$ to show its state. A state is called mathematical if all of the following three conditions are satisfied: For all $$$i$$$ ($$$1\le i\le n$$$), $$$a_i$$$ is an integer in the range $$$[l_i, r_i]$$$. $$$\sum \limits _{i=1} ^ n a_i \le m$$$. $$$\gcd(a_1,a_2,\ldots,a_n)=1$$$. Here, $$$\gcd(a_1,a_2,\ldots,a_n)$$$ denotes the greatest common divisor (GCD) of integers $$$a_1,a_2,\ldots,a_n$$$.Mocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo $$$998\,244\,353$$$.Two states $$$(a_1,a_2,\ldots,a_n)$$$ and $$$(b_1,b_2,\ldots,b_n)$$$ are considered different if there exists $$$i$$$ ($$$1\le i\le n$$$) such that $$$a_i \ne b_i$$$.
|
Print a single integer — the number of different mathematical states of this constellation, modulo $$$998\,244\,353$$$.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 50$$$, $$$1 \le m \le 10^5$$$) — the number of stars and the upper bound of the sum of the brightness of stars. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — the range of the brightness of the $$$i$$$-th star.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_095.jsonl
|
182067a428f77a6560e6827c21e4ab60
|
256 megabytes
|
["2 4\n1 3\n1 2", "5 10\n1 10\n1 10\n1 10\n1 10\n1 10", "5 100\n1 94\n1 96\n1 91\n4 96\n6 97"]
|
PASSED
|
import sys
input=sys.stdin.readline #文字列入力はするな!
mod=998244353
n,m=map(int,input().split())
l=[0]
r=[0]
for i in range(n):
x,y=map(int,input().split())
l.append(x)
r.append(y)
f=[0]*(m+10)
for g in range(m,0,-1):
if m//g<n:continue
dp=[0]*(n+3)*(m//g+2)
def _(i,k):
return k*(n+2)+i
dp[_(0,0)]=1
sdp=[1]*(m//g+3)
for i in range(1,n+1):
for k in range(m//g+2):
x,y=(l[i]+g-1)//g,r[i]//g
ma=k-x
mi=k-y
if ma<0:continue
if mi<=0:dp[_(i,k)]=sdp[ma]
else:dp[_(i,k)]=sdp[ma]-sdp[mi-1]
dp[_(i,k)]%=mod
sdp[0]=dp[_(i,0)]
for k in range(1,m//g+2):
sdp[k]=sdp[k-1]+dp[_(i,k)]
sdp[k]%=mod
for k in range(m//g+1):
f[g]+=dp[_(n,k)]
f[g]%=mod
ans=[0]*(m+5)
for g in range(m,0,-1):
ans[g]=f[g]
i=2
while i*g<=m:
ans[g]-=ans[g*i]
ans[g]%=mod
i+=1
print(ans[1])
|
1629038100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["yes", "no"]
|
36fb3a01860ef0cc2a1065d78e4efbd5
|
NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.
|
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
|
In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.
|
The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,500 |
train_022.jsonl
|
4906ce3358718027adc682dfec9d56de
|
256 megabytes
|
["3\ni\nlove\nyou\n<3i<3love<23you<3", "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3"]
|
PASSED
|
s=list('<3'+'<3'.join(raw_input() for _ in range(input()))+'<3')
t=list(raw_input())
while s and t:
if s[-1]==t[-1]:s.pop()
t.pop()
print 'no' if s else 'yes'
|
1382715000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["acb", "baa"]
|
adbfdb0d2fd9e4eb48a27d43f401f0e0
|
NoteLet's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb".
|
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change.For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.
|
Print a single string — the user's final name after all changes are applied to it.
|
The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_029.jsonl
|
5e465d8da04331defe9de9ddb148f8ef
|
256 megabytes
|
["2\nbac\n3\n2 a\n1 b\n2 c", "1\nabacaba\n4\n1 a\n1 a\n1 c\n2 b"]
|
PASSED
|
#copied... idea
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline() if mode=="file" else input()).split()]
[k]=get()
[g]=gets()
h = g*k
h = list(h)
p = []
for i in range(128):
p.append([0])
for i in range(len(h)):
p[ord(h[i])].append(i)
[n]=get()
for i in range(n):
[x,y]=gets()
x = int(x)
h[p[ord(y)][x]]=''
p[ord(y)].pop(x)
print("".join(h))
if mode=="file":f.close()
if __name__=="__main__":
main()
|
1331280000
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["66.666666666667", "37.500000000000"]
|
580596d05a2eaa36d630d71ef1055c43
|
NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal milliliters. The total cocktail's volume equals 3·x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent.
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.
|
Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10 - 4.
|
The first input line contains a single integer n (1 ≤ n ≤ 100) — the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 ≤ pi ≤ 100) — the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_004.jsonl
|
8d0eb9e97df415d54e47a1030a6fefbe
|
256 megabytes
|
["3\n50 50 100", "4\n0 25 50 75"]
|
PASSED
|
n=int(input())
l=map(int,input().split())
k=sum(l)/n
print('%.12f'%k)
|
1340551800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"]
|
739e60a2fa71aff9a5c7e781db861d1e
| null |
We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too?
|
Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) — the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_000.jsonl
|
479155577366530719b3898b47485a1a
|
256 megabytes
|
["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"]
|
PASSED
|
import sys
import os
range = xrange
input = raw_input
S = sys.stdin.read()
n = len(S)
A = []
i = 0
while i < n:
c = 0
while ord(S[i]) >= 48:
c = 10 * c + ord(S[i]) - 48
i += 1
A.append(c)
i += 1 + (S[i] == '\r')
inp = A; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
bfs = [0]
found = [0]*n
children = coupl
for node in bfs:
found[node] = 1
for nei in coupl[node]:
bfs.append(nei)
coupl[nei].remove(node)
family = [1]*n
for node in reversed(bfs):
for child in children[node]:
family[node] += family[child]
out = inp
out.append(0)
out[1] = 2 * n - 1
mark = [0]*n
for node in bfs:
l = mark[node]
r = l + 2 * family[node] - 1
for child in children[node]:
mark[child] = l
l += 2 * family[child] - 1
r -= 1
out[2 * child + 1] = r
out[2 * node] = r - 1
os.write(1, ' '.join(str(x + 1) for x in out))
|
1576766100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["Yes\nNo\nNo\nYes\nYes\nYes"]
|
7224ffd4776af4129739e1b28f696050
|
NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$
|
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move: exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$; exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$; exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$; exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.
|
For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_004.jsonl
|
7f5cd367e8cf07513163d9a19ff084f7
|
512 megabytes
|
["6\n3 2 2 2\n0 0 -2 -2 2 2\n3 1 4 1\n0 0 -1 -1 1 1\n1 1 1 1\n1 1 1 1 1 1\n0 0 0 1\n0 0 0 0 0 1\n5 1 1 1\n0 0 -100 -100 0 100\n1 1 5 1\n0 0 -100 -100 100 0"]
|
PASSED
|
for _ in " "*int(input()):
left,right,down,up=map(int,input().split())
x,y,x1,y1,x2,y2=map(int,input().split())
if (x1==x2 and left+right>0) or (y1==y2 and up+down>0):
print("NO")
elif x1<=x+(right-left)<=x2 and y1<=y+(up-down)<=y2:
print("YES")
else:
print("NO")
|
1585661700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0", "3", "2"]
|
80fdb95372c1e8d558b8c8f31c9d0479
| null |
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
|
Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
|
The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,100 |
train_013.jsonl
|
3a30455087b879302a052fd22b2a65bf
|
256 megabytes
|
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
|
PASSED
|
from collections import defaultdict
n = input()
s = raw_input()
d = defaultdict(int)
c = 0
for i in range(1,2*n-2+1):
if i%2:
d[s[i-1]] += 1
elif i%2 == 0 and d[s[i-1].lower()] == 0:
c += 1
elif i%2 ==0 and d[s[i-1].lower()] != 0:
d[s[i-1].lower()] -= 1
print c
|
1427387400
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["BOB\nBOB"]
|
42b425305ccc28b0d081b4c417fe77a1
|
NoteIn the first test case of the example, in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome. in the $$$2$$$-nd move Bob reverses the string. in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over. Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob always wins.
|
The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ (which is initially a palindrome in this version) of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
|
For each test case print a single word in a new line: "ALICE", if Alice will win the game, "BOB", if Bob will win the game, "DRAW", if the game ends in a draw.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ is a palindrome and contains at least one '0'. Note that there is no limit on the sum of $$$n$$$ over test cases.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_085.jsonl
|
37ee0dff6babbdad80d093f740ebc7e7
|
256 megabytes
|
["2\n4\n1001\n1\n0"]
|
PASSED
|
t = int(input())
while t:
int(input())
s = input().count('0')
if s%2 == 1 and s > 1: print('ALICE')
else: print('BOB')
t-=1
|
1621521300
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2 3", "2 1 3", "4 1 2"]
|
3cdd85f86c77afd1d3b0d1e951a83635
|
NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".
|
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.
|
Print three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.
|
First and only line contains two space-separated integers n and a (3 ≤ n ≤ 105, 1 ≤ a ≤ 180) — the number of vertices in the polygon and the needed angle, in degrees.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300 |
train_034.jsonl
|
b187677178f990618f073a8662744b74
|
256 megabytes
|
["3 15", "4 67", "4 68"]
|
PASSED
|
from sys import stdin, stdout
n, a = map(int, stdin.readline().split())
ans = 180 * (n - 2) / n
f, s, t = 1, 2, 3
dif = 180 / n
cnt = dif
for i in range(n - 2):
if abs(a - ans) > abs(a - cnt):
ans = cnt
f, s, t = 2, 1, 3 + i
cnt += dif
stdout.write(str(f) + ' ' + str(s) + ' ' + str(t))
|
1498574100
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO"]
|
6b37fc623110e49a5e311a2d186aae46
|
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
|
You are given two integers $$$n$$$ and $$$m$$$ ($$$m < n$$$). Consider a convex regular polygon of $$$n$$$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with $$$m$$$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with $$$m$$$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon 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. Each test case is given as two space-separated integers $$$n$$$ and $$$m$$$ ($$$3 \le m < n \le 100$$$) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.
|
standard output
|
standard input
|
Python 2
|
Python
| 800 |
train_009.jsonl
|
4926b486b614502b3a59856d9bd3cbb4
|
256 megabytes
|
["2\n6 3\n7 3"]
|
PASSED
|
'''
'''
from sys import stdin, stdout
def main():
n = int(stdin.readline())
for x in range(n):
n, m = [int(x) for x in stdin.readline().split()]
if n / float(m) == n / m:
stdout.write('YES\n')
else:
stdout.write('NO\n')
if __name__ == "__main__":
main()
|
1583764500
|
[
"number theory",
"geometry",
"math"
] |
[
0,
1,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["2\n1\n1\n4\n72"]
|
a58ad54eaf4912f530a7d25a503640d3
|
NoteFor the first test case, the only permutations similar to $$$a=[4,0,3,2,1]$$$ are $$$[4,0,3,2,1]$$$ and $$$[4,0,2,3,1]$$$.For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are $$$4$$$ permutations similar to $$$a=[1,2,4,0,5,3]$$$: $$$[1,2,4,0,5,3]$$$; $$$[1,2,5,0,4,3]$$$; $$$[1,4,2,0,5,3]$$$; $$$[1,5,2,0,4,3]$$$.
|
You are given a permutation $$$a_1,a_2,\ldots,a_n$$$ of integers from $$$0$$$ to $$$n - 1$$$. Your task is to find how many permutations $$$b_1,b_2,\ldots,b_n$$$ are similar to permutation $$$a$$$. Two permutations $$$a$$$ and $$$b$$$ of size $$$n$$$ are considered similar if for all intervals $$$[l,r]$$$ ($$$1 \le l \le r \le n$$$), the following condition is satisfied: $$$$$$\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]),$$$$$$ where the $$$\operatorname{MEX}$$$ of a collection of integers $$$c_1,c_2,\ldots,c_k$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in collection $$$c$$$. For example, $$$\operatorname{MEX}([1,2,3,4,5])=0$$$, and $$$\operatorname{MEX}([0,1,2,4,5])=3$$$.Since the total number of such permutations can be very large, you will have to print its remainder modulo $$$10^9+7$$$.In this problem, a permutation of size $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n-1$$$ in arbitrary order. For example, $$$[1,0,2,4,3]$$$ is a permutation, while $$$[0,1,1]$$$ is not, since $$$1$$$ appears twice in the array. $$$[0,1,3]$$$ is also not a permutation, since $$$n=3$$$ and there is a $$$3$$$ in the array.
|
For each test case, print a single integer, the number of permutations similar to permutation $$$a$$$, taken modulo $$$10^9+7$$$.
|
Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of permutation $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \lt n$$$) — the elements of permutation $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_088.jsonl
|
678772c2986c01d36f6cca116ead1758
|
256 megabytes
|
["5\n\n5\n\n4 0 3 2 1\n\n1\n\n0\n\n4\n\n0 1 2 3\n\n6\n\n1 2 4 0 5 3\n\n8\n\n1 3 7 2 5 0 6 4"]
|
PASSED
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split(' ')))
mod = 10 ** 9 + 7
if n <= 3:
print(1)
continue
indices = [0] * n
for i in range(n):
indices[a[i]] = i
res, l, r = 1, min(indices[0], indices[1]), max(indices[0], indices[1])
for i in range(2, n):
if l < indices[i] < r:
res *= r - l + 1 - i
res %= mod
else:
l = min(l, indices[i])
r = max(r, indices[i])
print(res)
|
1656945300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n1 2 5\n1 3 5", "1\n2 3 5", "2\n1 2 12\n3 4 8", "1\n2 3 15"]
|
6f7bee466780e6e65b2841bfccad28b0
|
NoteIn the first example the optimal sequence of operations can be the following: Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 2$$$, $$$d = 3$$$ and $$$z = 5$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(2, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$; Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$. In the second example the optimal sequence of operations can be the following: Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 3$$$, $$$d = 1$$$ and $$$z = 10$$$. The resulting debts are: $$$d(3, 2) = 10$$$, $$$d(2, 3) = 15$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$; Perform an operation of the first type with $$$a = 2$$$, $$$b = 3$$$, $$$c = 3$$$, $$$d = 2$$$ and $$$z = 10$$$. The resulting debts are: $$$d(2, 2) = 10$$$, $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$; Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$; Perform an operation of the second type with $$$a = 3$$$. The resulting debts are: $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$; Perform an operation of the second type with $$$a = 1$$$. The resulting debts are: $$$d(2, 3) = 5$$$, all other debts are $$$0$$$.
|
There are $$$n$$$ people in this world, conveniently numbered $$$1$$$ through $$$n$$$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $$$d(a,b)$$$ denote the debt of $$$a$$$ towards $$$b$$$, or $$$0$$$ if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done: Let $$$d(a,b) > 0$$$ and $$$d(c,d) > 0$$$ such that $$$a \neq c$$$ or $$$b \neq d$$$. We can decrease the $$$d(a,b)$$$ and $$$d(c,d)$$$ by $$$z$$$ and increase $$$d(c,b)$$$ and $$$d(a,d)$$$ by $$$z$$$, where $$$0 < z \leq \min(d(a,b),d(c,d))$$$. Let $$$d(a,a) > 0$$$. We can set $$$d(a,a)$$$ to $$$0$$$. The total debt is defined as the sum of all debts:$$$$$$\Sigma_d = \sum_{a,b} d(a,b)$$$$$$Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.
|
On the first line print an integer $$$m'$$$ ($$$0 \leq m' \leq 3\cdot 10^5$$$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint. After that print $$$m'$$$ lines, $$$i$$$-th of which contains three space separated integers $$$u_i, v_i, d_i$$$, meaning that the person $$$u_i$$$ owes the person $$$v_i$$$ exactly $$$d_i$$$ burles. The output must satisfy $$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$ and $$$0 < d_i \leq 10^{18}$$$. For each pair $$$i \neq j$$$, it should hold that $$$u_i \neq u_j$$$ or $$$v_i \neq v_j$$$. In other words, each pair of people can be included at most once in the output.
|
The first line contains two space separated integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$m$$$ ($$$0 \leq m \leq 3\cdot 10^5$$$), representing the number of people and the number of debts, respectively. $$$m$$$ lines follow, each of which contains three space separated integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), $$$d_i$$$ ($$$1 \leq d_i \leq 10^9$$$), meaning that the person $$$u_i$$$ borrowed $$$d_i$$$ burles from person $$$v_i$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_050.jsonl
|
aa6337013b9b73f3540702e457a1f00c
|
256 megabytes
|
["3 2\n1 2 10\n2 3 5", "3 3\n1 2 10\n2 3 15\n3 1 10", "4 2\n1 2 12\n3 4 8", "3 4\n2 3 1\n2 3 2\n2 3 4\n2 3 8"]
|
PASSED
|
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict as dd
I = lambda : list(map(int,input().split()))
n,m=I()
fi=[0]*(n+1)
for i in range(m):
u,v,w=I()
fi[u]-=w
fi[v]+=w
p=[];m=[]
for i in range(1,n+1):
if fi[i]<0:
m.append([-fi[i],i])
elif fi[i]>0:
p.append([fi[i],i])
an=[]
while p and m:
a,b=p[-1],m[-1]
if a[0]==b[0]:
p.pop();m.pop()
an.append([b[1],a[1],a[0]])
elif a[0]<b[0]:
m[-1][0]-=a[0]
p.pop()
an.append([b[1],a[1],a[0]])
else:
p[-1][0]-=b[0]
m.pop()
an.append([b[1],a[1],b[0]])
print(len(an))
for u,v,d in an:
print(u,v,d)
|
1576595100
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4"]
|
22319b83f5874287e3aeaa6dd339e7cb
| null |
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.In BubbleLand, there are $$$N$$$ toilet paper factories, and $$$N$$$ airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number $$$d$$$ given, number of days it takes to build that road.Your job is to choose $$$N$$$ factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
|
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal $$$d$$$ among all chosen roads.
|
The first line contains two integers $$$N$$$ $$$(1 \leq N \leq 10^4)$$$ - number of airports/factories, and $$$M$$$ $$$(1 \leq M \leq 10^5)$$$ - number of available pairs to build a road between. On next $$$M$$$ lines, there are three integers $$$u$$$, $$$v$$$ $$$(1 \leq u,v \leq N)$$$, $$$d$$$ $$$(1 \leq d \leq 10^9)$$$ - meaning that you can build a road between airport $$$u$$$ and factory $$$v$$$ for $$$d$$$ days.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_002.jsonl
|
e5788a6c4f240a69a3df5835ece2cbf9
|
256 megabytes
|
["3 5\n1 2 1\n2 3 2\n3 3 3\n2 1 4\n2 2 5"]
|
PASSED
|
import os
import sys
from io import BytesIO, IOBase
# 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")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
def judge(last,key,d1,d2):
if key>last:
for (a,b,c) in data:
if last<c<=key:
d1[a].add(b)
d2[b].add(a)
else:
for (a,b,c) in data:
if key<c<=last:
d1[a].remove(b)
if not d1[a]:
del d1[a]
d2[b].remove(a)
if not d2[b]:
del d2[b]
if len(d1.keys())<n or len(d2.keys())<n:
return False
for a in d1:
lone = 0
for b in d1[a]:
if len(d2[b])==1:
lone+=1
if lone>1:
return False
for b in d2:
lone = 0
for a in d2[b]:
if len(d1[a])==1:
lone+=1
if lone>1:
return False
used = set()
for a in d1:
if a not in used:
s1,s2,now = {a},d1[a].copy(),d1[a].copy()
while now:
b = now.pop()
da = d2[b]-s1
s1|=da
for aa in da:
db = d1[aa]-s2
now|=db
s2|=db
if len(s1)!=len(s2):
return False
used|=s1
return True
n,m = RL()
data = []
for _ in range(m):
data.append(tuple(map(int, sys.stdin.readline().split())))
l,r = min(a[2] for a in data),max(a[2] for a in data)+1
md = r
last = 0
du = dc(set)
dv = dc(set)
while l<r:
key = (l+r)>>1
if judge(last,key,du,dv):
r = key
else:
l = key+1
last = key
if l>=md:
print(-1)
else:
print(l)
|
1601903100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["210", "30"]
|
816a82bee65cf79ba8e4d61babcd0301
|
NoteIn the first example we can choose next parameters: $$$a = [1, 1, 1, 1]$$$, $$$b = [1, 1, 1, 1]$$$, $$$x = [0, 0, 0, 0]$$$, then $$$f_i^{(k)} = k \bmod p_i$$$.In the second example we can choose next parameters: $$$a = [1, 1, 2]$$$, $$$b = [1, 1, 0]$$$, $$$x = [0, 0, 1]$$$.
|
You are given a tuple generator $$$f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$$$, where $$$f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$$$ and $$$f^{(0)} = (x_1, x_2, \dots, x_n)$$$. Here $$$x \bmod y$$$ denotes the remainder of $$$x$$$ when divided by $$$y$$$. All $$$p_i$$$ are primes.One can see that with fixed sequences $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ the tuples $$$f^{(k)}$$$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $$$f^{(k)}$$$ for $$$k \ge 0$$$) that can be produced by this generator, if $$$x_i$$$, $$$a_i$$$, $$$b_i$$$ are integers in the range $$$[0, p_i - 1]$$$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $$$10^9 + 7$$$
|
Print one integer — the maximum number of different tuples modulo $$$10^9 + 7$$$.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the tuple. The second line contains $$$n$$$ space separated prime numbers — the modules $$$p_1, p_2, \ldots, p_n$$$ ($$$2 \le p_i \le 2 \cdot 10^6$$$).
|
standard output
|
standard input
|
Python 2
|
Python
| 2,900 |
train_000.jsonl
|
a6c9d900ce4a35b98ae2dd0c1b114598
|
512 megabytes
|
["4\n2 3 5 7", "3\n5 3 3"]
|
PASSED
|
import sys
import time
mod=1000000007
def sieve(s):
is_not_prime=[False]*(s+1)
prime=[]
small=[0]*(s+1)
cnt=[0]*(s+1)
other=[0]*(s+1)
for i in xrange(2, s+1):
if not is_not_prime[i]:
prime.append(i)
small[i]=i
cnt[i]=1
other[i]=1
for p in prime:
next=p*i
if next>s:
break
is_not_prime[next]=True
small[next]=p
if i%p==0:
cnt[next]=cnt[i]+1
other[next]=other[i]
break
cnt[next]=1
other[next]=i
print>>sys.stderr, len(prime)
return small, cnt, other
def add(value):
any=False
back_up=value
while value!=1:
old=d.get(small[value], (0, 0))
if old[0]<cnt[value]:
d[small[value]]=(cnt[value], 0)
any=True
value=other[value]
if any:
value=back_up
while value!=1:
old=d[small[value]]
if old[0]==cnt[value]:
d[small[value]]=(old[0], old[1]+1)
value=other[value]
return any
def test(value):
any=False
while value!=1:
old=d[small[value]]
if old[0]==cnt[value] and old[1]==1:
any=True
value=other[value]
return any
small, cnt, other=sieve(2000000)
print>>sys.stderr, time.clock()
n=input()
d=dict()
has_zero=False
p=sorted(map(int, raw_input().split()), reverse=True)
l=[]
for value in p:
if not add(value):
if not add(value-1):
has_zero=True
else:
l+=[value-1]
if not has_zero:
for value in l:
if not test(value):
has_zero=True
result=1
for p, _ in d.items():
c=_[0]
result=result*pow(p, c, mod)%mod
if has_zero:
result=(result+1)%mod
print result
|
1537707900
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["No\nYes\nYes\nYes"]
|
749a106d462555543c91753f00a5a479
|
NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing $$$(8,1,9,3)$$$ to $$$(7,0,8,6)$$$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.
|
Boboniu gives you $$$r$$$ red balls, $$$g$$$ green balls, $$$b$$$ blue balls, $$$w$$$ white balls. He allows you to do the following operation as many times as you want: Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.
|
For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".
|
The first line contains one integer $$$T$$$ ($$$1\le T\le 100$$$) denoting the number of test cases. For each of the next $$$T$$$ cases, the first line contains four integers $$$r$$$, $$$g$$$, $$$b$$$ and $$$w$$$ ($$$0\le r,g,b,w\le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_002.jsonl
|
e8d52f18fd3b1fbaa6d7079300714eda
|
256 megabytes
|
["4\n0 1 1 1\n8 1 9 3\n0 0 0 0\n1000000000 1000000000 1000000000 1000000000"]
|
PASSED
|
Nombre = int(input()) ;
for m in range(Nombre) :
Tab = list(map(int,input().split())) ;
odd = 0 ;
null = 0 ;
for n in Tab :
if (n % 2) == 1 :
odd += 1 ;
if (odd ==1) or (odd== 4) or (odd ==0) :
print("Yes") ;
elif (odd == 3) :
for n in range(3) :
if Tab[n] == 0 :
null += 1 ;
if null > 0 :
print("No") ;
else :
print("Yes") ;
else :
print("No") ;
|
1597242900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n0\n2\n0\n1\n1\n1\n1"]
|
c2a506d58a80a0fb6a16785605b075ca
|
NoteIn the first case, Burenka can multiply $$$c$$$ by $$$2$$$, then the fractions will be equal.In the second case, fractions are already equal.In the third case, Burenka can multiply $$$a$$$ by $$$4$$$, then $$$b$$$ by $$$3$$$. Then the fractions will be equal ($$$\frac{1 \cdot 4}{2 \cdot 3} = \frac{2}{3}$$$).
|
Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($$$\frac{a}{b}$$$ and $$$\frac{c}{d}$$$) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $$$0$$$). Now she wants know the minimal number of claps to make her fractions equal (by value). Please help her and find the required number of claps!
|
For each test case print a single integer — the minimal number of claps Burenka needs to make her fractions equal.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then follow the descriptions of each test case. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$0 \leq a, c \leq 10^9$$$, $$$1 \leq b, d \leq 10^9$$$) — numerators and denominators of the fractions given to Burenka initially.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_098.jsonl
|
c3ad00a9e17baa2d010651904032176c
|
256 megabytes
|
["8\n\n2 1 1 1\n\n6 3 2 1\n\n1 2 2 3\n\n0 1 0 100\n\n0 1 228 179\n\n100 3 25 6\n\n999999999 300000000 666666666 100000000\n\n33 15 0 84"]
|
PASSED
|
#comment
n = int(input())
def do(a, b, c, d):
if a==0 and c!=0:
return 1
if c==0 and a!=0:
return 1
fst, snd = a * d, b * c
if fst == snd:
return 0
if fst % snd == 0 or snd % fst == 0:
return 1
else:
return 2
for i in range(n):
a, b, c, d = map(int, input().split())
claps = 0
print(do(a, b, c, d))
|
1660829700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["1.000000000000000", "0.333333333333333", "0.100000000000000"]
|
4c92218ccbab7d142c2cbb6dd54c510a
|
NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
|
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
|
Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if
|
The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,600 |
train_000.jsonl
|
e1a75b52a4e1b51adf1d97dd49b4f9a3
|
256 megabytes
|
["technocup", "tictictactac", "bbaabaabbb"]
|
PASSED
|
from __future__ import print_function, division
from sys import stdin, stdout
from collections import *
chrs = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:;?!"#&\'()*+,-./ '
rstr = lambda: stdin.readline().strip()
s, ans = rstr(), 0
le = len(s)
mem = [[[0 for _ in range(le)] for _ in range(26)] for _ in range(26)]
get = lambda x: ord(x) - ord('a')
for i in range(le):
for j in range(le):
mem[get(s[i])][get(s[(j + i) % le])][j] += 1
for i in range(26):
t1 = 0
for j in range(le):
t2 = 0
for k in range(26):
t2 += (mem[get(chrs[i])][get(chrs[k])][j] == 1)
t1 = max(t1, t2)
ans += t1
print(ans / le)
|
1520177700
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2.5 seconds
|
["odfrces\nezakmi\ncba\nconvexhul\nwfldjgpaxs\nmyneocktxqjpz"]
|
a30f6f5273fc6c02ac1f2bc2b0ee893e
| null |
You are given a string $$$s$$$, consisting of lowercase Latin letters. While there is at least one character in the string $$$s$$$ that is repeated at least twice, you perform the following operation: you choose the index $$$i$$$ ($$$1 \le i \le |s|$$$) such that the character at position $$$i$$$ occurs at least two times in the string $$$s$$$, and delete the character at position $$$i$$$, that is, replace $$$s$$$ with $$$s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n$$$. For example, if $$$s=$$$"codeforces", then you can apply the following sequence of operations: $$$i=6 \Rightarrow s=$$$"codefrces"; $$$i=1 \Rightarrow s=$$$"odefrces"; $$$i=7 \Rightarrow s=$$$"odefrcs"; Given a given string $$$s$$$, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.A string $$$a$$$ of length $$$n$$$ is lexicographically less than a string $$$b$$$ of length $$$m$$$, if: there is an index $$$i$$$ ($$$1 \le i \le \min(n, m)$$$) such that the first $$$i-1$$$ characters of the strings $$$a$$$ and $$$b$$$ are the same, and the $$$i$$$-th character of the string $$$a$$$ is less than $$$i$$$-th character of string $$$b$$$; or the first $$$\min(n, m)$$$ characters in the strings $$$a$$$ and $$$b$$$ are the same and $$$n < m$$$. For example, the string $$$a=$$$"aezakmi" is lexicographically less than the string $$$b=$$$"aezus".
|
For each test case, output the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string become unique.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by a string $$$s$$$, consisting of lowercase Latin letters ($$$1 \le |s| \le 2 \cdot 10^5$$$). It is guaranteed that the sum of the lengths of the strings in all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_101.jsonl
|
fbc7c54ee1d523b84717d0fce5281904
|
256 megabytes
|
["6\ncodeforces\naezakmi\nabacaba\nconvexhull\nswflldjgpaxs\nmyneeocktxpqjpz"]
|
PASSED
|
in1 = lambda : int(input())
in2 = lambda : list(map(int, input().split()))
#Solve
import math
def solve():
s = input()
#print("RES: ", end='')
n = len(s)
stack = []
seen = set()
d = {c : idx for idx, c in enumerate(s)}
for i in range(n):
if s[i] not in seen:
while stack and stack[-1] < s[i] and d[stack[-1]] > i:
seen.discard(stack.pop())
stack.append(s[i])
seen.add(s[i])
print("".join(stack))
if __name__ == "__main__":
t = 1
t = in1()
for i in range(t):
solve()
|
1616682900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["14\n45\n163\n123"]
|
1ff25abd9d49de5e5ce3f7338ddef18c
|
NoteIn the first test case, an optimal solution is to: move $$$1$$$: $$$r = 4$$$, $$$b = 2$$$; no swap; move $$$2$$$: $$$r = 7$$$, $$$b = 6$$$; swap (after it $$$r = 6$$$, $$$b = 7$$$); move $$$3$$$: $$$r = 11$$$, $$$b = 9$$$; no swap. The total number of points is $$$|7 - 2| + |6 - 9| + |3 - 9| = 14$$$. In the second test case, an optimal solution is to: move $$$1$$$: $$$r = 2$$$, $$$b = 2$$$; no swap; move $$$2$$$: $$$r = 3$$$, $$$b = 4$$$; no swap; move $$$3$$$: $$$r = 5$$$, $$$b = 6$$$; no swap. The total number of points is $$$|32 - 32| + |78 - 69| + |5 - 41| = 45$$$.
|
You are given $$$n - 1$$$ integers $$$a_2, \dots, a_n$$$ and a tree with $$$n$$$ vertices rooted at vertex $$$1$$$. The leaves are all at the same distance $$$d$$$ from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree $$$1$$$ are leaves. If vertices $$$s$$$ and $$$f$$$ are connected by an edge and the distance of $$$f$$$ from the root is greater than the distance of $$$s$$$ from the root, then $$$f$$$ is called a child of $$$s$$$.Initially, there are a red coin and a blue coin on the vertex $$$1$$$. Let $$$r$$$ be the vertex where the red coin is and let $$$b$$$ be the vertex where the blue coin is. You should make $$$d$$$ moves. A move consists of three steps: Move the red coin to any child of $$$r$$$. Move the blue coin to any vertex $$$b'$$$ such that $$$dist(1, b') = dist(1, b) + 1$$$. Here $$$dist(x, y)$$$ indicates the length of the simple path between $$$x$$$ and $$$y$$$. Note that $$$b$$$ and $$$b'$$$ are not necessarily connected by an edge. You can optionally swap the two coins (or skip this step). Note that $$$r$$$ and $$$b$$$ can be equal at any time, and there is no number written on the root.After each move, you gain $$$|a_r - a_b|$$$ points. What's the maximum number of points you can gain after $$$d$$$ moves?
|
For each test case, print a single integer: the maximum number of points you can gain after $$$d$$$ moves.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$v_2, v_3, \dots, v_n$$$ ($$$1 \leq v_i \leq n$$$, $$$v_i \neq i$$$) — the $$$i$$$-th of them indicates that there is an edge between vertices $$$i$$$ and $$$v_i$$$. It is guaranteed, that these edges form a tree. The third line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the numbers written on the vertices. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,500 |
train_092.jsonl
|
b97b6491b5a52140c6088795f877f62c
|
256 megabytes
|
["4\n14\n1 1 1 2 3 4 4 5 5 6 7 8 8\n2 3 7 7 6 9 5 9 7 3 6 6 5\n6\n1 2 2 3 4\n32 78 69 5 41\n15\n1 15 1 10 4 9 11 2 4 1 8 6 10 11\n62 13 12 43 39 65 42 86 25 38 19 19 43 62\n15\n11 2 7 6 9 8 10 1 1 1 5 3 15 2\n50 19 30 35 9 45 13 24 8 44 16 26 10 40"]
|
PASSED
|
import sys
I=lambda:[*map(int,sys.stdin.readline().split())]
t, = I()
for _ in range(t):
n, = I()
par = [0,0]+I()
a = [0,0]+I()
children = [[] for _ in range(n+1)]
for i in range(2, n+1):
children[par[i]].append(i)
layers = [[1]]
while 1:
nextlayer = []
for v in layers[-1]:
for u in children[v]:
nextlayer.append(u)
if len(nextlayer) == 0:
break
layers.append(nextlayer)
dp = [0]*(n+1)
for j in range(len(layers)-1, 0, -1):
M = max(a[u] for u in layers[j])
m = min(a[u] for u in layers[j])
X = max(dp[u]+a[u] for u in layers[j])
Y = max(dp[u]-a[u] for u in layers[j])
for v in layers[j]:
dp[v] = max(max(M-a[v], a[v]-m)+dp[v], X-a[v], Y+a[v])
dp[par[v]] = max(dp[par[v]], dp[v])
print(dp[1])
|
1613141400
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
4 seconds
|
["14", "131"]
|
db8855495d22c26296351fe310281df2
|
NoteIn the first example, it's optimal to rearrange the elements of the given array in the following order: $$$[6, \, 2, \, 2, \, 2, \, 3, \, 1]$$$:$$$$$$\operatorname{gcd}(a_1) + \operatorname{gcd}(a_1, \, a_2) + \operatorname{gcd}(a_1, \, a_2, \, a_3) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5, \, a_6) = 6 + 2 + 2 + 2 + 1 + 1 = 14.$$$$$$ It can be shown that it is impossible to get a better answer.In the second example, it's optimal to rearrange the elements of a given array in the following order: $$$[100, \, 10, \, 10, \, 5, \, 1, \, 3, \, 3, \, 7, \, 42, \, 54]$$$.
|
This is the hard version of the problem. The only difference is maximum value of $$$a_i$$$.Once in Kostomuksha Divan found an array $$$a$$$ consisting of positive integers. Now he wants to reorder the elements of $$$a$$$ to maximize the value of the following function: $$$$$$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i),$$$$$$ where $$$\operatorname{gcd}(x_1, x_2, \ldots, x_k)$$$ denotes the greatest common divisor of integers $$$x_1, x_2, \ldots, x_k$$$, and $$$\operatorname{gcd}(x) = x$$$ for any integer $$$x$$$.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.
|
Output the maximum value of the function that you can get by reordering elements of the array $$$a$$$.
|
The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_{1}, \, a_{2}, \, \dots, \, a_{n}$$$ ($$$1 \le a_{i} \le 2 \cdot 10^7$$$) — the array $$$a$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_098.jsonl
|
7736a2859ec0cf55791414e12971808e
|
1024 megabytes
|
["6\n2 3 1 2 6 2", "10\n5 7 10 3 1 10 100 3 42 54"]
|
PASSED
|
''' D2. Divan and Kostomuksha (hard version)
https://codeforces.com/contest/1614/problem/D2
'''
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
INF = float('inf')
def sieve(N):
'''return all primes in [2..N] in O(N)'''
primes = []
mpf = [0]*(N+1) # min prime factor
for i in range(2, N+1):
if mpf[i] == 0:
primes.append(i)
mpf[i] = i
for p in primes:
if p*i > N or p > mpf[i]: break # mpf[p*i] <= mpf[i] < p
mpf[p*i] = p # once per composite number
return primes, mpf
# https://codeforces.com/contest/1614/submission/137008425
def solve(N, A):
MAX = max(A)
primes, mpf = sieve(MAX + 1)
# F[a] = all unique prime factors of a
F = {}
def get_factors(a):
if a in F: return F[a]
facs = []
while a > 1:
facs.append(mpf[a])
while facs[-1] == mpf[a]: a //= mpf[a]
return facs
# C[f] = num elements in A divisible by f
# think of primes as axes and numbers as points with coordinates = powers of primes
# for each possible factor f, want to calc how many points a in A have all coordinates >= f
C = [0]*(MAX+1)
for a in A: C[a] += 1
# i.e. for each point a, want to increment count for each b inside the cube 0..a
# to ensure a increments each b once and only once, there has to be a unique counting path from a to b
# the below procedure traverses each axis one by one, hence ensures unique paths
# note that the order of primes/axes are therefore not important
# it's easiest to visualize a 2D lattice (2 primes)
for p in primes:
for a in range(MAX//p, 0, -1):
C[a] += C[a*p]
# let g[i]=gcd(a[1]..a[i]) for i=1..N
# then g[1], g[2]...., g[N] is non-increasing, g[i] % g[i+1] == 0
# want to max SUM_i g[i]
# dp(g, p) = max gcd sum from this point onward where
# * g is the next gcd
# * p numbers already placed
# * memo[g] = dp(f, C[g]) over all factors f of g
# --> max gcd sum onwards after choosing g as first gcd
def dp(g, p=0, memo={}):
if g == 1: return N-p
if g not in memo:
facs = get_factors(g)
memo[g] = max(dp(g//f, C[g], memo) for f in facs)
# note previous p numbers are all multiples of g
# so there are C[g]-p multiples of g left to place
return memo[g] + g*(C[g]-p)
# try each possible g[1]
res = max(dp(a) for a in A)
return res
def main():
N = int(input())
A = list(map(int, input().split()))
out = solve(N, A)
output(f'{out}\n')
if __name__ == '__main__':
main()
|
1637925300
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["3", "-1"]
|
c5592080d0f98bf8d88feb4d98762311
|
NoteIn the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
|
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.
|
If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.
|
The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_033.jsonl
|
bd904a83bac9b163c1f12fe51045a011
|
512 megabytes
|
["6\n1 2\n2 3\n2 4\n4 5\n1 6", "7\n1 2\n1 3\n3 4\n1 5\n5 6\n6 7"]
|
PASSED
|
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()
def main():
n = II()
d = collections.defaultdict(set)
for _ in range(n-1):
a,b = LI()
d[a].add(b)
d[b].add(a)
memo = [-1] * (n+1)
def path(t,s):
ps = set()
dt = list(d[t])
for k in dt:
if memo[k] < 0:
continue
ps.add(memo[k])
if s == -1 and len(ps) == 2:
memo[t] = sum(ps) + 2
return memo[t]
if len(ps) > 1:
return -t
if len(ps) == 0:
memo[t] = 0
return 0
memo[t] = list(ps)[0] + 1
return memo[t]
def _path(tt,ss):
f = [False] * (n+1)
q = [(tt,ss)]
tq = []
qi = 0
while len(q) > qi:
t,s = q[qi]
for k in d[t]:
if k == s or memo[k] >= 0:
continue
q.append((k,t))
qi += 1
for t,s in q[::-1]:
r = path(t,s)
if r < 0:
return r
return memo[tt]
t = _path(1,-1)
if t < 0:
t = _path(-t,-1)
if t > 0:
while t%2 == 0:
t//=2
return t
return -1
print(main())
|
1487059500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1", "2"]
|
a0a6cdda2ce201767bf5418f445a44eb
|
NoteIn the first example you need to move the first chip by $$$2$$$ to the right and the second chip by $$$1$$$ to the right or move the third chip by $$$2$$$ to the left and the second chip by $$$1$$$ to the left so the answer is $$$1$$$.In the second example you need to move two chips with coordinate $$$3$$$ by $$$1$$$ to the left so the answer is $$$2$$$.
|
You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$); move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).
|
Print one integer — the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate.
|
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of chips. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th chip.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_004.jsonl
|
467c1f4c308fff6b7594758f24d6b94a
|
256 megabytes
|
["3\n1 2 3", "5\n2 2 2 3 3"]
|
PASSED
|
m=input()
n=input()
c1=0
c2=0
k=n.split(" ")
for mm in k:
if(int(mm)%2==0):
c1+=1
else:
c2+=1
if(c1>c2):
print(c2)
else:
print(c1)
|
1567175700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4", "-1"]
|
6126d9533abd466545d8153233b14192
|
NoteIn the second sample test one of the progressions contains only powers of two, the other one contains only powers of three.
|
Geometric progression with the first element a and common ratio b is a sequence of numbers a, ab, ab2, ab3, ....You are given n integer geometric progressions. Your task is to find the smallest integer x, that is the element of all the given progressions, or else state that such integer does not exist.
|
If the intersection of all progressions is empty, then print - 1, otherwise print the remainder of the minimal positive integer number belonging to all progressions modulo 1000000007 (109 + 7).
|
The first line contains integer (1 ≤ n ≤ 100) — the number of geometric progressions. Next n lines contain pairs of integers a, b (1 ≤ a, b ≤ 109), that are the first element and the common ratio of the corresponding geometric progression.
|
standard output
|
standard input
|
Python 2
|
Python
| 3,200 |
train_034.jsonl
|
06762491a581df862d3167c84537c143
|
256 megabytes
|
["2\n2 2\n4 1", "2\n2 2\n3 3"]
|
PASSED
|
def primes(n):
size = n/3 + (n%6==2)
plist = size * [True]
plist[0] = False
for i in xrange(int(n**0.5)/3+1):
if plist[i]:
k=3*i+1|1
for j in xrange((k*k)/3,size,2*k):
plist[j] = False
for j in xrange((k*k+4*k-2*k*(i&1))/3,size,2*k):
plist[j] = False
ans = [2,3]
for i in xrange(size):
if plist[i]:
ans.append(3*i+1|1)
return ans
def solve():
mod = 1000000007
plist = primes(31700)
instring = """2
2 2
4 1"""
n = int(raw_input())
alist = []
blist = []
for i in xrange(n):
a,b = [int(x) for x in raw_input().split()]
alist.append(a)
blist.append(b)
# break down the primes
amaps = []
bmaps = []
for i in xrange(n):
a,b = alist[i], blist[i]
amap = dict()
bmap = dict()
for p in plist:
if p*p > a:
if a > 1:
amap[a] = 1
bmap[a] = 0
break
if a%p == 0:
count = 1
a /= p
while a%p == 0:
count += 1
a /= p
amap[p] = count
bmap[p] = 0
for p in plist:
if p*p > b:
if b > 1:
if b not in bmap:
amap[b] = 0
bmap[b] = 1
break
if b%p == 0:
count = 1
b /= p
while b%p == 0:
count += 1
b /= p
if p not in bmap:
amap[p] = 0
bmap[p] = count
amaps.append(amap)
bmaps.append(bmap)
#print amaps
#print bmaps
# check each a, see if any works
for i in xrange(n):
a = alist[i]
amap = amaps[i]
works = True
for j in xrange(n):
if alist[j] == a:
continue
constrained = -1
amapj = amaps[j]
for p in amapj:
if p not in amap:
works = False
if not works:
break
bmapj = bmaps[j]
for (p,c) in amap.iteritems():
need = c
if p in amapj:
need -= amapj[p]
add = 0
if p in bmapj:
add = bmapj[p]
if need == 0 and add == 0:
continue
if need < 0 or (add==0 and need>0) or need%add != 0:
works = False
break
index = need / add
if constrained == -1:
constrained = index
elif constrained != index:
works = False
break
if works:
print a
return True
#print "Looks like no a works..."
# make sure all seqs use same primes
for i in xrange(n):
for j in xrange(i+1,n):
if amaps[i].keys() != amaps[j].keys():
return False
#print "All them primes check out dude"
# look for a diff in prime alloc in two b's (ratio diff), use to solve equation
pkeys = amaps[0].keys()
for i in xrange(len(pkeys)):
p1 = pkeys[i]
for j in xrange(i+1,len(pkeys)):
p2 = pkeys[j]
for k in xrange(n):
for l in xrange(k+1,n):
#diff1 = bmaps[k][p1] - bmaps[l][p1]
#diff2 = bmaps[k][p2] - bmaps[l][p2]
a1p1 = amaps[k][p1]
b1p1 = bmaps[k][p1]
a1p2 = amaps[k][p2]
b1p2 = bmaps[k][p2]
a2p1 = amaps[l][p1]
b2p1 = bmaps[l][p1]
a2p2 = amaps[l][p2]
b2p2 = bmaps[l][p2]
q = b1p1
s = b2p1
r = b1p2
t = b2p2
c1 = a2p1 - a1p1
c2 = a2p2 - a1p2
if q*t == r*s:
if r*c1 == q*c2:
continue
else:
return False
x3 = s*r - q*t
c3 = q*c2 - r*c1
if c3 % x3 != 0:
return False
sol_l = c3 / x3
# check if it works for all sequences
pmap = dict(amaps[l])
for key, value in bmaps[l].iteritems():
pmap[key] += sol_l*value
for o in xrange(n):
amap = amaps[o]
bmap = bmaps[o]
index = -1
for key, value in pmap.iteritems():
need = value - amap[key]
add = bmap[key]
if need == 0 and add == 0:
continue
if need < 0 or (need > 0 and add == 0):
return False
if need % add != 0:
return False
mustbe = need / add
if index == -1:
index = mustbe
elif index != mustbe:
return False
print alist[l] * pow(blist[l],sol_l,mod) % mod
return True
'''
if diff1 != diff2:
print "We got one!"
a1p1 = amaps[k][p1]
b1p1 = bmaps[k][p1]
a1p2 = amaps[k][p2]
b1p2 = bmaps[k][p2]
a2p1 = amaps[l][p1]
b2p1 = bmaps[l][p1]
a2p2 = amaps[l][p2]
b2p2 = bmaps[l][p2]
#print "%d + %d*i = %d + %d*j" % (a1p1,b1p1,a2p1,b2p1)
#print "%d + %d*i = %d + %d*j" % (a1p2,b1p2,a2p2,b2p2)
q = b1p1
s = b2p1
r = b1p2
t = b2p2
c1 = a2p1 - a1p1
c2 = a2p2 - a1p2
#print "%d*i-%d*j = %d" % (q,s,c1)
#print "%d*i-%d*j = %d" % (r,t,c2)
if (r*c1)%q != 0 or (r*s)%q != 0:
#print "Non integer solution to cross"
return False
c3 = c2 - (r*c1)/q
x3 = (r*s)/q - t
if c3%x3 != 0:
#print "Non integer solution to cross"
return False
sol_l = c3 / x3
#print p1, p2, sol_l, (c1+s)*sol_l/q
# check if it works for all sequences
pmap = dict(amaps[l])
for key, value in bmaps[l].iteritems():
pmap[key] += value
for o in xrange(n):
amap = amaps[o]
bmap = bmaps[o]
index = -1
for key, value in pmap.iteritems():
need = value - amap[key]
add = bmap[key]
if need == 0 and add == 0:
continue
if need < 0 or (need > 0 and add == 0):
return False
if need % add != 0:
return False
mustbe = need / add
if index == -1:
index = mustbe
elif index != mustbe:
return False
print alist[l] * pow(blist[l],sol_l,mod) % mod
return True
'''
# if no diffs, use mod sys solver
eea = lambda b,s,w=1,x=0,y=0,z=1:(b,w,x)if s==0 else eea(s,b%s,y,z,w-b/s*y,x-b/s*z)
def solve_mod_sys(eqs):
if len(eqs) == 1: return eqs
a,m1 = eqs.pop()
b,m2 = eqs.pop()
lhs,rhs = m1,b-a
gcd, m1inv = eea(m1,m2)[:2]
if (gcd > 1):
if rhs%gcd == 0:
rhs/=gcd
m1/=gcd
m2/=gcd
m1inv = eea(m1,m2)[1]
else:
return False
rhs = m1inv*rhs%m2
c = a + rhs*lhs
m3 = m2*lhs
eqs.append((c,m3))
return solve_mod_sys(eqs)
pkey = amaps[0].keys()[0]
equations = []
for i in xrange(n):
start = amaps[i][pkey]
step = bmaps[i][pkey]
equations.append((start,step))
res = solve_mod_sys(equations)
if res == False:
return False
else:
x,m = res[0]
x /= bmaps[0][pkey]
solution = alist[0]
for p in bmaps[0]:
solution *= pow(p,x*bmaps[0][p],mod)
print solution % mod
return True
if not solve():
print -1
|
1440261000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["00\n01\n11111\n1010"]
|
679a1e455073d3ea3856aa16516ba8ba
|
NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$.
|
Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$="0101" the period is $$$k=2$$$, for $$$s$$$="0000" the period is $$$k=1$$$, for $$$s$$$="010" the period is $$$k=2$$$, for $$$s$$$="0011" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that: String $$$s$$$ consists only of 0's and 1's; The length of $$$s$$$ doesn't exceed $$$2 \cdot |t|$$$; String $$$t$$$ is a subsequence of string $$$s$$$; String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$="011" is a subsequence of $$$s$$$="10101".
|
Print one string for each test case — string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.
|
The first line contains single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting only of 0's and 1's.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_000.jsonl
|
c21eb008ed077af0fd3539cb1cb2dacb
|
256 megabytes
|
["4\n00\n01\n111\n110"]
|
PASSED
|
t=int(input())
for i in range(t):
t=input()
one=t.count('1')
zero=t.count('0')
if(zero>0 and one>0):
if(zero>=one):
print('01'*len(t))
else:
print('10'*len(t))
else:
print(t)
|
1587911700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds
|
["1 2 3 3 3 4 4 4 4 4", "2 2 2 1 1"]
|
5c17e01d02df26148e87dcba60ddf499
|
NoteFor the first test, the optimal answer is $$$f=-269$$$. Note that a larger $$$f$$$ value is possible if we ignored the constraint $$$\sum\limits_{i=1}^n b_i=k$$$.For the second test, the optimal answer is $$$f=9$$$.
|
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)You have completed many programming projects. In fact, there are exactly $$$n$$$ types of programming projects, and you have completed $$$a_i$$$ projects of type $$$i$$$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$Here, $$$b_i$$$ denotes the number of projects of type $$$i$$$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $$$0\le b_i \le a_i$$$ for all $$$i$$$.Your résumé only has enough room for $$$k$$$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $$$\sum\limits_{i=1}^n b_i=k$$$.Find values for $$$b_1,\ldots, b_n$$$ that maximize the value of $$$f(b_1,\ldots,b_n)$$$ while satisfying the above two constraints.
|
In a single line, output $$$n$$$ integers $$$b_1,\ldots, b_n$$$ that achieve the maximum value of $$$f(b_1,\ldots,b_n)$$$, while satisfying the requirements $$$0\le b_i\le a_i$$$ and $$$\sum\limits_{i=1}^n b_i=k$$$. If there are multiple solutions, output any. Note that you do not have to output the value $$$f(b_1,\ldots,b_n)$$$.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — the number of types of programming projects and the résumé size, respectively. The next line contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$) — $$$a_i$$$ is equal to the number of completed projects of type $$$i$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,700 |
train_013.jsonl
|
2c147c018b86f7ed4b89af37783e5ff1
|
256 megabytes
|
["10 32\n1 2 3 4 5 5 5 5 5 5", "5 8\n4 4 8 2 1"]
|
PASSED
|
import sys,math
range = xrange
input = raw_input
n, k = [int(x) for x in input().split()]
A = [int(x) for x in sys.stdin.read().split()]
# pick as few as possible
def f1(lam):
s = 0
for a in A:
# (b + 1) * (a + lam - (b + 1) ^ 2) - b * (a + lam - b ^ 2)
def g(b):
return a + lam - 3 * b * (b + 1) - 1
opti = 1/6.0 * (math.sqrt(max(0, 3 * (4 * (a + lam) - 1))) - 3)
l = min(max(0, int(opti) - 1), a)
r = max(min(a, int(opti) + 1), 0)
while l < r:
mid = l + r >> 1
der = g(mid)
if der > 0:
l = mid + 1
else:
r = mid
s += l
return s
# pick as few as possible
def f2(lam):
B = []
for a in A:
# (b + 1) * (a + lam - (b + 1) ^ 2) - b * (a + lam - b ^ 2)
def g(b):
return a + lam - 3 * b * (b + 1) - 1
opti = 1/6.0 * (math.sqrt(max(3 * (4 * (a + lam) - 1),0)) - 3)
l = min(max(0, int(opti) - 1), a)
r = max(min(a, int(opti) + 1), 0)
while l < r:
mid = l + r >> 1
der = g(mid)
if der > 0:
l = mid + 1
else:
r = mid
B.append(l)
return B
a = -4 * 10**18
b = 4 * 10**18
while a < b:
c = a + b + 1 >> 1
if f1(c) > k:
b = c - 1
else:
a = c
B = f2(a)
C = f2(a + 1)
k -= sum(B)
for i in range(n):
extra = min(C[i] - B[i], k)
k -= extra
B[i] += extra
import __pypy__, os
out = __pypy__.builders.StringBuilder()
for b in B:
out.append(str(b))
out.append(' ')
os.write(1, out.build())
|
1588775700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7"]
|
4f2c2d67c1a84bf449959b06789bb3a7
| null |
There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.
|
For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it. In the next m lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once.
|
The first line contains a positive integer t (1 ≤ t ≤ 200) — the number of testsets in the input. Each of the testsets is given in the following way. The first line contains two integers n and m (1 ≤ n ≤ 200, 0 ≤ m ≤ n·(n - 1) / 2) — the number of cities and the number of roads in Berland. The next m lines contain the description of roads in Berland. Each line contains two integers u and v (1 ≤ u, v ≤ n) — the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities. It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200. Pay attention that for hacks, you can only use tests consisting of one testset, so t should be equal to one.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_022.jsonl
|
c0b82ff3423cffa685c7741e1c184ca4
|
256 megabytes
|
["2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2"]
|
PASSED
|
from collections import defaultdict, Counter
T = int(input())
for _ in range(T):
global lst
N, M = map(int, input().split())
visit = set()
oddNodes = []
directed = []
G = defaultdict(list)
oriG = defaultdict(list)
Gra = [[0] * (N+1) for _ in range(N+1)]
deg = [0] * (N+1)
for k in range(M):
u, v = map(int, input().split())
Gra[u][v] += 1
Gra[v][u] += 1
deg[u] += 1
deg[v] += 1
# G[u].append(v)
# G[v].append(u)
# oriG[u].append(v)
# oriG[v].append(u)
ans = 0
for i in range(1, N+1):
if deg[i] % 2 == 0:
ans += 1
else:
oddNodes.append(i)
for i in range(0, len(oddNodes), 2):
# G[oddNodes[i]].append(oddNodes[i+1])
# G[oddNodes[i+1]].append(oddNodes[i])
Gra[oddNodes[i]][oddNodes[i+1]] += 1
Gra[oddNodes[i+1]][oddNodes[i]] += 1
deg[oddNodes[i]] += 1
deg[oddNodes[i+1]] += 1
def eulerPath(u):
stk = [u]
while stk:
u = stk.pop()
for i in range(1, N+1):
if Gra[u][i]:
Gra[u][i] -= 1
Gra[i][u] -= 1
directed.append((u, i))
stk.append(i)
break
for i in range(1, N+1):
eulerPath(i)
for i in range(0, len(oddNodes), 2):
# G[oddNodes[i]].append(oddNodes[i+1])
# G[oddNodes[i+1]].append(oddNodes[i])
Gra[oddNodes[i]][oddNodes[i+1]] += 1
Gra[oddNodes[i+1]][oddNodes[i]] += 1
# for i in oddNodes:
print(ans)
for u, v in directed:
if Gra[u][v] != 0:
Gra[u][v] -= 1
Gra[v][u] -= 1
else:
print(str(u) + " " + str(v))
|
1475494500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nYES\nYES"]
|
fbb4e1cf1cad47481c6690ce54b27a1e
|
NoteFor the first test case, we can increment the elements with an even index, obtaining the array $$$[1, 3, 1]$$$, which contains only odd numbers, so the answer is "YES".For the second test case, we can show that after performing any number of operations we won't be able to make all elements have the same parity, so the answer is "NO".For the third test case, all elements already have the same parity so the answer is "YES".For the fourth test case, we can perform one operation and increase all elements at odd positions by $$$1$$$, thus obtaining the array $$$[1001, 1, 1001, 1, 1001]$$$, and all elements become odd so the answer is "YES".
|
Given an array $$$a=[a_1,a_2,\dots,a_n]$$$ of $$$n$$$ positive integers, you can do operations of two types on it: Add $$$1$$$ to every element with an odd index. In other words change the array as follows: $$$a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \dots$$$. Add $$$1$$$ to every element with an even index. In other words change the array as follows: $$$a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \dots$$$.Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations.Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times.
|
Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
|
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 50$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^3$$$) — the elements of the array. Note that after the performed operations the elements in the array can become greater than $$$10^3$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_084.jsonl
|
8f350a81ad93c6635f2620eb065ecd4b
|
256 megabytes
|
["4\n\n3\n\n1 2 1\n\n4\n\n2 2 2 3\n\n4\n\n2 2 2 2\n\n5\n\n1000 1 1000 1 1000"]
|
PASSED
|
casenum = int(input())
def eachissame(numlist):
parity = numlist[0] % 2
for i in numlist:
if i % 2 != parity:
return False
return True
for i in range(casenum):
arraylen = int(input())
array = [int(x) for x in input().split()]
oddnums = [array[i] for i in range(arraylen) if i % 2 == 0]
evennums = [array[i] for i in range(arraylen) if i % 2 == 1]
#print(eachissame(oddnums), eachissame(evennums))
if (eachissame(oddnums) and eachissame(evennums)) or (len(oddnums) == 1 and len(evennums) == 1):
print("YES")
else:
print("NO")
|
1650551700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["6\n5\n375000012\n500000026\n958557139\n0\n49735962"]
|
ee4038a896565a82d2d0d5293fce2a18
|
NoteIn the first test case, the entire game has $$$3$$$ turns, and since $$$m = 3$$$, Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is $$$k = 2$$$, every turn.In the third test case, Alice has a strategy to guarantee a score of $$$\frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}$$$.In the fourth test case, Alice has a strategy to guarantee a score of $$$\frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}$$$.
|
This is the easy version of the problem. The difference is the constraints on $$$n$$$, $$$m$$$ and $$$t$$$. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers $$$n$$$, $$$m$$$ and $$$k$$$, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially $$$0$$$. The game consists of $$$n$$$ turns. Each turn, Alice picks a real number from $$$0$$$ to $$$k$$$ (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least $$$m$$$ out of the $$$n$$$ turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?
|
For each test case output a single integer number — the score of the optimal game 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 < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
|
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. Each test case consists of a single line containing the three integers, $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le m \le n \le 2000, 0 \le k < 10^9 + 7$$$) — the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_093.jsonl
|
739510c8a71e2896f4b8121002835310
|
256 megabytes
|
["7\n\n3 3 2\n\n2 1 10\n\n6 3 10\n\n6 4 10\n\n100 1 1\n\n4 4 0\n\n69 4 20"]
|
PASSED
|
mxn=10**9 + 7
def modI(a, m):
m0=m
y=0
x=1;
if(m==1): return 0;
while(a>1):
q=a//m;
t=m;
m=a%m;
a=t;
t=y;
y=x-q*y;
x=t;
if(x<0):x+=m0;
return x;
def fastfrac(a,b,M):
numb = modI(b,M)
return ((a%M)*(numb%M))%M
for _ in range(int(input())):
n,m,k=map(int,input().split())
dp=[[0 for i in range(m+1)] for j in range(n+1)]
for i in range(1,n+1):
for j in range(1,m+1):
if i==j:
dp[i][j]=(k*i)%mxn
else:
dp[i][j]=fastfrac((dp[i-1][j]+dp[i-1][j-1])%mxn,2,mxn)
print(dp[n][m])
|
1642862100
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "3"]
|
dc044b8fe01b0a94638139cea034b1a8
|
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields $$$3$$$ and $$$5$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$. The graph for the second example is shown below. Farmer John must add a road between fields $$$2$$$ and $$$4$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$.
|
Bessie is out grazing on the farm, which consists of $$$n$$$ fields connected by $$$m$$$ bidirectional roads. She is currently at field $$$1$$$, and will return to her home at field $$$n$$$ at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $$$k$$$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field $$$1$$$ to field $$$n$$$. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!
|
Output one integer, the maximum possible length of the shortest path from field $$$1$$$ to $$$n$$$ after Farmer John installs one road optimally.
|
The first line contains integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le 2 \cdot 10^5$$$, $$$2 \le k \le n$$$) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the special fields. All $$$a_i$$$ are distinct. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between fields $$$x_i$$$ and $$$y_i$$$. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_022.jsonl
|
7d3adca4b7a738d4f862048a9a57bbb1
|
256 megabytes
|
["5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4", "5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5"]
|
PASSED
|
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
# 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")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')
# ------------------------------
def main():
n, m, k = RL()
spa = list(RL())
dic = defaultdict(set)
ds = 0
for _ in range(m):
a, b = RL()
dic[a].add(b)
dic[b].add(a)
def bfs(root):
rec = [0]*(n+1)
q = [(root, 0)]
da = [0]*(n+1)
rec[root] = 1
for i, d in q:
for nex in dic[i]:
if rec[nex]==0:
q.append((nex, d+1))
rec[nex] = 1
da[nex] = d+1
return da
star = bfs(1)
end = bfs(n)
res = end[1]
spa.sort(key=lambda i: star[i]-end[i])
ts = float('-inf')
disa = star[spa[0]]
dis = 0
# print(end, spa)
for i in spa[1:]:
dis = max(end[i]+1+disa, dis)
disa = max(disa, star[i])
# print(dis, disa, i)
print(min(res, dis))
if __name__ == "__main__":
main()
|
1581953700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["7", "4", "12"]
|
09da15ac242c9a599221e205d1b92fa9
|
NoteIn the first sample case, you can set $$$t_{1} =$$$ 'a', $$$t_{2} =$$$ 'b', $$$t_{3} =$$$ 'a' and pay $$$3 + 3 + 1 = 7$$$ coins, since $$$t_{3}$$$ is a substring of $$$t_{1}t_{2}$$$.In the second sample, you just need to compress every character by itself.In the third sample, you set $$$t_{1} = t_{2} =$$$ 'a', $$$t_{3} =$$$ 'aa' and pay $$$10 + 1 + 1 = 12$$$ coins, since $$$t_{2}$$$ is a substring of $$$t_{1}$$$ and $$$t_{3}$$$ is a substring of $$$t_{1} t_{2}$$$.
|
Suppose you are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.To compress the string, you have to represent $$$s$$$ as a concatenation of several non-empty strings: $$$s = t_{1} t_{2} \ldots t_{k}$$$. The $$$i$$$-th of these strings should be encoded with one of the two ways: if $$$|t_{i}| = 1$$$, meaning that the current string consists of a single character, you can encode it paying $$$a$$$ coins; if $$$t_{i}$$$ is a substring of $$$t_{1} t_{2} \ldots t_{i - 1}$$$, then you can encode it paying $$$b$$$ coins. A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $$$s$$$.
|
Output a single integer — the smallest possible number of coins you need to spend to compress $$$s$$$.
|
The first line contains three positive integers, separated by spaces: $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \leq n, a, b \leq 5000$$$) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before. The second line contains a single string $$$s$$$, consisting of $$$n$$$ lowercase English letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_012.jsonl
|
4541e68a238233a7f923adb56314badb
|
256 megabytes
|
["3 3 1\naba", "4 1 1\nabcd", "4 10 1\naaaa"]
|
PASSED
|
import sys
sys.setrecursionlimit(10 ** 8)
n, a, b = map(int,input().split())
s = input()
def calc(j):
if (j >= n): return 0
if (dp[j] != -1): return dp[j]
dp[j] = a + calc(j + 1)
lo = j
hi = n
farthest = -1
# finding best string to reach from a given j such that it eist before i using binary search
while (lo < hi):
mid = (lo + hi) // 2
if (s[j:mid + 1] in s[0:j]):
farthest = mid
lo = mid + 1
else:
hi = mid
if (farthest != -1): dp[j] = min(dp[j], b + calc(farthest + 1))
return dp[j]
dp = [-1 for i in range(n + 5)]
print(calc(0))
|
1551627300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["YES\nNO"]
|
bcdd7862b718d6bcc25c9aba8716d487
|
NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
|
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.
|
For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_004.jsonl
|
6b5201810dc038313e30aab9163944f4
|
256 megabytes
|
["2\n13\n7818005553535\n11\n31415926535"]
|
PASSED
|
for i in range(int(input())):
n = int(input())
s = input()
print('YES' if '8' in s and n - s.index('8') >= 11 else 'NO')
|
1557930900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["7", "12", "0"]
|
1eb41e764a4248744edce6a9e7e3517a
|
NoteIn the first example pairs $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(3, 1)$$$, $$$(3, 4)$$$, $$$(4, 2)$$$, $$$(4, 3)$$$ suffice. They produce numbers $$$451$$$, $$$4510$$$, $$$110$$$, $$$1045$$$, $$$1012$$$, $$$121$$$, $$$1210$$$, respectively, each of them is divisible by $$$11$$$.In the second example all $$$n(n - 1)$$$ pairs suffice.In the third example no pair is sufficient.
|
You are given an array $$$a$$$, consisting of $$$n$$$ positive integers.Let's call a concatenation of numbers $$$x$$$ and $$$y$$$ the number that is obtained by writing down numbers $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, a concatenation of numbers $$$12$$$ and $$$3456$$$ is a number $$$123456$$$.Count the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.
|
Print a single integer — the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le k \le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_041.jsonl
|
ece6a7eed64e489890b03bcf111c4557
|
256 megabytes
|
["6 11\n45 1 10 12 11 7", "4 2\n2 78 4 10", "5 2\n3 7 19 3 3"]
|
PASSED
|
from sys import stdin, stdout
ti = lambda : stdin.readline().strip()
os = lambda i : stdout.write(str(i) + '\n')
ma = lambda fxn, ti : map(fxn, ti.split())
ol = lambda arr : stdout.write(' '.join(element for element in arr) + '\n')
olws = lambda arr : stdout.write(''.join(element for element in arr) + '\n')
class Digit:
def __init__(self):
self.count = {}
def increment(self, k):
if self.count.has_key(k):
got = self.count[k]
self.count[k] += 1
else:
self.count[k] = 1
def found(self, k):
if self.count.has_key(k):
return self.count[k]
else:
return 0
n, mod = ma(int, ti())
array = ma(int, ti())
ans = 0
digits = [None]*11
for i in range(11):
digits[i] = Digit()
for i in range(n):
temp = array[i]%mod
for j in range(10):
temp *= 10
temp %= mod
digits[j+1].increment(temp)
for i in range(n):
temp = array[i]
count = 0
while temp>0:
temp /= 10
count += 1
find = mod-array[i]%mod
find %= mod
ans += digits[count].found(find)
for i in range(n):
temp1 = array[i]%mod
temp2 = array[i]
while temp2 > 0:
temp2 /= 10
temp1 *= 10
temp1 %= mod
if ((temp1 + array[i])%mod == 0):
ans -= 1
os(ans)
|
1535122200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO"]
|
3ef23f114be223255bd10131b2375b86
|
NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement.
|
Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.
|
For each test case, output "YES" in a separate line, if the first player wins. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \le n \le 100, 1 \le k_1 \le n - 1, 1 \le k_2 \le n - 1, k_1 + k_2 = n$$$) — the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \dots, a_{k_1}$$$ ($$$1 \le a_i \le n$$$) — the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \dots, b_{k_2}$$$ ($$$1 \le b_i \le n$$$) — the values of cards of the second player. It is guaranteed that the values of all cards are different.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800 |
train_010.jsonl
|
87e6dc2700e8eb0e22bb256115ef2f6e
|
256 megabytes
|
["2\n2 1 1\n2\n1\n5 2 3\n2 3\n1 4 5"]
|
PASSED
|
t=input()
for i in xrange(t):
n,k1,k2=map(int, raw_input().split())
a=map(int, raw_input().split())
b=map(int, raw_input().split())
if n in a:
print "YES"
else:
print "NO"
|
1577628300
|
[
"math",
"games"
] |
[
1,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0", "5555555550"]
|
409b27044d5ec97b5315c92d4112376f
|
NoteIn the first test you can make only one number that is a multiple of 90 — 0.In the second test you can make number 5555555550, it is a multiple of 90.
|
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
|
In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.
|
The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_003.jsonl
|
58e47b5256fc03df2924d9a99eb27be5
|
256 megabytes
|
["4\n5 0 5 0", "11\n5 5 5 5 5 5 5 5 0 5 5"]
|
PASSED
|
n=int(input())
l=list(map(int,input().split()))
a,b=0,0
s=""
for i in l:
if i==5:
a=a+1
if i==0:
b=b+1
for i in range(a//9):
s=s+"555555555"
if a<9:
if b>0:
s="0"
else:
for i in range(b):
s=s+"0"
if b>0:
print(s)
else:
print("-1")
|
1380900600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["NNOTA\nAANN\nAAAAAA\nTNNTAOOA"]
|
f17445aca588e5fbc1dc6a595c811bd6
|
NoteFor the first testcase, it takes $$$7$$$ seconds for Anton's body to transform NNOTA to ANTON: NNOTA $$$\to$$$ NNOAT $$$\to$$$ NNAOT $$$\to$$$ NANOT $$$\to$$$ NANTO $$$\to$$$ ANNTO $$$\to$$$ ANTNO $$$\to$$$ ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes $$$2$$$ seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.
|
After rejecting $$$10^{100}$$$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string $$$a$$$ which only contains the characters "ANTON" (there are only $$$4$$$ distinct characters). Errorgorn can change Anton's DNA into string $$$b$$$ which must be a permutation of $$$a$$$. However, Anton's body can defend against this attack. In $$$1$$$ second, his body can swap $$$2$$$ adjacent characters of his DNA to transform it back to $$$a$$$. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $$$B$$$. Can you help him?
|
For each testcase, print a single string, $$$b$$$. If there are multiple answers, you can output any one of them. $$$b$$$ must be a permutation of the string $$$a$$$.
|
The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 100000)$$$ — the number of testcases. The first and only line of each testcase contains $$$1$$$ string $$$a$$$ ($$$1 \leq |a| \leq 100000$$$). $$$a$$$ consists of only the characters "A", "N", "O" and "T". It is guaranteed that the sum of $$$|a|$$$ over all testcases does not exceed $$$100000$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_105.jsonl
|
fe06f76b8f10ce8623638aa7d8174ff4
|
512 megabytes
|
["4\nANTON\nNAAN\nAAAAAA\nOAANTTON"]
|
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 bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return list(map(str,input().strip().split(" ")))
def le(): return list(map(int,input().split()))
def rc(): return map(float,input().split())
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def joron(L):
return('\n'.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
boi=int(998244353)
doi=int(1e9+7)
hoi=int(1e5+50)
poi=int(10+2**20)
y="YES"
n="NO"
def gosa(x, y):
while(y):
x, y = y, x % y
return x
L=[0]*hoi
M=[0]*hoi
def bulli(x):
return bin(x).count('1')
def iu():
import sys
import math as my
import functools
input=sys.stdin.readline
from collections import deque, defaultdict
bec=-1
e=[]
t=list(st())
de=""
U=[]
V=[]
zs=defaultdict(int)
m=len(t)
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
for h in range(1,5):
if(i!=j and i!=k and h!=i and j!=k and j!=h and h!=k):
df=0
for p in range(1,6):
M[p]=0
L[ord('A')]=i
L[ord('N')]=j
L[ord('T')]=k
L[ord('O')]=h
for fg in range(1,1+m):
df=df+M[L[ord(t[fg-1])]+1]
for dg in range(1,1+L[ord(t[fg-1])]):
M[dg]=1+M[dg]
if(bec<df):
pp=i
qq=j
rr=k
ss=h
bec=df
L[ord('A')]=pp
L[ord('N')]=qq
L[ord('T')]=rr
L[ord('O')]=ss
e.append([L[ord('A')],'A'])
e.append([L[ord('N')],'N'])
e.append([L[ord('T')],'T'])
e.append([L[ord('O')],'O'])
e.sort()
#print(e)
for i in e:
de+=(t.count(i[1]))*i[1]
print(de)
def main():
for i in range(so()):
#print("Case #"+str(i+1)+": ",end="")
iu()
# 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()
|
1622210700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
1 second
|
["6", "20"]
|
240a2b88ded6016d0fd7157d0ee2beea
|
NoteIn the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11).
|
The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.
|
Print a single number — the answer to the problem.
|
The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,200 |
train_008.jsonl
|
9c43fb84415cac25180fee36d0902b6b
|
256 megabytes
|
["bearbtear", "bearaabearc"]
|
PASSED
|
import sys, math
def rs():
return sys.stdin.readline().strip()
def ri():
return int(sys.stdin.readline().strip())
def ras():
return list(sys.stdin.readline().strip())
def rai():
return map(int,sys.stdin.readline().strip().split())
def solve():
# s = "bear"*(5000/4)
s = rs()
l = len(s)
sm = 0
bears = 0
c = 0
for x in xrange(l - 3):
if s[x] == "b" and s[x+1] == "e" and s[x+2] == "a" and s[x+3] == "r":
if bears:
con = (x-c)
else:
con = (x+1)
sm += con*(l-3-x)
c = x
bears +=1
return sm
print solve()
|
1390577700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds
|
["2\n16\n0\n6\n16"]
|
f48d55c60c12136979fe6db1e15c6053
|
NoteLet's consider the example test.In the first test case, one way to obtain a score of $$$2$$$ is the following one: choose $$$a_7 = 1$$$ and $$$a_4 = 2$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{2} \rfloor = 0$$$, the array becomes $$$[1, 1, 1, 1, 3]$$$; choose $$$a_1 = 1$$$ and $$$a_5 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[1, 1, 1]$$$; choose $$$a_1 = 1$$$ and $$$a_2 = 1$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{1} \rfloor = 1$$$, the array becomes $$$[1]$$$; add the remaining element $$$1$$$ to the score, so the resulting score is $$$2$$$. In the second test case, no matter which operations you choose, the resulting score is $$$16$$$.In the third test case, one way to obtain a score of $$$0$$$ is the following one: choose $$$a_1 = 1$$$ and $$$a_2 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[3, 7]$$$; choose $$$a_1 = 3$$$ and $$$a_2 = 7$$$ for the operation; the score becomes $$$0 + \lfloor \frac{3}{7} \rfloor = 0$$$, the array becomes empty; the array is empty, so the score doesn't change anymore. In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: $$$4 + 2 = 6$$$.
|
You are given an array $$$a$$$ of $$$n$$$ integers, and another integer $$$k$$$ such that $$$2k \le n$$$.You have to perform exactly $$$k$$$ operations with this array. In one operation, you have to choose two elements of the array (let them be $$$a_i$$$ and $$$a_j$$$; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add $$$\lfloor \frac{a_i}{a_j} \rfloor$$$ to your score, where $$$\lfloor \frac{x}{y} \rfloor$$$ is the maximum integer not exceeding $$$\frac{x}{y}$$$.Initially, your score is $$$0$$$. After you perform exactly $$$k$$$ operations, you add all the remaining elements of the array to the score.Calculate the minimum possible score you can get.
|
Print one integer — the minimum possible score you can get.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$0 \le k \le \lfloor \frac{n}{2} \rfloor$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_087.jsonl
|
3a6517e91434d732be16912e079a43a8
|
512 megabytes
|
["5\n7 3\n1 1 1 2 1 3 1\n5 1\n5 5 5 5 5\n4 2\n1 3 3 7\n2 0\n4 2\n9 2\n1 10 10 1 10 2 7 10 3"]
|
PASSED
|
cases = int(input())
finalstring = ''
for case in range(cases):
nk = [int(x) for x in input().split(' ')]
caselist = [int(x) for x in input().split(' ')]
caselist.sort(reverse=True)
score = 0
for case in range(nk[1]):
score+=int(caselist[case+nk[1]]/caselist[case])
finalstring += f'{sum(caselist[2*nk[1]:])+score}\n'
print(finalstring)
|
1639492500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["11", "4"]
|
8476fd1d794448fb961248cd5afbc92d
| null |
You are given a tree, which consists of $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles. Example of a tree. Vertices are numbered from $$$1$$$ to $$$n$$$. All vertices have weights, the weight of the vertex $$$v$$$ is $$$a_v$$$.Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $$$k$$$ or less between them in this subset.
|
Print one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than $$$k$$$.
|
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 200$$$) — the number of vertices in the tree and the distance restriction, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$), where $$$a_i$$$ is the weight of the vertex $$$i$$$. The next $$$n - 1$$$ lines contain edges of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_014.jsonl
|
26c0930853a343431dd92fae6f53baf4
|
256 megabytes
|
["5 1\n1 2 3 4 5\n1 2\n2 3\n3 4\n3 5", "7 2\n2 1 2 1 2 1 1\n6 4\n1 5\n3 1\n2 3\n7 5\n7 4"]
|
PASSED
|
visited = [0]*205
dp = [[0]*205 for i in range(205)]
def dfs(node,g):
sons = []
for nb in g[node]:
if not visited[nb]:
visited[nb] = 1
dfs(nb,g)
sons.append(nb)
dp[node][0] = ws[node-1]
for s in sons:
dp[node][0] += dp[s][k]
ls = len(sons)
# print node,sons,g[node]
for i in range(ls):
for j in range(k+1):
d2 = max(k-1-j,0)
maxd = j+1
if d2+1<maxd and ls>1:
d2 = j
tmp = dp[sons[i]][j]
for s in range(ls):
if s==i:
continue
tmp += dp[sons[s]][d2]
dp[node][maxd] = max(dp[node][maxd],tmp)
for i in range(k)[::-1]:
dp[node][i] = max(dp[node][i],dp[node][i+1])
n,k = map(int,raw_input().split(" "))
ws = map(int,raw_input().split(" "))
edges = []
def add(dic,k,v):
if not dic.has_key(k):
dic[k] = v
else:
dic[k] += v
g = {}
for i in range(n-1):
a,b = map(int,raw_input().split(" "))
edges.append((a,b))
add(g,a,[b])
add(g,b,[a])
root = 1
visited[root] = 1
if g.has_key(root):
dfs(root,g)
print dp[root][0]
else:
print ws[root-1]
|
1571754900
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["? 1\n? 2\n? 3\n? 4\n? 5\n! 81"]
|
8aba8c09ed1b1b25fa92cdad32d6fec3
|
NoteYou can read more about singly linked list by the following link: https://en.wikipedia.org/wiki/Linked_list#Singly_linked_list The illustration for the first sample case. Start and finish elements are marked dark.
|
This is an interactive problem.You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the integer value in this element, and nexti that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if nexti ≠ - 1, then valuenexti > valuei.You are given the number of elements in the list n, the index of the first element start, and the integer x.You can make up to 2000 queries of the following two types: ? i (1 ≤ i ≤ n) — ask the values valuei and nexti, ! ans — give the answer for the problem: the minimum integer, greater than or equal to x, or ! -1, if there are no such integers. Your program should terminate after this query. Write a program that solves this problem.
|
To print the answer for the problem, print ! ans, where ans is the minimum integer in the list greater than or equal to x, or -1, if there is no such integer.
|
The first line contains three integers n, start, x (1 ≤ n ≤ 50000, 1 ≤ start ≤ n, 0 ≤ x ≤ 109) — the number of elements in the list, the index of the first element and the integer x.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_007.jsonl
|
b139fa626aaf0e9a3f39a1e7a2572264
|
256 megabytes
|
["5 3 80\n97 -1\n58 5\n16 2\n81 1\n79 4"]
|
PASSED
|
from random import sample
def R():
return map(int, input().split())
def ask(i):
print('?', i, flush=True)
v, nxt = R()
if v < 0:
exit()
return v, nxt
def ans(v):
print('!', v)
exit()
n, s, x = R()
mv = -1
i = s
S = 800
q = range(1, n + 1)
if n > S:
q = sample(q, S)
if s not in q:
q[0] = s
for i in q:
v, nxt = ask(i)
if v == x or i == s and v > x:
ans(v)
if v < x:
if nxt < 0:
ans(-1)
if v > mv:
mv, mnxt = v, nxt
while mv < x and mnxt >= 1:
mv, mnxt = ask(mnxt)
ans(mv if mv >= x else -1)
|
1503592500
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
5 seconds
|
["0", "0", "1"]
|
560d70425c765c325f412152c8124d2d
|
NoteIn the first example only one province exists, so it is not necessary to build any tunnels or roads.In the second example two provinces exist. It is possible to merge the provinces by building a tunnel between cities 1 and 3.In the third example at least one additional road is necessary. For example it is possible to build additional road between cities 1 and 2 and build two tunnels between cities 1 and 3, 2 and 4 after that.
|
Vasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces. Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than k tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.
|
Print a single number, the minimum number of additional roads.
|
The first line contains three integers n, m and k (1 ≤ n, k ≤ 106, 0 ≤ m ≤ 106). Each of the next m lines contains two integers. They are the numbers of cities connected by a corresponding road. No road connects city to itself and there is at most one road between each pair of cities.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_059.jsonl
|
c930ed4d60cfc161a7bab429152e9249
|
256 megabytes
|
["3 3 2\n1 2\n2 3\n3 1", "4 2 2\n1 2\n3 4", "4 0 2"]
|
PASSED
|
import sys
rl=sys.stdin.readline
n,m,k=map(int,rl().split())
c = [-1]*n
def root(x):
p = x
while c[p]>=0: p=c[p]
while c[x]>=0:
t = c[x]
c[x] = p
x = t
return p
#def root(x):
# if c[x]<0: return x
# c[x]=root(c[x])
# return c[x]
for i in xrange(m):
x,y=rl().split()
f = root(int(x)-1)
t = root(int(y)-1)
if f==t: continue
if (c[f]&1): f,t=t,f
c[t]+=c[f]
c[f]=t
l,s,q=0,2,0
for i in xrange(n):
if c[i]>=0: continue
j=k if c[i]<-k else -c[i]
if j==1: l+=1
else: s+=j-2
q+=1
if l==1: print 0
elif k==1: print q-2;
elif l<=s: print 0;
else: print (l-s+1)/2;
|
1302422400
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3.500000000", "2", "3439.031415943"]
|
ca417ff967dcd4594de66ade1a06acf0
|
NoteIn the first example, Bob's counter has a 62.5% chance of being 3, a 25% chance of being 4, and a 12.5% chance of being 5.
|
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a skyscraper with height i are numbered 0 through i - 1.To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the i-th floor of one skyscraper with the i-th floor of another skyscraper if and only if there are no skyscrapers between them that have an i-th floor.Alice and Bob decide to count the number of skyscrapers.Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than h due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2i to his counter, where i is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and h = 2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (h = 2). Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.
|
Output a single real value giving the expected value of the Alice's counter if you were given Bob's counter, or Bob's counter if you were given Alice's counter. You answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
|
The first line of input will be a name, either string "Alice" or "Bob". The second line of input contains two integers n and h (2 ≤ n ≤ 30000, 0 ≤ h ≤ 30). If the name is "Alice", then n represents the value of Alice's counter when she reaches the rightmost skyscraper, otherwise n represents the value of Bob's counter when he reaches the rightmost skyscraper; h represents the highest floor number Bob is willing to use.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,800 |
train_037.jsonl
|
9b790c17b97d12a8be06594dea096ac1
|
256 megabytes
|
["Alice\n3 1", "Bob\n2 30", "Alice\n2572 10"]
|
PASSED
|
s=raw_input()
n,h=map(int,raw_input().split())
if s == "Bob": print n;exit()
ans=n
ti=1.0
for i in xrange(1,h+1):
ti *= 0.5
if ti < 0.1**50: break
tj = 1.0/(1.0-ti)
for j in xrange(1,n+1):
tj *= 1.0-ti
ans += (n-j)*tj*(ti-0.5*ti*(1.0+(j-1.0)*ti/(1.0-ti)))
print ans
|
1375549200
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["2", "8"]
|
609c531258612e58c4911c650e90891c
| null |
Kuzya started going to school. He was given math homework in which he was given an array $$$a$$$ of length $$$n$$$ and an array of symbols $$$b$$$ of length $$$n$$$, consisting of symbols '*' and '/'.Let's denote a path of calculations for a segment $$$[l; r]$$$ ($$$1 \le l \le r \le n$$$) in the following way: Let $$$x=1$$$ initially. For every $$$i$$$ from $$$l$$$ to $$$r$$$ we will consequently do the following: if $$$b_i=$$$ '*', $$$x=x*a_i$$$, and if $$$b_i=$$$ '/', then $$$x=\frac{x}{a_i}$$$. Let's call a path of calculations for the segment $$$[l; r]$$$ a list of all $$$x$$$ that we got during the calculations (the number of them is exactly $$$r - l + 1$$$). For example, let $$$a=[7,$$$ $$$12,$$$ $$$3,$$$ $$$5,$$$ $$$4,$$$ $$$10,$$$ $$$9]$$$, $$$b=[/,$$$ $$$*,$$$ $$$/,$$$ $$$/,$$$ $$$/,$$$ $$$*,$$$ $$$*]$$$, $$$l=2$$$, $$$r=6$$$, then the path of calculations for that segment is $$$[12,$$$ $$$4,$$$ $$$0.8,$$$ $$$0.2,$$$ $$$2]$$$.Let's call a segment $$$[l;r]$$$ simple if the path of calculations for it contains only integer numbers. Kuzya needs to find the number of simple segments $$$[l;r]$$$ ($$$1 \le l \le r \le n$$$). Since he obviously has no time and no interest to do the calculations for each option, he asked you to write a program to get to find that number!
|
Print a single integer — the number of simple segments $$$[l;r]$$$.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). The third line contains $$$n$$$ symbols without spaces between them — the array $$$b_1, b_2 \ldots b_n$$$ ($$$b_i=$$$ '/' or $$$b_i=$$$ '*' for every $$$1 \le i \le n$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,600 |
train_106.jsonl
|
869da5d6c010f857b6d363df21d28fb6
|
512 megabytes
|
["3\n1 2 3\n*/*", "7\n6 4 10 1 2 15 1\n*/*/*//"]
|
PASSED
|
import sys,math
from collections import defaultdict
N = 1000005
maxf = [0] * N
for i in range(2,int(math.sqrt(N))+2):
if maxf[i] == 0:
for j in range(i+i, N, i):
maxf[j] = i
for i in range(2, N):
if maxf[i] == 0: maxf[i] = i
n = int(sys.stdin.readline())
a = [int(i) for i in sys.stdin.readline().split()]
p = defaultdict(list)
l = [0]*n
r = 0
for idx, i in enumerate(sys.stdin.readline().strip()):
x = a[idx]
l[idx] = idx+1
if i == '*':
while x > 1:
p[maxf[x]].append(idx+1)
x//=maxf[x]
else:
while x > 1:
l[idx] = min(l[idx], p[maxf[x]].pop()) if p[maxf[x]] else 0
x//=maxf[x]
st = []
for i in range(n):
st.append(i+1)
while st and st[-1] > l[i]: st.pop()
r+=len(st)
print(r)
|
1635069900
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["0\n1", "0\n3\n2\n4\n1"]
|
5ef966b7d9fbf27e6197b074eca31b15
|
NoteThe tree from the second sample:
|
You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive. All the written labels are distinct. The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.
|
Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).
|
The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_011.jsonl
|
63c07907fa7dbcc961ddde96bfbd5e44
|
256 megabytes
|
["3\n1 2\n1 3", "6\n1 2\n1 3\n2 4\n2 5\n5 6"]
|
PASSED
|
data = input().rstrip().split()
n = int(data[0])
edges = []
g = {i+1: [] for i in range(n)}
leafes = set()
for _ in range(n-1):
data = input().rstrip().split()
a, b = int(data[0]), int(data[1])
a, b = sorted([a, b])
edges.append((a, b))
g[a].append(b)
g[b].append(a)
for k, v in g.items():
if len(leafes) == 3:
break
if len(v) == 1:
e = sorted([k, v[0]])
leafes.add(tuple(e))
counter = len(leafes)
l_counter = 0
to_print = []
for edge in edges:
a, b = edge
if edge in leafes:
to_print.append(l_counter)
l_counter += 1
else:
to_print.append(counter)
counter += 1
for p in to_print:
print(p)
|
1584196500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["YES\nabc", "NO", "YES\nxxxxxxy"]
|
64700ca85ef3b7408d7d7ad1132f8f81
|
NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
|
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
|
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
|
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_066.jsonl
|
9d64aede4bd7e0e878d70f4f09ab1eae
|
256 megabytes
|
["abc", "abcd", "xxxyxxx"]
|
PASSED
|
from collections import Counter
def is_prime(x):
if x < 2:
return 0
for i in range(2, x):
if x % i == 0:
return False
return True
def proc(s):
n = len(s)
same = set()
for p in range(2,n+1):
if not is_prime(p):
continue
if p * 2 > n:
continue
for i in range(2, n//p+1):
same.add(p*i)
same.add(p)
counter = Counter(s)
ch, count = counter.most_common(1)[0]
if count < len(same):
print("NO")
return
same = [x-1 for x in same]
w = [x for x in s]
for i in same:
if w[i] == ch:
continue
for j in range(n):
if j not in same and w[j] == ch:
tmp = w[j]
w[j] = w[i]
w[i] = tmp
break
print("YES")
print(''.join(w))
s = input()
proc(s)
|
1320333000
|
[
"number theory",
"strings"
] |
[
0,
0,
0,
0,
1,
0,
1,
0
] |
|
2 seconds
|
["2.683281573000", "2.267786838055"]
|
18b1814234b05bae56ea4446506b543b
|
NoteIn the first sample the jury should choose the following values: r1 = 3, p1 = 2, p2 = 1.
|
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1, x2, ..., xn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1, y2, ..., ym, and p2 will take a value from list z1, z2, ..., zk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A, B are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
|
Print a single real number — the sought value r2 with absolute or relative error of at most 10 - 6. It is guaranteed that the solution that meets the problem requirements exists.
|
The first input line contains an integer n and a sequence of integers x1, x2, ..., xn. The second input line contains an integer m and a sequence of integers y1, y2, ..., ym. The third input line contains an integer k and a sequence of integers z1, z2, ..., zk. The last line contains two integers A and B. All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,300 |
train_000.jsonl
|
6a6bb6cdaa6a0cc8db980f87b4189cd7
|
256 megabytes
|
["3 1 2 3\n1 2\n3 3 2 1\n1 2", "4 2 3 6 4\n2 1 2\n3 10 6 8\n2 1"]
|
PASSED
|
#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil, factorial, log,tan,pi,cos,sin,radians
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
from fractions import Fraction
from functools import reduce
from decimal import *
import string
import sys
import os
import re
inf = float('inf')
mod_ = int(1e9) + 7
mod = 998244353
def factors(n):
from functools import reduce
return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def sieve(m):
n=1
primes = {}
arr=set([])
for i in range(2, int(m ** 0.5) + 1):
a = n // i
b = m // i
for k in range(max(2, a), b + 1):
c = i * k
primes[c] = 1
for i in range(max(n, 2), m + 1):
if i not in primes:
arr.add(i)
return arr
class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def main():
r1=max(list(map(int,input().split()))[1:])
p1=max(list(map(int,input().split()))[1:])
p2=list(map(int,input().split()))[1:]
a,b=map(int,input().split())
r2=0
for j in range(len(p2)):
ans=r1*(b*p1/(b*p1+a*p2[j]))**0.5
r2=max(r2,ans)
print(r2)
# region fastio
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def gcd(x, y):
while y:
x, y = y, x % y
return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
1344267000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["abca", "aabbbcba", "abdbdccacbdbdccb", "cccccffffcccccffccfcffcccccfffff", "zz"]
|
bc145a67268b42c00835dc2370804ec9
|
NoteIn the first test, the lexicographically minimal xoration $$$t$$$ of $$$s =$$$"acba" is "abca". It's a xoration because, for $$$j = 3$$$, $$$t_0 = s_{0 \oplus j} = s_3 =$$$ "a"; $$$t_1 = s_{1 \oplus j} = s_2 =$$$ "b"; $$$t_2 = s_{2 \oplus j} = s_1 =$$$ "c"; $$$t_3 = s_{3 \oplus j} = s_0 =$$$ "a". There isn't any xoration of $$$s$$$ lexicographically smaller than "abca".In the second test, the minimal string xoration corresponds to choosing $$$j = 4$$$ in the definition of xoration.In the third test, the minimal string xoration corresponds to choosing $$$j = 11$$$ in the definition of xoration.In the fourth test, the minimal string xoration corresponds to choosing $$$j = 10$$$ in the definition of xoration.In the fifth test, the minimal string xoration corresponds to choosing either $$$j = 0$$$ or $$$j = 1$$$ in the definition of xoration.
|
You are given an integer $$$n$$$ and a string $$$s$$$ consisting of $$$2^n$$$ lowercase letters of the English alphabet. The characters of the string $$$s$$$ are $$$s_0s_1s_2\cdots s_{2^n-1}$$$.A string $$$t$$$ of length $$$2^n$$$ (whose characters are denoted by $$$t_0t_1t_2\cdots t_{2^n-1}$$$) is a xoration of $$$s$$$ if there exists an integer $$$j$$$ ($$$0\le j \leq 2^n-1$$$) such that, for each $$$0 \leq i \leq 2^n-1$$$, $$$t_i = s_{i \oplus j}$$$ (where $$$\oplus$$$ denotes the operation bitwise XOR).Find the lexicographically minimal xoration of $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
Print a single line containing the lexicographically minimal xoration of $$$s$$$.
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 18$$$). The second line contains a string $$$s$$$ consisting of $$$2^n$$$ lowercase letters of the English alphabet.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,800 |
train_105.jsonl
|
37d7150d1a865df973d983a4ad17cfe3
|
512 megabytes
|
["2\nacba", "3\nbcbaaabb", "4\nbdbcbccdbdbaaccd", "5\nccfcffccccccffcfcfccfffffcccccff", "1\nzz"]
|
PASSED
|
r=range
n=int(input())
N=1<<n
s=input()
a=sorted([ord(s[i])*N+i for i in r(N)])
for j in r(n):
p=1<<j;v=[0]*N;c=0;l=0
for i in r(N):
if a[i]//N>c:c=a[i]//N;l+=1
v[a[i]%N]=l
a=sorted([v[i]*N*N+v[i^p]*N+i for i in r(N)])
print(''.join([s[j^(a[0]%N)]for j in r(N)]))
|
1647764100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["6.4641016", "1.0000000", "3.2429391"]
|
e27cff5d681217460d5238bf7ef6a876
| null |
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.
|
Output a single number $$$R$$$ — the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$$$.
|
The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \leq n \leq 100$$$, $$$1 \leq r \leq 100$$$) — the number of the outer circles and the radius of the inner circle respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_006.jsonl
|
3cab2a35d6eaf514095fb2166c897ab7
|
256 megabytes
|
["3 1", "6 1", "100 100"]
|
PASSED
|
import math
def quadratic(a, b, c):
return (-1 * b + math.sqrt(b * b - 4 * a * c))/(2 * a)
PI = 3.14159265
x = input().split()
n = int(x[0])
r = int(x[1])
k = 360.0/n;
R = quadratic((2/(1-math.cos(k * PI/180)))-1, - 2 * r, - r * r);
print(R)
|
1547390100
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n3", "2\n4"]
|
bda7d223eabfcc519a60801012c58616
|
NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number.
|
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.
|
First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.
|
The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_035.jsonl
|
d16078dc38d3deb760329bde5ce21a2e
|
256 megabytes
|
["7 2\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n2 7", "6 4\n1 2\n2 3\n2 4\n4 5\n4 6\n2 4 5 6"]
|
PASSED
|
from heapq import *
INF = float('inf')
n, m = map(int, input().split())
adj = [[] for _ in range(n+1)]
wg= ng = [0 for _ in range(n+1)]
for _ in range(n-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
aaa = set(map(int, input().split()))
if len(aaa) == 1:print(min(aaa));print(0);exit()
rm = []
for i in range(n+1):
ng[i] = len(adj[i])
if i not in aaa and ng[i] == 1: rm.append(i)
for a in aaa: ng[a] = 0
def remove_node(index):
while adj[index]:
nx = adj[index].pop()
adj[nx].remove(index)
ng[nx] -= 1
if ng[nx] == 1: rm.append(nx)
ng[index] = 0
while rm: remove_node(rm.pop())
state = [0 for _ in range(n+1)]
que = [(min(aaa), None)]
res = 0
for _ in range(2):
deep = [0 for _ in range(n + 1)]
while que:
res += 1
root, proot = que.pop()
for nx in adj[root]:
if proot == nx:
continue
if _: state[nx] = root
deep[nx] = deep[root] + 1
que.append((nx, root))
if _: break
start = max(1,deep.index(max(deep)))
que = [(start, None)]
end = max(1, deep.index(max(deep)))
i = end
path = 1
while i != start:
path += 1
i = state[i]
print(min(start,end))
print(res -1 -path)
|
1446309000
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["7"]
|
dced53eba154855fa0f203178574990c
|
Note The sample is like this:
|
There is a square of size $$$10^6 \times 10^6$$$ on the coordinate plane with four points $$$(0, 0)$$$, $$$(0, 10^6)$$$, $$$(10^6, 0)$$$, and $$$(10^6, 10^6)$$$ as its vertices.You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
|
Print the number of pieces the square is divided into after drawing all the segments.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n, m \le 10^5$$$) — the number of horizontal segments and the number of vertical segments. The next $$$n$$$ lines contain descriptions of the horizontal segments. The $$$i$$$-th line contains three integers $$$y_i$$$, $$$lx_i$$$ and $$$rx_i$$$ ($$$0 < y_i < 10^6$$$; $$$0 \le lx_i < rx_i \le 10^6$$$), which means the segment connects $$$(lx_i, y_i)$$$ and $$$(rx_i, y_i)$$$. The next $$$m$$$ lines contain descriptions of the vertical segments. The $$$i$$$-th line contains three integers $$$x_i$$$, $$$ly_i$$$ and $$$ry_i$$$ ($$$0 < x_i < 10^6$$$; $$$0 \le ly_i < ry_i \le 10^6$$$), which means the segment connects $$$(x_i, ly_i)$$$ and $$$(x_i, ry_i)$$$. It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_019.jsonl
|
a08ae7ac349d92b8b4a979685f8076a0
|
384 megabytes
|
["3 3\n2 3 1000000\n4 0 4\n3 0 1000000\n4 0 1\n2 0 5\n3 1 1000000"]
|
PASSED
|
from __future__ import division, print_function
_interactive = False
def main():
MAX = 1000000
h, v = input_as_list()
hs = input_as_matrix(h, 3)
vs = input_as_matrix(v, 3)
hs += [(0, 0, MAX), (MAX, 0, MAX)]
vs += [(0, 0, MAX), (MAX, 0, MAX)]
# Event types
VST, H, VEN = (0, 1, 2)
events = []
for y, l, r in hs:
events += [(y, H, (l, r))]
for x, l, r in vs:
events += [(l, VST, x)]
events += [(r, VEN, x)]
events.sort()
debug_print(events)
st = SegmentTree([0]*MAX, func=lambda x, y: x+y)
newv = SortedList()
ans = 0
for y, t, d in events:
if t == VST:
newv.add(d)
elif t == H:
l, r = d
cnt = st.query(l, r+1)
ans += max(0, cnt-1)
if l == 0:
pos = newv.bisect_right(r)
for _ in range(pos):
x = newv.pop(0)
st[x] = 1
else:
pos = newv.bisect_left(l)
while len(newv) > pos:
x = newv.pop()
st[x] = 1
elif t == VEN:
newv.discard(d)
st[d] = 0
print(ans)
# Constants
INF = float('inf')
MOD = 10**9+7
alphabets = 'abcdefghijklmnopqrstuvwxyz'
# Python3 equivalent names
import os, sys, itertools
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
# print-flush in interactive problems
if _interactive:
flush = sys.stdout.flush
def printf(*args, **kwargs):
print(*args, **kwargs)
flush()
# Debug print, only works on local machine
LOCAL = "LOCAL_" in os.environ
debug_print = (print) if LOCAL else (lambda *x, **y: None)
# Fast IO
if (not LOCAL) and (not _interactive):
from io import BytesIO
from atexit import register
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Some utility functions(Input, N-dimensional lists, ...)
def input_as_list():
return [int(x) for x in input().split()]
def input_with_offset(o):
return [int(x)+o for x in input().split()]
def input_as_matrix(n, m):
return [input_as_list() for _ in range(n)]
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
main()
|
1598020500
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["? 1 2 3\n\n? 3 4 5\n\n! 3 4 1 2\n\n? 7 1 9\n\n! 4 2 3 6 8"]
|
98c584b0479eb26d8b0307bd72fc48fd
|
NoteExplanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):For the first test case:Question "? 1 2 3" returns $$$0$$$, so there are more impostors than crewmates among players $$$1$$$, $$$2$$$ and $$$3$$$.Question "? 3 4 5" returns $$$1$$$, so there are more crewmates than impostors among players $$$3$$$, $$$4$$$ and $$$5$$$.Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are $$$k = 3$$$ impostors. The players who are impostors are players $$$4$$$, $$$1$$$ and $$$2$$$.For the second test case:Question "? 7 1 9" returns $$$1$$$, so there are more crewmates than impostors among players $$$7$$$, $$$1$$$ and $$$9$$$.Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are $$$k = 4$$$ impostors. The players who are impostors are players $$$2$$$, $$$3$$$, $$$6$$$ and $$$8$$$.
|
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.There are $$$n$$$ players labelled from $$$1$$$ to $$$n$$$. It is guaranteed that $$$n$$$ is a multiple of $$$3$$$.Among them, there are $$$k$$$ impostors and $$$n-k$$$ crewmates. The number of impostors, $$$k$$$, is not given to you. It is guaranteed that $$$\frac{n}{3} < k < \frac{2n}{3}$$$.In each question, you can choose three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le n$$$) and ask: "Among the players labelled $$$a$$$, $$$b$$$ and $$$c$$$, are there more impostors or more crewmates?" You will be given the integer $$$0$$$ if there are more impostors than crewmates, and $$$1$$$ otherwise.Find the number of impostors $$$k$$$ and the indices of players that are impostors after asking at most $$$n+6$$$ questions.The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.
| null |
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains a single integer $$$n$$$ ($$$6 \le n < 10^4$$$, $$$n$$$ is a multiple of $$$3$$$) — the number of players. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^4$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_100.jsonl
|
a7cdcddaf4eef3765ca1223327e66c49
|
256 megabytes
|
["2\n6\n\n0\n\n1\n\n9\n\n1"]
|
PASSED
|
def ask(a, b, c):
print(f'? {a} {b} {c}', flush=True)
s = input()
if s == '-1':
exit()
else:
return int(s)
for _ in range(int(input())):
n = int(input())
ans = [0]*n
fp = [0]*2
sp = [0]*2
tp = [0]*2
fop= [0]*2
fp[0]= ['0000', '0010', '0100', '1000', '0001', '0011', '0101', '1001' ]
fp[1] = ['1111', '1101', '1011', '0111', '1110', '1100', '1010', '0110']
sp[0] = ['0000', '0010', '0100', '0110', '0001', '0011', '1000', '1010']
sp[1] = ['1111', '1101', '1011', '1001', '1110', '1100', '0111', '0101']
tp[0] = ['0000', '1000', '0100', '1100', '0010', '1010', '0001', '1001']
tp[1] = ['1111', '0111', '1011', '0011', '1101', '0101', '1110', '0110']
fop[0] = ['0000', '0100', '1000', '1100', '0010', '0110', '0001', '0101']
fop[1] = ['1111', '1011', '0111', '0011', '1101', '1001', '1110', '1010']
m = ask(1, 2, 3)
for k in range(1,n//3):
i = 3*k
tmp = ask(i + 1, i + 2, i + 3)
if tmp!= m:
break
if tmp == 1:
r = tp[1]
j = 3*(k-1)
p = fp[ask(j + 1, i + 1, i + 2)]
q = sp[ask(j + 1, i + 1, i + 3)]
s = fop[ask(j + 1, i + 2, i + 3)]
x = list(((set(p)&set(q)) & set(r)) & set(s))
if len(x) == 1:
ans[j] = '0'
ans[i:i+3] = list(x[0])[1:]
zeropos = j+1
onepos = i+ list(x[0]).index('1')
else:
p = fp[ask(j + 2, i + 1, i + 2)]
q = sp[ask(j + 2, i + 1, i + 3)]
s = fop[ask(j + 2, i + 2, i + 3)]
x = list(((set(p) & set(q)) & set(r)) & set(s))
if len(x) == 1:
ans[j+1] = '0'
ans[i:i + 3] = list(x[0])[1:]
zeropos = j + 2
onepos = i + list(x[0]).index('1')
else:
ans[i:i+3] = list('111')
onepos = i + 1
t = ask(j+1, j+2, onepos)
if t== 0:
ans[j] = '0'
ans[j+1] = '0'
zeropos = j+1
else:
ans[j+2] = '0'
zeropos = j+3
for z in range(j+1,j+4):
if z!= zeropos:
ans[z-1] = str(ask(z, zeropos, onepos))
for c in range(0,k-1):
d = 3*c
b = ask(d+1, d+2, onepos)
if b == 0:
ans[d] = '0'
ans[d+1] = '0'
ans[d+2] = str(ask(zeropos, d + 3, onepos))
else:
ans[d+2] = '0'
ans[d + 1] = str(ask(d + 2, zeropos, onepos))
ans[d] = str(1- int(ans[d+1]))
else:
r = tp[0]
j = 3 * (k - 1)
p = fp[ask(j + 1, i + 1, i + 2)]
q = sp[ask(j + 1, i + 1, i + 3)]
s = fop[ask(j + 1, i + 2, i + 3)]
x = list(((set(p) & set(q)) & set(r)) & set(s))
if len(x) == 1:
ans[j] = '1'
ans[i :i + 3] = list(x[0])[1:]
onepos = j + 1
zeropos = i + list(x[0]).index('0')
else:
p = fp[ask(j + 2, i + 1, i + 2)]
q = sp[ask(j + 2, i + 1, i + 3)]
s = fop[ask(j + 2, i + 2, i + 3)]
x = list(((set(p) & set(q)) & set(r)) & set(s))
if len(x) == 1:
ans[j + 1] = '1'
ans[i :i + 3] = list(x[0][1:])
onepos = j + 2
zeropos = i + list(x[0]).index('0')
else:
ans[i :i + 3] = list('000')
zeropos = i + 1
t = ask(j + 1, j + 2, zeropos)
if t == 1:
ans[j] = '1'
ans[j + 1] = '1'
onepos = j + 1
else:
ans[j + 2] = '1'
onepos = j + 3
for z in range(j+1,j+4):
if z!= onepos:
ans[z-1] = str(ask(z, zeropos, onepos))
for c in range(0,k-1):
d = 3*c
b = str(ask(d+1, d+2, zeropos))
if b == '1':
ans[d] = '1'
ans[d+1] = '1'
ans[d+2] = str(ask(d + 3, zeropos, onepos))
else:
ans[d+2] = '1'
ans[d + 1] = str(ask(d + 2, zeropos, onepos))
ans[d] = str(1- int(ans[d+1]))
for l in range(i+4,n+1):
ans[l - 1] = str(ask(l, zeropos, onepos))
#print(ans)
indans = [str(i+1) for i in range(n) if ans[i] == '0']
fans = '! '+str(len(indans)) + ' ' + ' '.join(indans)
print(fans, flush=True)
|
1639661700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["Rublo", "Rublo", "Furlo"]
|
cc23f07b6539abbded7e120793bef6a7
| null |
Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to: choose some pile, let's denote the current number of coins in it as x; choose some integer y (0 ≤ y < x; x1 / 4 ≤ y ≤ x1 / 2) and decrease the number of coins in this pile to y. In other words, after the described move the pile will have y coins left. The player who can't make a move, loses. Your task is to find out, who wins in the given game if both Furlo and Rublo play optimally well.
|
If both players play optimally well and Furlo wins, print "Furlo", otherwise print "Rublo". Print the answers without the quotes.
|
The first line contains integer n (1 ≤ n ≤ 77777) — the number of piles. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 777777777777) — the sizes of piles. The numbers are separated by single spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_001.jsonl
|
ffca4bac4e0e73f25ac7c01ea5dd17f9
|
256 megabytes
|
["1\n1", "2\n1 2", "10\n1 2 3 4 5 6 7 8 9 10"]
|
PASSED
|
from bisect import *
input()
r = [3, 15, 81, 6723, 15 ** 4, 15 ** 8]
v = [0, 1, 2, 0, 3, 1, 2]
print ['Rublo', 'Furlo'][reduce(lambda x, y : x ^ y, map(lambda x : v[bisect_left(r, x)], map(int, raw_input().split()))) > 0]
|
1355671800
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["R\nL\nL\nD\nU\nU\nU\nR\nR\nD"]
|
79879630a9358ea152a6f1616ef9b630
|
NoteIn first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:This test could be presenter for hack in following way: 4 3 1 1...**.F*....
|
This is an interactive problem.Vladik has favorite game, in which he plays all his free time.Game field could be represented as n × m matrix which consists of cells of three types: «.» — normal cell, player can visit it. «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type. «*» — dangerous cell, if player comes to this cell, he loses. Initially player is located in the left top cell with coordinates (1, 1). Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.Help Vladik win the game!
| null |
First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively. Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above. Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_007.jsonl
|
4af6cf8adc7c898bcbbcb1ba62767f35
|
256 megabytes
|
["4 3\n...\n**.\nF*.\n...\n1 1\n1 2\n1 3\n1 3\n2 3\n3 3\n4 3\n4 2\n4 1\n3 1"]
|
PASSED
|
import sys
sys.setrecursionlimit(2*10**5)
n, m=map(int, input().split())
g=[input() for i in range(n)]
vis=[[0]*m for i in range(n)]
mp={}
l=[]
def dfs(i, j):
vis[i][j]=1
l.append((i, j))
if g[i][j]=='F':
return 1
for d in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
if not (i+d[0]<0 or i+d[0]>=n or j+d[1]<0 or j+d[1]>=m or g[i+d[0]][j+d[1]]=='*' or vis[i+d[0]][j+d[1]]) and dfs(i+d[0], j+d[1]):
return 1
l.pop()
return 0
dfs(0, 0)
#print(l)
for i in range(1, len(l)):
# i-1 to i
d=(l[i][0]-l[i-1][0], l[i][1]-l[i-1][1])
if not d in mp:
if d[0]==0:
print('R',flush=True)
a,b=map(int, input().split())
b-=1
if b==l[i][1]:
# actually right
mp[(0, 1)]='R'
mp[(0, -1)]='L'
continue
else:
mp[(0, 1)]='L'
mp[(0, -1)]='R'
else:
print('D',flush=True)
a,b=map(int, input().split())
a-=1
if a==l[i][0]:
# actually down
mp[(1, 0)]='D'
mp[(-1, 0)]='U'
continue
else:
mp[(1, 0)]='U'
mp[(-1, 0)]='D'
print(mp[d],flush=True)
input()
|
1495877700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["6\n2\n3"]
|
c358bce566a846bd278329ef2c029dff
|
NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations: swap $$$a_k$$$ and $$$a_4$$$; swap $$$a_2$$$ and $$$a_2$$$; swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.
|
You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.
|
For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_001.jsonl
|
99716b2822970c255965782ba88caa05
|
256 megabytes
|
["3\n6 4 3\n1 6\n2 3\n5 5\n4 1 2\n2 4\n1 2\n3 3 2\n2 3\n1 2"]
|
PASSED
|
for _ in range(int(input())):
n,x,m = map(int,input().split())
lst = []
for i in range(m):
tmp = list(map(int,input().split()))
lst.append(tmp)
while lst and not lst[0][0]<=x<=lst[0][1]:
lst.pop(0)
if not lst:
print(1)
else:
ans = [lst[0]]
for i in range(1,len(lst)):
if lst[i][0]<ans[-1][0] and ans[-1][1]<lst[i][1]:
ans[-1] = lst[i]
elif ans[-1][0]<=lst[i][1]<=ans[-1][1] and lst[i][0]<ans[-1][0]:
ans[-1][0] = lst[i][0]
elif ans[-1][0]<=lst[i][0]<=ans[-1][1] and lst[i][1]>ans[-1][1]:
ans[-1][1] = lst[i][1]
if ans:
print(ans[-1][1]-ans[-1][0]+1)
else:
print(1)
|
1591886100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["17\n82\n23\n210", "2\n0\n22\n59\n16\n8"]
|
e02938670cb1d586d065ca9750688404
|
NoteIn the first query of the first sample, the Lipschitz constants of subarrays of with length at least 2 are: The answer to the query is their sum.
|
A function is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all . We'll deal with a more... discrete version of this term.For an array , we define it's Lipschitz constant as follows: if n < 2, if n ≥ 2, over all 1 ≤ i < j ≤ n In other words, is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n.You are given an array of size n and q queries of the form [l, r]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .
|
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of .
|
The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array and the number of queries respectively. The second line contains n space-separated integers (). The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 ≤ li < ri ≤ n).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_024.jsonl
|
ca65e3064d0735787897814f0f5ccb24
|
256 megabytes
|
["10 4\n1 5 2 9 1 3 4 2 1 7\n2 4\n3 8\n7 10\n1 9", "7 6\n5 7 7 4 6 6 2\n1 2\n2 3\n2 6\n1 7\n4 7\n3 5"]
|
PASSED
|
f = lambda: map(int, input().split())
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
j = n - i
x, y = i - 1, j + 1
a, b = p[i], p[j]
while a > p[x]: x = L[x]
while b >= p[y]: y = R[y]
L[i], R[j] = x, y
for k in range(m):
l, r = f()
print(sum((i - max(l - 1, L[i])) * (min(r, R[i]) - i) * p[i] for i in range(l, r)))
|
1448382900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2", "1", "1"]
|
00db0111fd80ce1820da2af07a6cb8f1
|
NoteIn the second example hacker need to use any of the passwords to access the system.
|
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
|
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
|
The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_023.jsonl
|
ef3d465a611ab310c1135cf44d1ba8b8
|
256 megabytes
|
["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"]
|
PASSED
|
def union(x, y):
xr = find(x)
yr = find(y)
root[yr] = xr
def find(x):
if root[x] != x:
x = find(root[x])
return x
import sys
input = sys.stdin.readline
used = set()
root = dict()
for _ in range(int(input())):
s = input().rstrip()
for j in s:
if ord(j) - 97 not in root:
root[ord(j) - 97] = ord(j) - 97
union(ord(s[0]) - 97, ord(j) - 97)
for i in root:
used.add(find(root[i]))
print(used.__len__())
|
1575038100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n2 2\n1 1\n2 4\n-1\n4\n1 1\n2 6\n3 3\n3 7\n4\n3 1\n1 2\n2 3\n1 4\n2\n4 5\n2 1\n4\n3 1\n4 5\n2 9\n1 13"]
|
c08933fdaceb220f4ef3ba8c5f09fe12
|
NoteThe first test case is explained in the problem statement.In the second test case, it is impossible to color all the letters of the text in red.
|
You are given some text $$$t$$$ and a set of $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$. In one step, you can choose any occurrence of any string $$$s_i$$$ in the text $$$t$$$ and color the corresponding characters of the text in red. For example, if $$$t=\texttt{bababa}$$$ and $$$s_1=\texttt{ba}$$$, $$$s_2=\texttt{aba}$$$, you can get $$$t=\color{red}{\texttt{ba}}\texttt{baba}$$$, $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$ or $$$t=\texttt{bab}\color{red}{\texttt{aba}}$$$ in one step.You want to color all the letters of the text $$$t$$$ in red. When you color a letter in red again, it stays red.In the example above, three steps are enough: Let's color $$$t[2 \dots 4]=s_2=\texttt{aba}$$$ in red, we get $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$; Let's color $$$t[1 \dots 2]=s_1=\texttt{ba}$$$ in red, we get $$$t=\color{red}{\texttt{baba}}\texttt{ba}$$$; Let's color $$$t[4 \dots 6]=s_2=\texttt{aba}$$$ in red, we get $$$t=\color{red}{\texttt{bababa}}$$$. Each string $$$s_i$$$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.Determine the minimum number of steps needed to color all letters $$$t$$$ in red and how to do it. If it is impossible to color all letters of the text $$$t$$$ in red, output -1.
|
For each test case, print the answer on a separate line. If it is impossible to color all the letters of the text in red, print a single line containing the number -1. Otherwise, on the first line, print the number $$$m$$$ — the minimum number of steps it will take to turn all the letters $$$t$$$ red. Then in the next $$$m$$$ lines print pairs of indices: $$$w_j$$$ and $$$p_j$$$ ($$$1 \le j \le m$$$), which denote that the string with index $$$w_j$$$ was used as a substring to cover the occurrences starting in the text $$$t$$$ from position $$$p_j$$$. The pairs can be output in any order. If there are several answers, output any of them.
|
The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains the text $$$t$$$ ($$$1 \le |t| \le 100$$$), consisting only of lowercase Latin letters, where $$$|t|$$$ is the length of the text $$$t$$$. The second line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of strings in the set. This is followed by $$$n$$$ lines, each containing a string $$$s_i$$$ ($$$1 \le |s_i| \le 10$$$) consisting only of lowercase Latin letters, where $$$|s_i|$$$ — the length of string $$$s_i$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_102.jsonl
|
6458d49857e833dafc7b4e2f8e83baee
|
256 megabytes
|
["6\n\nbababa\n\n2\n\nba\n\naba\n\ncaba\n\n2\n\nbac\n\nacab\n\nabacabaca\n\n3\n\naba\n\nbac\n\naca\n\nbaca\n\n3\n\na\n\nc\n\nb\n\ncodeforces\n\n4\n\ndef\n\ncode\n\nefo\n\nforces\n\naaaabbbbcccceeee\n\n4\n\neeee\n\ncccc\n\naaaa\n\nbbbb"]
|
PASSED
|
import sys
input=lambda: sys.stdin.readline().strip()
for _ in range(int(input())):
t = input()
n = int(input())
l = list()
for i in range(n):
inp = input()
l.append((inp,len(inp),i+1))
l.sort(key=lambda p: p[1],reverse=True)
ans = list() # (id, pos)
mai = 0
i = 0
while i <= mai < len(t):
for (s, le, ind) in l:
if mai < le+i <= len(t):
if all(t[i+j]==s[j] for j in range(le)):
if len(ans) > 1 and ans[-2][-1] >= i:
ans.pop()
mai = le+i
ans.append((ind,i+1,le+i))
i+=1
if mai < i:
print(-1)
break
else:
print(len(ans))
for (a,b,i) in ans:
print(a, b)
|
1659364500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2.5 seconds
|
["8", "3"]
|
e4a2cfe3e76a7fafb8116c1972394c46
|
NoteDo keep in mind that k0 = 1.In the first sample, Molly can get following different affection values: 2: segments [1, 1], [2, 2], [3, 3], [4, 4]; 4: segments [1, 2], [2, 3], [3, 4]; 6: segments [1, 3], [2, 4]; 8: segments [1, 4]. Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].
|
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments.
|
Output a single integer — the number of valid segments.
|
The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 105, 1 ≤ |k| ≤ 10). Next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — affection values of chemicals.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,800 |
train_017.jsonl
|
329fc7d9a02bdd39dde9621ace99b5c0
|
512 megabytes
|
["4 2\n2 2 2 2", "4 -3\n3 -6 -3 12"]
|
PASSED
|
from sys import stdin
from collections import *
def arr_sum(arr):
tem = [0]
for i in range(len(arr)):
tem.append(tem[i] + arr[i])
return tem
rints = lambda: [int(x) for x in stdin.readline().split()]
mi, ma = -10 ** 14, 10 ** 14
n, k = rints()
a = rints()
mem, ans, lst, val = arr_sum(a), 0, 0, 1
c = Counter(mem)
for j in mem[:-1]:
c[j] -= 1
val = 1
for i in range(48):
if k == -1 and i == 2 or k == 1 and i == 1 or val > ma or val < mi:
break
ans += c[val + j]
val *= k
print(ans)
|
1487861100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3.849644710502\n1.106060157705"]
|
3882f2c02e83bd2d55de8004ea3bbd88
| null |
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight line from point si to point fi (si < fi).Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius r. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius r. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.At the beginning each participant can choose any point bi, such that his bike is fully behind the starting line, that is, bi < si - r. After that, he starts the movement, instantly accelerates to his maximum speed and at time tsi, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time tfi), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time tfi - tsi. Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed v, but also on his choice of the initial point bi. Now Maxim is asking you to calculate for each of n competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to r.
|
Print n real numbers, the i-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 6. Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .
|
The first line contains three integers n, r and v (1 ≤ n ≤ 100 000, 1 ≤ r, v ≤ 109) — the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively. Next n lines contain the descriptions of the contests. The i-th line contains two integers si and fi (1 ≤ si < fi ≤ 109) — the coordinate of the start and the coordinate of the finish on the i-th competition.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,500 |
train_022.jsonl
|
94ecadbbdec855bac087171a8a62699e
|
256 megabytes
|
["2 1 2\n1 10\n5 9"]
|
PASSED
|
from math import cos,pi
def g(t):
return t+cos(t)
def solve(y):
assert(y>=1 and y<2*pi+1)
low = 0.
high = 2*pi+1
for k in range(64):
mid = (low+high)/2
if g(mid) > y:
high = mid
else:
low = mid
return low
def bestTime(s,f,r,v):
m = int((2.+float(f-s)/r)/pi-0.1)
if (m%2 == 0): m += 1
res = None
for i in range(3):
try:
t = solve((m*pi-float(f-s)/r)/2)
cand = (m*pi-2*t)*r/v
if res==None or cand < res:
res = cand
except:
pass
m += 2
return res
n,r,v = map(int,raw_input().split())
for i in range(n):
s,f = map(int,raw_input().split())
print bestTime(s,f,r,v)
|
1447000200
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["3"]
|
f33991da3b4a57dd6535af86edeeddc0
|
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
|
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
|
Print a single number — the maximum size of a clique in a divisibility graph for set A.
|
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_007.jsonl
|
b72301c10d2ea757b84f001aea1a3c0e
|
256 megabytes
|
["8\n3 4 6 8 10 18 21 24"]
|
PASSED
|
#!/usr/bin/env python3
import os
import sys
from io import BytesIO, IOBase
class FastO:
def __init__(self, fd=1):
stream = BytesIO()
self.flush = lambda: os.write(fd, stream.getvalue()) and not stream.truncate(0) and stream.seek(0)
self.write = lambda b: stream.write(b.encode())
class ostream:
def __lshift__(self, a):
sys.stdout.write(str(a))
return self
sys.stdout, cout = FastO(), ostream()
numbers, num, sign = [], 0, True
for char in os.read(0, os.fstat(0).st_size):
if char >= 48:
num = num * 10 + char - 48
elif char == 45:
sign = False
elif char != 13:
numbers.append(num if sign else -num)
num, sign = 0, True
if char >= 48:
numbers.append(num if sign else -num)
getnum = iter(numbers).__next__
n = getnum()
dp = [0] * (10**6 + 1)
for _ in range(n):
dp[getnum()] = 1
for i in reversed(range(10**6 + 1)):
dp[i] = max((dp[x] + 1 for x in range(2 * i, 10**6 + 1, i) if dp[x]), default=1) if dp[i] else 0
cout << max(dp)
|
1438273200
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["NO\nYES\nYES\nNO"]
|
08679e44ee5d3c3287230befddf7eced
|
NoteIn the first test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.In the second test case, you should swap $$$c_i$$$ with $$$a_i$$$ for all possible $$$i$$$. After the swaps $$$a$$$ becomes "bca", $$$b$$$ becomes "bca" and $$$c$$$ becomes "abc". Here the strings $$$a$$$ and $$$b$$$ are equal.In the third test case, you should swap $$$c_1$$$ with $$$a_1$$$, $$$c_2$$$ with $$$b_2$$$, $$$c_3$$$ with $$$b_3$$$ and $$$c_4$$$ with $$$a_4$$$. Then string $$$a$$$ becomes "baba", string $$$b$$$ becomes "baba" and string $$$c$$$ becomes "abab". Here the strings $$$a$$$ and $$$b$$$ are equal.In the fourth test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.
|
You are given three strings $$$a$$$, $$$b$$$ and $$$c$$$ of the same length $$$n$$$. The strings consist of lowercase English letters only. The $$$i$$$-th letter of $$$a$$$ is $$$a_i$$$, the $$$i$$$-th letter of $$$b$$$ is $$$b_i$$$, the $$$i$$$-th letter of $$$c$$$ is $$$c_i$$$.For every $$$i$$$ ($$$1 \leq i \leq n$$$) you must swap (i.e. exchange) $$$c_i$$$ with either $$$a_i$$$ or $$$b_i$$$. So in total you'll perform exactly $$$n$$$ swap operations, each of them either $$$c_i \leftrightarrow a_i$$$ or $$$c_i \leftrightarrow b_i$$$ ($$$i$$$ iterates over all integers between $$$1$$$ and $$$n$$$, inclusive).For example, if $$$a$$$ is "code", $$$b$$$ is "true", and $$$c$$$ is "help", you can make $$$c$$$ equal to "crue" taking the $$$1$$$-st and the $$$4$$$-th letters from $$$a$$$ and the others from $$$b$$$. In this way $$$a$$$ becomes "hodp" and $$$b$$$ becomes "tele".Is it possible that after these swaps the string $$$a$$$ becomes exactly the same as the string $$$b$$$?
|
Print $$$t$$$ lines with answers for all test cases. For each test case: If it is possible to make string $$$a$$$ equal to string $$$b$$$ print "YES" (without quotes), otherwise print "NO" (without quotes). You can print either lowercase or uppercase letters in the answers.
|
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 description of the test cases follows. The first line of each test case contains a string of lowercase English letters $$$a$$$. The second line of each test case contains a string of lowercase English letters $$$b$$$. The third line of each test case contains a string of lowercase English letters $$$c$$$. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding $$$100$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_010.jsonl
|
546704727393151a62aa7713147cc6a1
|
256 megabytes
|
["4\naaa\nbbb\nccc\nabc\nbca\nbca\naabb\nbbaa\nbaba\nimi\nmii\niim"]
|
PASSED
|
n = int(input())
for i in range(n):
a = input()
b = input()
c = input()
flag=1
for j in range(len(c)):
if(c[j]==a[j] or c[j]==b[j]):
flag =1
else:
flag = 0
break
if(flag==1):
print("YES")
else:
print("NO")
|
1581604500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\n3 2 1\nYES\n8 1 2 3 4\nNO"]
|
85383c9e802348a3153e7f98ce278f09
|
NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.
|
Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.
|
For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively. The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_097.jsonl
|
ff607480e89a933be4591b44f14e6966
|
256 megabytes
|
["3\n3 2\n3 2 1\n5 3\n1 2 3 4 8\n1 5\n5"]
|
PASSED
|
for _ in range(int(input())):
n,x = [int(x) for x in input().split()]
lis = list(map(int,input().split()))
if sum(lis) ==x:
print('NO')
continue
lis = sorted(lis,reverse = True)
value =0
for i in range(n):
value+=lis[i]
if value == x:
lis[i],lis[i+1] = lis[i+1],lis[i]
break
print('YES')
print(*lis)
|
1619966100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["Possible\n3\n1 2 3\n3\n1 4 3", "Impossible", "Impossible"]
|
2847383385097c4ab8e5ee1f06580d0e
| null |
Leslie and Leon entered a labyrinth. The labyrinth consists of $$$n$$$ halls and $$$m$$$ one-way passages between them. The halls are numbered from $$$1$$$ to $$$n$$$.Leslie and Leon start their journey in the hall $$$s$$$. Right away, they quarrel and decide to explore the labyrinth separately. However, they want to meet again at the end of their journey.To help Leslie and Leon, your task is to find two different paths from the given hall $$$s$$$ to some other hall $$$t$$$, such that these two paths do not share halls other than the staring hall $$$s$$$ and the ending hall $$$t$$$. The hall $$$t$$$ has not been determined yet, so you can choose any of the labyrinth's halls as $$$t$$$ except $$$s$$$.Leslie's and Leon's paths do not have to be the shortest ones, but their paths must be simple, visiting any hall at most once. Also, they cannot visit any common halls except $$$s$$$ and $$$t$$$ during their journey, even at different times.
|
If it is possible to find the desired two paths, output "Possible", otherwise output "Impossible". If the answer exists, output two path descriptions. Each description occupies two lines. The first line of the description contains an integer $$$h$$$ ($$$2 \le h \le n$$$) — the number of halls in a path, and the second line contains distinct integers $$$w_1, w_2, \dots, w_h$$$ ($$$w_1 = s$$$; $$$1 \le w_j \le n$$$; $$$w_h = t$$$) — the halls in the path in the order of passing. Both paths must end at the same vertex $$$t$$$. The paths must be different, and all intermediate halls in these paths must be distinct.
|
The first line contains three integers $$$n$$$, $$$m$$$, and $$$s$$$, where $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) is the number of vertices, $$$m$$$ ($$$0 \le m \le 2 \cdot 10^5$$$) is the number of edges in the labyrinth, and $$$s$$$ ($$$1 \le s \le n$$$) is the starting hall. Then $$$m$$$ lines with descriptions of passages follow. Each description contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$), denoting a passage from the hall $$$u_i$$$ to the hall $$$v_i$$$. The passages are one-way. Each tuple $$$(u_i, v_i)$$$ is present in the input at most once. The labyrinth can contain cycles and is not necessarily connected in any way.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,800 |
train_091.jsonl
|
75d196843daed1b34b5d50f6ba0e4a47
|
512 megabytes
|
["5 5 1\n1 2\n2 3\n1 4\n4 3\n3 5", "5 5 1\n1 2\n2 3\n3 4\n2 5\n5 4", "3 3 2\n1 2\n2 3\n3 1"]
|
PASSED
|
import sys
input = sys.stdin.readline
def gen_input():
while True:
yield [int(c) for c in input().split()]
def gen_fake1():
yield [5, 5, 1]
yield [1, 2]
yield [2, 3]
yield [1, 4]
yield [4, 3]
yield [3, 5]
def gen_fake():
yield [3, 3, 2]
yield [1, 2]
yield [2, 3]
yield [3, 1]
def gen_fake3():
yield [5, 5, 1]
yield [1, 2]
yield [2, 3]
yield [3, 4]
yield [2, 5]
yield [5, 4]
def ints(g=gen_input()):
return next(g)
n, m, s = ints()
s -= 1
v = [[] for _ in range(n)]
for _ in range(m):
a, b = ints()
v[a - 1].append(b - 1)
def down(v, s, q):
"""nodes reachable from s through q"""
n = len(v)
vis = [False] * n
vis[s] = True
back = [-1] * n
back[q] = s
op = [q] # open nodes
ret = set()
while op:
x = op.pop()
ret.add(x)
vis[x] = True
for y in v[x]:
if not vis[y]:
op.append(y)
back[y] = x
return ret, back
def backtrack(back, start):
ret = []
while start != -1:
ret.append(start)
start = back[start]
return list(reversed(ret))
def prune_common(path1, path2):
for i, node in enumerate(path1):
if i and node in path2:
return path1[:i+1], path2[:path2.index(node) + 1]
return path1, path2
def go(v=v, s=s):
n = len(v)
vis = [-1] * n
vis[s] = s
back = [-1] * n
for q in v[s]:
if vis[q] >= 0:
return [s, q], backtrack(back, q)
op = [q]
back[q] = s
while op:
x = op.pop()
vis[x] = q
for y in v[x]:
if vis[y] == -1:
op.append(y)
back[y] = x
elif vis[y] != s and vis[y] >= 0 and vis[y] != q:
return backtrack(back, y), backtrack(back, x) + [y]
# def go():
# if len(v[s]) <= 1:
# return
# d = [0] * len(v[s])
# d[0] = down(v, s, v[s][0])[0]
# vis_total = d[0]
# for i in range(1, len(d)):
# d[i] = down(v, s, v[s][i])[0]
# vis_new = vis_total | d[i]
# if len(vis_new) < len(vis_total) + len(d[i]):
# break
# vis_total = vis_new
# else:
# return
# for j in range(0, i):
# s12 = d[i] & d[j]
# if s12:
# desto = s12.pop()
# back1 = down(v, s, v[s][i])[1]
# back2 = down(v, s, v[s][j])[1]
# path1 = backtrack(back1, desto)
# path2 = backtrack(back2, desto)
# #print(path1, path2)
# path1, path2 = prune_common(path1, path2)
# path1 = [x+1 for x in path1]
# path2 = [x+1 for x in path2]
# return path1, path2
def array_plus1(v):
for i in range(len(v)):
v[i] += 1
p12 = go()
if p12:
print("Possible")
p1, p2 = p12
array_plus1(p1)
array_plus1(p2)
print(len(p1))
print(*p1)
print(len(p2))
print(*p2)
else:
print("Impossible")
|
1649837100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["Yes\nNo\nNo\nYes\nNo"]
|
d5bd27c969d9cd910f13baa53c247871
|
NoteIn the first test case, a possible way of splitting the set is $$$(2,3)$$$, $$$(4,5)$$$.In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is $$$(2,3)$$$.
|
You are given a multiset (i. e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by $$$2$$$, the remainder is $$$1$$$).
|
For each test case, print "Yes" if it can be split into exactly $$$n$$$ pairs so that the sum of the two elements in each pair is odd, 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 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1,a_2,\dots, a_{2n}$$$ ($$$0\leq a_i\leq 100$$$) — the numbers in the set.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_083.jsonl
|
0bd86eaf6486edde2fb523fcebed8ef1
|
256 megabytes
|
["5\n2\n2 3 4 5\n3\n2 3 4 5 5 5\n1\n2 4\n1\n2 3\n4\n1 5 3 2 6 7 3 4"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
# n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
odd = 0
even = 0
for i in range(n*2):
if arr[i] % 2 == 0:
even += 1
else:
odd += 1
if odd == 2 and even == 0:
print("No")
elif odd == even:
print("Yes")
else:
print("No")
|
1625317500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nNO\nYES\nYES"]
|
f4267120fce9304fc4c45142b60fb867
| null |
You are given $$$n$$$ points with integer coordinates on a coordinate axis $$$OX$$$. The coordinate of the $$$i$$$-th point is $$$x_i$$$. All points' coordinates are distinct and given in strictly increasing order.For each point $$$i$$$, you can do the following operation no more than once: take this point and move it by $$$1$$$ to the left or to the right (i..e., you can change its coordinate $$$x_i$$$ to $$$x_i - 1$$$ or to $$$x_i + 1$$$). In other words, for each point, you choose (separately) its new coordinate. For the $$$i$$$-th point, it can be either $$$x_i - 1$$$, $$$x_i$$$ or $$$x_i + 1$$$.Your task is to determine if you can move some points as described above in such a way that the new set of points forms a consecutive segment of integers, i. e. for some integer $$$l$$$ the coordinates of points should be equal to $$$l, l + 1, \ldots, l + n - 1$$$.Note that the resulting points should have distinct coordinates.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer — if the set of points from the test case can be moved to form a consecutive segment of integers, print YES, otherwise print NO.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points in the set $$$x$$$. The second line of the test case contains $$$n$$$ integers $$$x_1 < x_2 < \ldots < x_n$$$ ($$$1 \le x_i \le 10^6$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th point. It is guaranteed that the points are given in strictly increasing order (this also means that all coordinates are distinct). It is also guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_087.jsonl
|
31dd71f3f425b46936991a1c34b435f2
|
256 megabytes
|
["5\n\n2\n\n1 4\n\n3\n\n1 2 3\n\n4\n\n1 2 3 7\n\n1\n\n1000000\n\n3\n\n2 5 6"]
|
PASSED
|
import sys
t = int(input())
is_one = 0
is_three = 0
is_two = 0
is_break = 0
for i in range(t):
is_one = 0
is_three = 0
is_two = 0
is_break = 0
fullcount = 0
n = int(input())
arr = list(map(int, input().split()))
# print(arr)
if(n == 1):
print('YES')
continue
else:
for idx, val in enumerate(arr):
if(idx>0):
if(arr[idx]-arr[idx-1] == 1):
is_one += 1
elif(arr[idx]-arr[idx-1] == 3):
is_three += 1
if(is_two != 0):
print('NO')
is_break = 1
break
if(is_three >= 2):
print('NO')
is_break = 1
break
elif(arr[idx]-arr[idx-1] == 2):
is_two += 1
if(is_three != 0):
print('NO')
is_break = 1
break
if(is_two >= 3):
print('NO')
is_break = 1
break
else:
print('NO')
is_break = 1
break
if(is_break == 1):
continue
else:
print('YES')
|
1650638100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["10\n18\n90\n180"]
|
d11b56fe172110d5dfafddf880e48f18
|
NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).
|
You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.
|
For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.
|
The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries. Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,600 |
train_026.jsonl
|
f5192c6cb6362a8930d1960809b9dec3
|
256 megabytes
|
["4\n54\n50\n2\n178"]
|
PASSED
|
L = [-1] * 181
for i in range(3, 400):
for j in range(1, i-1):
if L[180*j/i] == -1 and 180*j%i==0:
L[180*j/i] = i
T = input()
for i in range(T):
ang = input()
print L[ang]
|
1546007700
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1.000000000\n2.414213562\n127.321336469"]
|
0c7a476716445c535a61f4e81edc7f75
| null |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.
|
Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,400 |
train_006.jsonl
|
f6a9a72c21428dfe6a2da3f8660c20ef
|
256 megabytes
|
["3\n2\n4\n200"]
|
PASSED
|
import sys
import math
range = xrange
input = raw_input
t = int(input())
for _ in range(t):
n = int(input())
r = 0.5 * math.tan(math.pi*(2*n-2)/(4*n))
# r = 1/(2.0 * math.tan(math.pi / 2.0*n))
print 2*r
|
1589707200
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0 1 2 0 3", "1000 1000000000 0", "2 3 5 7 10"]
|
e22b10cdc33a165fbd73b45dc5fbedce
|
NoteThe first test was described in the problem statement.In the second test, if Alicia had an array $$$a = \{1000, 1000000000, 0\}$$$, then $$$x = \{0, 1000, 1000000000\}$$$ and $$$b = \{1000-0, 1000000000-1000, 0-1000000000\} = \{1000, 999999000, -1000000000\}$$$.
|
Alicia has an array, $$$a_1, a_2, \ldots, a_n$$$, of non-negative integers. For each $$$1 \leq i \leq n$$$, she has found a non-negative integer $$$x_i = max(0, a_1, \ldots, a_{i-1})$$$. Note that for $$$i=1$$$, $$$x_i = 0$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, then $$$x = \{0, 0, 1, 2, 2\}$$$.Then, she calculated an array, $$$b_1, b_2, \ldots, b_n$$$: $$$b_i = a_i - x_i$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, $$$b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$$$.Alicia gives you the values $$$b_1, b_2, \ldots, b_n$$$ and asks you to restore the values $$$a_1, a_2, \ldots, a_n$$$. Can you help her solve the problem?
|
Print $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), such that if you calculate $$$x$$$ according to the statement, $$$b_1$$$ will be equal to $$$a_1 - x_1$$$, $$$b_2$$$ will be equal to $$$a_2 - x_2$$$, ..., and $$$b_n$$$ will be equal to $$$a_n - x_n$$$. It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.
|
The first line contains one integer $$$n$$$ ($$$3 \leq n \leq 200\,000$$$) – the number of elements in Alicia's array. The next line contains $$$n$$$ integers, $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$). It is guaranteed that for the given array $$$b$$$ there is a solution $$$a_1, a_2, \ldots, a_n$$$, for all elements of which the following is true: $$$0 \leq a_i \leq 10^9$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_010.jsonl
|
3ce30269a0f9307550ac246378a6d166
|
256 megabytes
|
["5\n0 1 1 -2 1", "3\n1000 999999000 -1000000000", "5\n2 1 2 2 3"]
|
PASSED
|
n = int(input())
b = str(input()).split()
x = []
a = []
for i in range(n):
b[i] = int(b[i])
if i == 0:
m = b[i]
x.append(0)
a.append(b[i])
else:
if a[i-1] > m:
m = a[i-1]
x.append(m)
a.append(b[i] + x[i])
print(a[i], end=' ')
|
1584628500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3\n3"]
|
e59cddb6c941b1d7556ee9c020701007
|
NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.
|
You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.
|
For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,100 |
train_005.jsonl
|
c9097d60a41b23272809a3b2b60fabb1
|
256 megabytes
|
["2\n5\n3 1 2 3 1\n7\n1 1 1 1 1 2 2"]
|
PASSED
|
#import resource
import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.Thread(target=main).start()
#threading.stack_size(2**26)
#sys.setrecursionlimit(10**6)
mod=(10**9)+7
fact=[1]
#for i in range(1,100001):
# fact.append((fact[-1]*i)%mod)
#ifact=[0]*10000001
#ifact[10000000]=pow(fact[10000000],mod-2,mod)
#for i in range(10000000,0,-1):
# ifact[i-1]=(i*ifact[i])%mod
from sys import stdin, stdout
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import math
import heapq
from random import randint as rn
from Queue import Queue as Q
def modinv(n,p):
return pow(n,p-2,p)
def ncr(n,r,p):
t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p
return t
def ain():
return map(int,sin().split())
def sin():
return stdin.readline()
def GCD(x,y):
while(y):
x, y = y, x % y
return x
def isprime(x):
if(x==1):
return False
elif(x<4):
return True
for i in range(2,int(math.sqrt(x))+1):
if(x%i==0):
return False
return True
"""**************************************************************************"""
for _ in range(input()):
n=input()
a=ain()
b=[0,0,0]
for i in range(n):
b[a[i]%3]+=1
x=min(b[1],b[2])
y=max(b[1],b[2])
ans=b[0]+x
y-=x
y/=3
ans+=y
print ans
|
1560090900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["35\n30\n42\n0\n0"]
|
f5a0dbef2aed164d83759e797569aef1
|
NoteIn the first test case optimal sequence of solving problems is as follows: $$$1 \rightarrow 2$$$, after that total score is $$$5$$$ and $$$\text{IQ} = 2$$$ $$$2 \rightarrow 3$$$, after that total score is $$$10$$$ and $$$\text{IQ} = 4$$$ $$$3 \rightarrow 1$$$, after that total score is $$$20$$$ and $$$\text{IQ} = 6$$$ $$$1 \rightarrow 4$$$, after that total score is $$$35$$$ and $$$\text{IQ} = 14$$$ In the second test case optimal sequence of solving problems is as follows: $$$1 \rightarrow 2$$$, after that total score is $$$5$$$ and $$$\text{IQ} = 2$$$ $$$2 \rightarrow 3$$$, after that total score is $$$10$$$ and $$$\text{IQ} = 4$$$ $$$3 \rightarrow 4$$$, after that total score is $$$15$$$ and $$$\text{IQ} = 8$$$ $$$4 \rightarrow 1$$$, after that total score is $$$35$$$ and $$$\text{IQ} = 14$$$ In the third test case optimal sequence of solving problems is as follows: $$$1 \rightarrow 3$$$, after that total score is $$$17$$$ and $$$\text{IQ} = 6$$$ $$$3 \rightarrow 4$$$, after that total score is $$$35$$$ and $$$\text{IQ} = 8$$$ $$$4 \rightarrow 2$$$, after that total score is $$$42$$$ and $$$\text{IQ} = 12$$$
|
Please note the non-standard memory limit.There are $$$n$$$ problems numbered with integers from $$$1$$$ to $$$n$$$. $$$i$$$-th problem has the complexity $$$c_i = 2^i$$$, tag $$$tag_i$$$ and score $$$s_i$$$.After solving the problem $$$i$$$ it's allowed to solve problem $$$j$$$ if and only if $$$\text{IQ} < |c_i - c_j|$$$ and $$$tag_i \neq tag_j$$$. After solving it your $$$\text{IQ}$$$ changes and becomes $$$\text{IQ} = |c_i - c_j|$$$ and you gain $$$|s_i - s_j|$$$ points.Any problem can be the first. You can solve problems in any order and as many times as you want.Initially your $$$\text{IQ} = 0$$$. Find the maximum number of points that can be earned.
|
For each test case print a single integer — the maximum number of points that can be earned.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 5000)$$$ — the number of problems. The second line of each test case contains $$$n$$$ integers $$$tag_1, tag_2, \ldots, tag_n$$$ $$$(1 \le tag_i \le n)$$$ — tags of the problems. The third line of each test case contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ $$$(1 \le s_i \le 10^9)$$$ — scores of the problems. It's guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,500 |
train_087.jsonl
|
c0b618e2fcc84f64117b21a2bff7378b
|
32 megabytes
|
["5\n4\n1 2 3 4\n5 10 15 20\n4\n1 2 1 2\n5 10 15 20\n4\n2 2 4 1\n2 8 19 1\n2\n1 1\n6 9\n1\n1\n666"]
|
PASSED
|
import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# a.sort()
# b = []
# st = set()
# c = []
# for i in range(n):
# if a[i] in st:
# c.append(a[i])
# else:
# b.append(a[i])
# st.add(a[i])
# print(*(b + c))
# for _ in range(int(input())):
# n, m = list(map(int, input().split()))
# a = list(map(int, input().split()))
# for i in range(n):
# a[i] %= m
# cnt = [0] * m
# for i in range(n):
# cnt[a[i]] += 1
# # print(cnt)
# ans = 0
# if cnt[0] > 0:
# ans += 1
# for i in range(1, (m - 1) // 2 + 1):
# x, y = cnt[i], cnt[m - i]
# if x == y == 0: continue
# if x < y: x, y = y, x
# if x - y <= 1:
# ans += 1
# else:
# ans += x - y
# if m % 2 == 0:
# ans += (cnt[m // 2] > 0)
# print(ans)
# for _ in range(int(input())):
# n, k = list(map(int, input().split()))
# ans = []
# for i in range(k - 3):
# ans.append(1)
# k -= 1
# n -= 1
# r = 1
# while n % 2 == 0:
# r *= 2
# n //= 2
# if n == 1:
# n = 4
# r //= 4
# ans += [2 * r, r, r]
# else:
# ans += [n // 2 * r, n // 2 * r, r]
# print(*ans)
# N = int(pow(10 ** 9, 0.5)) + 5
# def get_prime_linear(n):
# global cnt
# for i in range(2, n + 1):
# if not st[i]:
# primes[cnt] = i
# cnt += 1
# for j in range(n):
# if primes[j] > n / i: break
# st[primes[j] * i] = True
# if i % primes[j] == 0: break
# primes, cnt, st = [0] * (N + 5), 0, [False] * (N + 5)
# get_prime_linear(N)
# prime1e3 = primes[:cnt]
# @lru_cache(None)
# def get_factor(n):
# res = []
# for i in prime1e3:
# if i * i > n:
# break
# while n % i == 0:
# n //= i
# res.append(i)
# if n > 1:
# res.append(n)
# return res
# for _ in range(int(input())):
# n, k = list(map(int, input().split()))
# a = list(map(int, input().split()))
# for i in range(n):
# f = get_factor(a[i])
# st = set()
# for j in f:
# if j in st:
# st.remove(j)
# else:
# st.add(j)
# a[i] = 1
# for j in st:
# a[i] *= j
# print(a)
# ans = 0
# st = set()
# for i in range(n):
# if a[i] in st:
# st = set()
# st.add(a[i])
# ans += 1
# else:
# st.add(a[i])
# print(ans + 1)
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
s = list(map(int, input().split()))
dp = [0] * n
for i in range(n):
for j in range(i)[::-1]:
if a[i] != a[j]:
dp[i], dp[j] = max(dp[i], dp[j] + abs(s[i] - s[j])), max(dp[j], dp[i] + abs(s[i] - s[j]))
print(max(dp))
|
1615991700
|
[
"number theory",
"graphs"
] |
[
0,
0,
1,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["...\n.L.\n...\n#++++\n..##L\n...#+\n...++\nL\n++++L++#."]
|
fa82a5160696616af784b5488c9f69f6
|
NoteIn the first testcase there is no free cell that the robot can be forced to reach the lab from. Consider a corner cell. Given any direction, it will move to a neighbouring border grid that's not a corner. Now consider a non-corner free cell. No matter what direction you send to the robot, it can choose a different direction such that it ends up in a corner.In the last testcase, you can keep sending the command that is opposite to the direction to the lab and the robot will have no choice other than move towards the lab.
|
There is a grid, consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked.A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: "move right", "move down", "move left" or "move up". Each command means moving to a neighbouring cell in the corresponding direction.However, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing.We want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.
|
For each testcase find the free cells that the robot can be forced to reach the lab from. Given the grid, replace the free cells (marked with a dot) with a plus sign ('+') for the cells that the robot can be forced to reach the lab from. Print the resulting grid.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^6$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the grid. The $$$i$$$-th of the next $$$n$$$ lines provides a description of the $$$i$$$-th row of the grid. It consists of $$$m$$$ elements of one of three types: '.' — the cell is free; '#' — the cell is blocked; 'L' — the cell contains a lab. The grid contains exactly one lab. The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_090.jsonl
|
fae7079d6666b2c392586d123d2db2a8
|
512 megabytes
|
["4\n3 3\n...\n.L.\n...\n4 5\n#....\n..##L\n...#.\n.....\n1 1\nL\n1 9\n....L..#."]
|
PASSED
|
import sys
import os
from io import BytesIO, IOBase
from collections import deque
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
f = sys.stdin
if os.environ.get('USER') == "loic":
f = open("data.in")
line = lambda: f.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
def neigh(i,j):
res = []
if i > 0:
res.append((i-1,j))
if i < N-1:
res.append((i+1,j))
if j > 0:
res.append((i,j-1))
if j < M-1:
res.append((i,j+1))
return res
def solve():
start = (x,y)
q = deque([start])
while q:
i,j = q.pop()
chs = neigh(i, j)
for i_n,j_n in chs:
val = G[i_n][j_n]
if val == '.':
cnt = 0
for i_ch,j_ch in neigh(i_n, j_n):
if G[i_ch][j_ch] == '.':
cnt += 1
if cnt <= 1:
G[i_n][j_n] = '+'
q.append((i_n,j_n))
res = "\n".join("".join(v for v in l) for l in G)
return str(res)
for test in range(1,ui()+1):
N,M = ti()
G = []
x = -1
y = -1
G = [list(line()[0]) for i in range(N)]
xLab = -1
yLab = -1
for i in range(N):
for j in range(M):
if G[i][j] == 'L':
x = i
y = j
break
# for i in range(N):
# l = list(line()[0])
# G.append(l)
# if x == -1:
# for j in range(M):
# if l[j] == 'L':
# x = i
# y = j
# break
print(solve())
f.close()
|
1638369300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["2\n5\n7\n10\n26\n366580019"]
|
2b15a299c25254f265cce106dffd6174
|
NoteIn the fourth test case $$$n=4$$$, so $$$ans=f(1)+f(2)+f(3)+f(4)$$$. $$$1$$$ is a divisor of $$$1$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$1$$$. Thus, $$$f(1)=2$$$. $$$1$$$ and $$$2$$$ are divisors of $$$2$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$2$$$. Thus, $$$f(2)=3$$$. $$$1$$$ is a divisor of $$$3$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$3$$$. Thus, $$$f(3)=2$$$. $$$1$$$ and $$$2$$$ are divisors of $$$4$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$4$$$. Thus, $$$f(4)=3$$$. Therefore, $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$.
|
Let $$$f(i)$$$ denote the minimum positive integer $$$x$$$ such that $$$x$$$ is not a divisor of $$$i$$$.Compute $$$\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$. In other words, compute $$$f(1)+f(2)+\dots+f(n)$$$ modulo $$$10^9+7$$$.
|
For each test case, output a single integer $$$ans$$$, where $$$ans=\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$.
|
The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$), the number of test cases. Then $$$t$$$ cases follow. The only line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_083.jsonl
|
6ea1fa4c1283422de8827dca1e9cabf9
|
256 megabytes
|
["6\n1\n2\n3\n4\n10\n10000000000000000"]
|
PASSED
|
from math import gcd
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
i, smallest_divisor, ans = 1, 1, n
while n // i:
i = i * smallest_divisor // gcd(i, smallest_divisor)
ans += n // i
smallest_divisor += 1
print(ans % 1000000007)
|
1625317500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2\n0", "2\n0", "8"]
|
da11e843698b3ad997e12be2dbd0b71f
|
NoteConsider the first example. For the first question, the possible arrangements are "aabb" and "bbaa", and for the second question, index $$$1$$$ contains 'a' and index $$$2$$$ contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half.
|
There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.Each colony arrangement can be expressed as a string of even length, where the $$$i$$$-th character of the string represents the type of villain in the $$$i$$$-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.Now Iron Man asks Jarvis $$$q$$$ questions. In each question, he gives Jarvis two numbers $$$x$$$ and $$$y$$$. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in $$$x$$$-th hole or $$$y$$$-th hole live in the same half and the Iron Man can destroy that colony arrangement.Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.
|
For each question output the number of arrangements possible modulo $$$10^9+7$$$.
|
The first line contains a string $$$s$$$ ($$$2 \le |s| \le 10^{5}$$$), representing the initial colony arrangement. String $$$s$$$ can have both lowercase and uppercase English letters and its length is even. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 10^{5}$$$) — the number of questions. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le |s|$$$, $$$x_i \ne y_i$$$) — the two numbers given to the Jarvis for the $$$i$$$-th question.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,600 |
train_041.jsonl
|
c31f7cc49264014d1cbe0de4319a71f1
|
512 megabytes
|
["abba\n2\n1 4\n1 2", "AAaa\n2\n1 2\n1 3", "abcd\n1\n1 3"]
|
PASSED
|
from sys import stdin
MOD = 1000000007
s = stdin.readline().strip()
n = len(s)
buc = [0] * 101
fac = [0] * (n + 1)
inv = [0] * (n + 1)
dp = [0] * (n + 1)
# temp_dp = [0] * (n+1)
ans = [[0] * 55 for _ in range(55)]
def find(c: 'str') -> 'int':
if 'A' <= c <= 'Z':
return ord(c) - ord('A') + 26
else:
return ord(c) - ord('a')
def add(a: 'int', b: 'int') -> 'int':
a += b
if a >= MOD:
a -= MOD
return a
def sub(a: 'int', b: 'int') -> 'int':
a -= b
if a < 0:
a += MOD
return a
# c = Counter(s)
# # store frequency
# for k in c.keys():
# buc[find(k)] = c[k]
for i in s:
buc[find(i)] += 1 # naive count is fater than counter
# compute factorial and inv
fac[0] = 1
for i in range(1, n + 1):
fac[i] = (fac[i - 1] * i) % MOD
inv[n] = pow(fac[n], MOD - 2, MOD)
for i in range(n - 1, -1, -1):
inv[i] = (inv[i + 1] * (i + 1)) % MOD
num = pow(fac[n // 2], 2, MOD)
for i in range(0, 52):
num = (num * inv[buc[i]]) % MOD
dp[0] = 1
for i in range(0, 52):
if not buc[i]:
continue
for j in range(n, buc[i] - 1, -1):
dp[j] = add(dp[j], dp[j - buc[i]])
for i in range(52):
ans[i][i] = dp[n // 2]
for i in range(52):
if not buc[i]:
continue
temp_dp = dp.copy()
for k in range(buc[i], n + 1):
temp_dp[k] = sub(temp_dp[k], temp_dp[k - buc[i]])
for j in range(i + 1, 52):
if not buc[j]:
continue
for k in range(buc[j], n + 1):
temp_dp[k] = sub(temp_dp[k], temp_dp[k - buc[j]])
ans[i][j] = (2 * temp_dp[n // 2]) % MOD
for k in range(n, buc[j] - 1, -1):
temp_dp[k] = add(temp_dp[k], temp_dp[k - buc[j]])
q = int(input())
l = stdin.read().splitlines()
for i in l:
x, y = map(int, i.split())
l, r = find(s[x - 1]), find(s[y - 1])
if l > r:
l, r = r, l
print(num * ans[l][r] % MOD)
|
1549208100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n27\n1\n4\n1\n1\n2\n35\n2\n77\n1\n4\n1\n6"]
|
22c0489eec3d8e290fcbcf1aeb3bb66c
|
NoteIn the first test case, you can't delete $$$2$$$ digits from the number $$$237$$$, as all the numbers $$$2$$$, $$$3$$$, and $$$7$$$ are prime. However, you can delete $$$1$$$ digit, obtaining a number $$$27 = 3^3$$$.In the second test case, you can delete all digits except one, as $$$4 = 2^2$$$ is a composite number.
|
During the hypnosis session, Nicholas suddenly remembered a positive integer $$$n$$$, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number $$$53$$$ it's impossible to delete some of its digits to obtain a not prime integer. However, for all $$$n$$$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $$$1$$$ is neither a prime nor a composite number.
|
For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions. If there are multiple solutions, print any.
|
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$k$$$ ($$$1 \le k \le 50$$$) — the number of digits in the number. The second line of each test case contains a positive integer $$$n$$$, which doesn't contain zeros in decimal notation ($$$10^{k-1} \le n < 10^{k}$$$). It is guaranteed that it is always possible to remove less than $$$k$$$ digits to make the number not prime. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_086.jsonl
|
a446a743c141a3f71fab8ddb5e44397f
|
256 megabytes
|
["7\n3\n237\n5\n44444\n3\n221\n2\n35\n3\n773\n1\n4\n30\n626221626221626221626221626221"]
|
PASSED
|
from math import sqrt
"""
def IsPrime(n):
if n==1:
return False
elif n==2:
return True
elif n%2 ==0:
return False
else:
for i in range(3,int(sqrt(n))+1,2):
if n%i ==0:
return False
return True
"""
composite_number=("1","4","6","8","9")
def do():
number_of_digits=int(input())
the_number=input()
for s in the_number:
if s in composite_number:
return ("1",s)
t=the_number[1:].find("2")
if t!=-1:
return ("2",the_number[t:t+2])
elif the_number[0]=="2":
if the_number[1:].find("7")!=-1:
return ("2","27")
t=the_number[1:].find("5")
if t!=-1:
return ("2",the_number[t:t+2])
elif the_number[0]=="5":
if the_number[1:].find("7")!=-1:
return ("2","57")
t=the_number.count("3")
if t>1:
return ("2","33")
t=the_number.count("7")
if t>1:
return ("2","77")
#d=the_number[:the_number.index("3")]
number_list=list(the_number)
number_list=[int(x) for x in number_list]
j=0
i=0
for j in range(0,len(number_list)-1):
for i in range(j+1,len(number_list)):
if (number_list[j]+number_list[i])%3 == 0:
return ("2","{0}{1}".format(number_list[j],number_list[i]))
print(the_number)
try:
number_of_tests=int(input())
while number_of_tests>0:
'''
if 1000-number_of_tests ==106:
number_of_digits=int(input())
the_number=input()
print("v"+the_number)'''
number_of_tests-=1
x,y=do()
print(x,y,sep="\n")
except ValueError:
print("Invalid input")
except Exception as e:
print(str(e).replace(" ",""))
|
1629988500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["4\nB 1 1\nR 1 2\nR 2 1\nB 2 3", "5\nB 1 1\nB 1 2\nR 1 3\nD 1 2\nR 1 2"]
|
9b9f6d95aecc1b6c95e5d9acca4f5453
| null |
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types: Blue towers. Each has population limit equal to 100. Red towers. Each has population limit equal to 200. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side. Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case).Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible.He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks.
|
Print an integer k in the first line (0 ≤ k ≤ 106) — the number of operations Iahub should perform to obtain optimal result. Each of the following k lines must contain a single operation in the following format: «B x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — building a blue tower at the cell (x, y); «R x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — building a red tower at the cell (x, y); «D x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — destroying a tower at the cell (x, y). If there are multiple solutions you can output any of them. Note, that you shouldn't minimize the number of operations.
|
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 500). Each of the next n lines contains m characters, describing the grid. The j-th character in the i-th line is '.' if you're allowed to build at the cell with coordinates (i, j) a tower (empty cell) or '#' if there is a big hole there.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_080.jsonl
|
1e8cf7efc891351032cde7a33fcd02d5
|
256 megabytes
|
["2 3\n..#\n.#.", "1 3\n..."]
|
PASSED
|
from collections import deque
def main():
n, m = [int(x) for x in raw_input().split()]
bactions, ractions = [], []
sets = [[ 1 if c == '.' else 0 for c in row] for row in [raw_input() for x in xrange(n)]]
q = deque()
qappend = q.append
qpop = q.popleft
rappend = ractions.append
bappend = bactions.append
delta = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in xrange(n):
for j in xrange(m):
if sets[i][j] == 1:
qappend((i, j))
while len(q):
x, y = qpop()
if sets[x][y]:
sets[x][y] = 0
bappend('B {0} {1}'.format(x+1, y+1))
if x != i or y != j:
rappend('R {0} {1}'.format(x+1, y+1))
rappend('D {0} {1}'.format(x+1, y+1))
for (dx, dy) in delta:
a, b = x + dx, y + dy
if (a >= 0) and (b >= 0) and (a < n) and (b < m) and (sets[a][b] == 1):
qappend((a, b));
ractions.reverse()
print len(bactions) + len(ractions)
print '\n'.join(bactions)
print '\n'.join(ractions)
if __name__ == '__main__':
main()
|
1372941000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n1\n3"]
|
0ce05499cd28f0825580ff48dae9e7a9
|
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
|
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \cdot a_j = i + j$$$.
|
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \cdot a_j = i + j$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_107.jsonl
|
1e418f0df1b4f6dbadc3c474b5b2cfe7
|
256 megabytes
|
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
|
PASSED
|
for i in range(int(input())):
n=int(input())
L=list(map(int,input().split()))
import math
L=[0]+L
cnt =0
for i in range(1,n+1):
for j in range(L[i]-i,n+1,L[i]):
if(L[i]*L[j])==(i+j) and (j>i):
cnt+=1
print(cnt)
|
1624635300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1.0000000000 2.0000000000\n2.0000000000 0.0000000000", "2.8819000000 0.0000000000\n4.1470000000 1.6168000000\n3.7953000000 4.1470000000\n0.9134000000 4.1470000000\n0.0000000000 2.1785000000\n0.7034000000 0.0000000000"]
|
d00b8423c3c52b19fec25bc63e4d4c1c
| null |
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.
|
Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.
|
The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_021.jsonl
|
96e0437a48895f65afb3976f2a46364e
|
256 megabytes
|
["2 5\n2", "4.147 2.8819\n6"]
|
PASSED
|
a, d = [float(el) for el in input().split()]
n = int(input())
for i in range(1, n+1):
k = i*d % (4*a)
m = k // a
if m == 0:
x, y = k % a, 0
elif m == 1:
x, y = a , k % a
elif m == 2:
x, y = a - k % a, a
elif m == 3:
x, y = 0, a - k % a
print('%s %s' % (x, y))
|
1395243000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["ALICE\nBOB\nALICE"]
|
aef15a076b04e510e663a41341c8d156
|
NoteIn the first test case of example, in the $$$1$$$-st move, Alice will use the $$$2$$$-nd operation to reverse the string, since doing the $$$1$$$-st operation will result in her loss anyway. This also forces Bob to use the $$$1$$$-st operation. in the $$$2$$$-nd move, Bob has to perform the $$$1$$$-st operation, since the $$$2$$$-nd operation cannot be performed twice in a row. All characters of the string are '1', game over. Alice spends $$$0$$$ dollars while Bob spends $$$1$$$ dollar. Hence, Alice wins.In the second test case of example, in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome. in the $$$2$$$-nd move Bob reverses the string. in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over. Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob wins.
|
The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations: Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
|
For each test case print a single word in a new line: "ALICE", if Alice will win the game, "BOB", if Bob will win the game, "DRAW", if the game ends in a draw.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ contains at least one '0'. Note that there is no limit on the sum of $$$n$$$ over test cases.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_085.jsonl
|
91c8c89dec2af98e5131378a2c031d29
|
256 megabytes
|
["3\n3\n110\n2\n00\n4\n1010"]
|
PASSED
|
import os,sys
from random import randint
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# n = int(input())
# l = len(str(bin(n)[2:]))
# print(pow(2, l - 1) - 1)
# for _ in range(int(input())):
# n = int(input())
# s = input()
# cnt = s.count('0')
# if cnt == 1 or cnt % 2 == 0:
# print('BOB')
# else:
# print('ALICE')
for _ in range(int(input())):
n = int(input())
s = input()
cnt = cntp = 0
for i in range(n // 2):
if s[i] == '1' and s[n - 1 - i] == '0':
cnt += 1
elif s[i] == '0' and s[n - 1 - i] == '1':
cnt += 1
elif s[i] == s[n - 1 - i] == '0':
cntp += 2
if cnt == 0:
cnt = s.count('0')
if cnt == 1 or cnt % 2 == 0:
print('BOB')
else:
print('ALICE')
else:
if n % 2 == 0 or (n % 2 and s[n // 2] == '1'):
print('ALICE')
else:
if cnt == 1 and cntp == 0:
print('DRAW')
else:
print('ALICE')
|
1621521300
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["24", "2835", "0", "46"]
|
45d8827bfee3afeeed79741a2c3b0a0f
|
NoteIn the first example, we can obtain $$$9$$$ strings: "acabac" — there are $$$2$$$ subsequences "abc", "acabbc" — there are $$$4$$$ subsequences "abc", "acabcc" — there are $$$4$$$ subsequences "abc", "acbbac" — there are $$$2$$$ subsequences "abc", "acbbbc" — there are $$$3$$$ subsequences "abc", "acbbcc" — there are $$$4$$$ subsequences "abc", "accbac" — there is $$$1$$$ subsequence "abc", "accbbc" — there are $$$2$$$ subsequences "abc", "accbcc" — there are $$$2$$$ subsequences "abc". So, there are $$$2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24$$$ subsequences "abc" in total.
|
You are given a string $$$s$$$ consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".Let the number of question marks in the string $$$s$$$ be $$$k$$$. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all $$$3^{k}$$$ possible strings consisting only of letters "a", "b" and "c". For example, if $$$s = $$$"ac?b?c" then we can obtain the following strings: $$$[$$$"acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"$$$]$$$.Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo $$$10^{9} + 7$$$.A subsequence of the string $$$t$$$ is such a sequence that can be derived from the string $$$t$$$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions $$$(2, 5, 6)$$$ and a subsequence consisting of letters at positions $$$(3, 5, 6)$$$.
|
Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo $$$10^{9} + 7$$$.
|
The first line of the input contains one integer $$$n$$$ $$$(3 \le n \le 200\,000)$$$ — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_009.jsonl
|
4e5adc354e27acba72d7110f0b62d8f7
|
256 megabytes
|
["6\nac?b?c", "7\n???????", "9\ncccbbbaaa", "5\na???c"]
|
PASSED
|
#matthew's bad code
import re
import sys
MOD = 1000000007
# string s of length n
n = input()
s = input()
# number of a sequences, ab sequences, and abc sequences in s
# sets is the total number of distinct sets generated
# e.g. {a, ?, b} branches into three sets {a, a, b}; {a, b, b}; {a, c, b}
num_a = 0
num_ab = 0
num_abc = 0
num_sets = 1;
for char in s:
if char == 'a':
num_a = (num_a + num_sets + MOD)%MOD
elif char == 'b':
num_ab = (num_a + num_ab + MOD)%MOD
elif char == 'c':
num_abc = (num_ab + num_abc + MOD)%MOD
elif char == '?':
num_abc = (num_ab + 3 * num_abc + MOD)%MOD
num_ab = (num_a + 3 * num_ab + MOD)%MOD
num_a = (num_sets + 3 * num_a + MOD)%MOD
num_sets = (3 * num_sets + MOD)%MOD
#print(num_a, num_ab, num_abc)
print(num_abc)
|
1601280300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
5 seconds
|
["2 1 8 7"]
|
e01cf98c203b8845312ce30af70d3f2e
|
NoteLet d(x, y) be the shortest distance between cities x and y. Then in the example d(2, 1) = 3, d(1, 8) = 7, d(8, 7) = 3. The total distance equals 13.
|
A famous sculptor Cicasso goes to a world tour!Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland.Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help. There are n cities and m one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest. Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1, 5, 2, 4].Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.
|
Print four integers — numbers of cities which Cicasso will visit according to optimal choice of the route. Numbers of cities should be printed in the order that Cicasso will visit them. If there are multiple solutions, print any of them.
|
In the first line there is a pair of integers n and m (4 ≤ n ≤ 3000, 3 ≤ m ≤ 5000) — a number of cities and one-way roads in Berland. Each of the next m lines contains a pair of integers ui, vi (1 ≤ ui, vi ≤ n) — a one-way road from the city ui to the city vi. Note that ui and vi are not required to be distinct. Moreover, it can be several one-way roads between the same pair of cities.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,000 |
train_049.jsonl
|
c92be19baf6f31ad8ad811e1c0efc3ec
|
512 megabytes
|
["8 9\n1 2\n2 3\n3 4\n4 1\n4 5\n5 6\n6 7\n7 8\n8 5"]
|
PASSED
|
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from heapq import heappop, heappush
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
INF = float('inf')
def bfs(graph, start=0):
used = [False] * len(graph)
used[start] = True
dist = [0] * len(graph)
q = [start]
for v in q:
for w in graph[v]:
if not used[w]:
dist[w] = dist[v] + 1
used[w] = True
q.append(w)
return dist, q[-3:]
def main():
n, m = map(int, input().split())
rev_graph = [set() for _ in range(n)]
graph = [set() for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
if u == v:
continue
graph[u - 1].add(v - 1)
rev_graph[v - 1].add(u - 1)
adj = [[0] * n for _ in range(n)]
best_to = [[0] * 3 for _ in range(n)]
best_from = [[0] * 3 for _ in range(n)]
for i in range(n):
adj[i], best_from[i] = bfs(graph, i)
_, best_to[i] = bfs(rev_graph, i)
best_score = 0
sol = (-1, -1, -1, -1)
for c2 in range(n):
for c3 in range(n):
if not adj[c2][c3] or c2 == c3:
continue
for c1 in best_to[c2]:
if c1 in [c2, c3]:
continue
for c4 in best_from[c3]:
if c4 in [c1, c2, c3]:
continue
score = adj[c1][c2] + adj[c2][c3] + adj[c3][c4]
if score > best_score:
best_score = score
sol = (c1 + 1, c2 + 1, c3 + 1, c4 + 1)
print(*sol)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
1461947700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["Ashish", "Ayush"]
|
1a93a35395436f9e15760400f991f1ce
|
NoteFor the $$$1$$$st test case, Ayush can only remove node $$$2$$$ or $$$3$$$, after which node $$$1$$$ becomes a leaf node and Ashish can remove it in his turn.For the $$$2$$$nd test case, Ayush can remove node $$$2$$$ in the first move itself.
|
Ayush and Ashish play a game on an unrooted tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Players make the following move in turns: Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $$$1$$$. A tree is a connected undirected graph without cycles.There is a special node numbered $$$x$$$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.
|
For every test case, if Ayush wins the game, print "Ayush", otherwise print "Ashish" (without quotes).
|
The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of testcases. The description of the test cases follows. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ $$$(1\leq n \leq 1000, 1 \leq x \leq n)$$$ — the number of nodes in the tree and the special node respectively. Each of the next $$$n-1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_001.jsonl
|
8aaad8ff047fc842aab1c7fb021a1a4a
|
256 megabytes
|
["1\n3 1\n2 1\n3 1", "1\n3 2\n1 2\n1 3"]
|
PASSED
|
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
N, X = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
Query.append((N, X-1, graph))
for N, s, graph in Query:
checked = [False]*N
checked[s] = True
odd = 0
for b in graph[s]:
q = [b]
checked[b] = True
Count = 1
while q:
qq = []
for p in q:
for np in graph[p]:
if not checked[np]:
checked[np] = True
qq.append(np)
Count += 1
q = qq
if Count%2 == 1:
odd += 1
if len(graph[s]) <= 1 or odd%2 == 1:
print("Ayush")
else:
print("Ashish")
|
1590935700
|
[
"games",
"trees"
] |
[
1,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["2\n1\n1\n2\n99999999\n3\n0\n1\n9"]
|
be27a43c6844575f1d17487e564803bb
|
NoteThe first sample is parsed in statement.One of the optimal schedule changes for the second sample: Initial schedule. New schedule.In the third sample, we need to move the exam from day $$$1$$$ to any day from $$$4$$$ to $$$100$$$.In the fourth sample, any change in the schedule will only reduce $$$\mu$$$, so the schedule should be left as it is.In the fifth sample, we need to move the exam from day $$$1$$$ to any day from $$$100000000$$$ to $$$300000000$$$.One of the optimal schedule changes for the sixth sample: Initial schedule. New schedule.In the seventh sample, every day is exam day, and it is impossible to rearrange the schedule.
|
Now Dmitry has a session, and he has to pass $$$n$$$ exams. The session starts on day $$$1$$$ and lasts $$$d$$$ days. The $$$i$$$th exam will take place on the day of $$$a_i$$$ ($$$1 \le a_i \le d$$$), all $$$a_i$$$ — are different. Sample, where $$$n=3$$$, $$$d=12$$$, $$$a=[3,5,9]$$$. Orange — exam days. Before the first exam Dmitry will rest $$$2$$$ days, before the second he will rest $$$1$$$ day and before the third he will rest $$$3$$$ days. For the session schedule, Dmitry considers a special value $$$\mu$$$ — the smallest of the rest times before the exam for all exams. For example, for the image above, $$$\mu=1$$$. In other words, for the schedule, he counts exactly $$$n$$$ numbers — how many days he rests between the exam $$$i-1$$$ and $$$i$$$ (for $$$i=0$$$ between the start of the session and the exam $$$i$$$). Then it finds $$$\mu$$$ — the minimum among these $$$n$$$ numbers.Dmitry believes that he can improve the schedule of the session. He may ask to change the date of one exam (change one arbitrary value of $$$a_i$$$). Help him change the date so that all $$$a_i$$$ remain different, and the value of $$$\mu$$$ is as large as possible.For example, for the schedule above, it is most advantageous for Dmitry to move the second exam to the very end of the session. The new schedule will take the form: Now the rest periods before exams are equal to $$$[2,2,5]$$$. So, $$$\mu=2$$$. Dmitry can leave the proposed schedule unchanged (if there is no way to move one exam so that it will lead to an improvement in the situation).
|
For each test case, output the maximum possible value of $$$\mu$$$ if Dmitry can move any one exam to an arbitrary day. All values of $$$a_i$$$ should remain distinct.
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. The descriptions of test cases follow. An empty line is written in the test before each case. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le d \le 10^9$$$) — the number of exams and the length of the session, respectively. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le d, a_i < a_{i+1}$$$), where the $$$i$$$-th number means the date of the $$$i$$$-th exam. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_104.jsonl
|
5834036883962d4542ded40183d3a599
|
256 megabytes
|
["9\n\n\n\n\n3 12\n\n3 5 9\n\n\n\n\n2 5\n\n1 5\n\n\n\n\n2 100\n\n1 2\n\n\n\n\n5 15\n\n3 6 9 12 15\n\n\n\n\n3 1000000000\n\n1 400000000 500000000\n\n\n\n\n2 10\n\n3 4\n\n\n\n\n2 2\n\n1 2\n\n\n\n\n4 15\n\n6 11 12 13\n\n\n\n\n2 20\n\n17 20"]
|
PASSED
|
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main(t):
s = input()
n,d = map(int,input().split())
arr = [0]+list(map(int,input().split()))
distance = [arr[i+1]-arr[i]-1 for i in range(n)]
minleft = [0]*(n+1)
maxleft = [0]*(n+1)
minright = [0]*(n+1)
maxright = [0]*(n+1)
minleft[-1] = float('inf')
minright[-1] = float('inf')
for i in range(n):
minleft[i] = min(distance[i],minleft[i-1])
maxleft[i] = max(distance[i],maxleft[i-1])
for i in range(n-1,-1,-1):
minright[i] = min(distance[i],minright[i+1])
maxright[i] = max(distance[i],maxright[i+1])
# print(distance)
# print(minleft)
# print(maxleft)
# print(minright)
# print(maxright)
def judge(mu):
if minleft[-3]>=mu and d-arr[-2]-1 >= mu:
return True
# print(mu)
for i in range(len(distance)-1):
if minleft[i-1] < mu: break
if minright[i+2] >= mu and distance[i]+distance[i+1]+1 >= mu:
if distance[i]+distance[i+1]>= 2*mu or max(maxleft[i-1],maxright[i+2]) >= 2*mu+1 or d - arr[-1]-1 >= mu:
return True
return False
front = 0
rear = d//n + 2
while front < rear:
mid = (front+rear)//2
if judge(mid):
front = mid + 1
else:
rear = mid
ans = front-1
print(ans)
T = int(input())
t = 1
while t<=T:
main(t)
t += 1
|
1646750100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["8", "4"]
|
5ff4275de91b65115666d4a98b9f3b8b
| null |
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij = apq at (i, j) ≠ (p, q).Dima has already written a song — a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).We'll represent a way to play a song as a sequence of pairs (xi, yi) (1 ≤ i ≤ s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1, y1) and (x2, y2) equals + . The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!
|
In a single line print a single number — the maximum possible complexity of the song.
|
The first line of the input contains four integers n, m, k and s (1 ≤ n, m ≤ 2000, 1 ≤ k ≤ 9, 2 ≤ s ≤ 105). Then follow n lines, each containing m integers aij (1 ≤ aij ≤ k). The number in the i-th row and the j-th column (aij) means a note that the guitar produces on the i-th string and the j-th fret. The last line of the input contains s integers qi (1 ≤ qi ≤ k) — the sequence of notes of the song.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200 |
train_038.jsonl
|
195ce812518164c2ce2c8ad085d61c45
|
256 megabytes
|
["4 6 5 7\n3 1 2 2 3 1\n3 2 2 2 5 5\n4 2 2 2 5 3\n3 2 2 1 4 3\n2 3 1 4 1 5 1", "4 4 9 5\n4 7 9 5\n1 2 1 7\n8 3 4 9\n5 7 7 2\n7 1 9 2 5"]
|
PASSED
|
def solution() : # 最大的距离来自于角落附近的点
n,m,k,s = map(int, input().split())
dis = lambda a,b : abs(a[0] - b[0]) + abs(a[1] - b[1])
corner = [(0,0), (0,m-1), (n-1,0), (n-1,m-1)]
vertex = [[(n,m), (n,-1), (-1,m), (-1,-1)] for _ in range(k+1)]
for i in range(n) :
for j,note in enumerate(map(int, input().split())) :
vertex[note] = [
(i,j) if dis((i,j), c) < dis(v, c) else v
for v,c in zip(vertex[note], corner)]
maxdis = [[-1] * (k+1) for _ in range(k+1)]
pairs = [(0,3),(3,0),(1,2),(2,1)]
for i in range(1, k+1) :
for j in range(i, k+1) :
vi,vj = vertex[i],vertex[j]
maxdis[i][j] = max(dis(vi[a], vj[b]) for a,b in pairs)
maxdis[j][i] = maxdis[i][j]
s = list(map(int, input().split()))
print(max(maxdis[s[i]][s[i+1]] for i in range(len(s) - 1)))
solution()
|
1385307000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\n2\n1 3 \nNO", "YES\n8\n1 3 4 5 6 9 14 17"]
|
d4e1ec5445de029895a9c47ab89db3a2
|
NoteThe picture below shows the second example test.
|
Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold: All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open. It should be possible to travel between any two houses using the underground passages that are open. Teachers should not live in houses, directly connected by a passage. Please help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.
|
For each test case, if there is no way to choose the desired set of houses, output "NO". Otherwise, output "YES", then the total number of houses chosen, and then the indices of the chosen houses in arbitrary order.
|
The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10^5$$$). Each test case starts with two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le 3 \cdot 10^5$$$) — the number of houses and the number of passages. Then $$$m$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), describing a passage between the houses $$$u$$$ and $$$v$$$. It is guaranteed that there are no two passages connecting the same pair of houses. The sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_084.jsonl
|
2e4c2d76cda0fd311bdc5dccdb3cc28d
|
256 megabytes
|
["2\n3 2\n3 2\n2 1\n4 2\n1 4\n2 3", "1\n17 27\n1 8\n2 9\n3 10\n4 11\n5 12\n6 13\n7 14\n8 9\n8 14\n8 15\n9 10\n9 15\n10 11\n10 15\n10 17\n11 12\n11 17\n12 13\n12 16\n12 17\n13 14\n13 16\n14 16\n14 15\n15 16\n15 17\n16 17"]
|
PASSED
|
import sys
input=sys.stdin.buffer.readline
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
g=[[] for i in range(n+1)]
for __ in range(m):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
black=[-1 for i in range(n+1)]
ans=[]
path=[1]
black[0]=2
black[1]=1
while path:
x=path.pop()
for y in g[x]:
if black[x]==1:
if black[y]==-1:
path.append(y)
black[y]=0
elif black[y]==-1:
path.append(y)
black[y]=1
if -1 in black:
print('NO')
continue
print('YES')
for i in range(1,n+1):
if black[i]==1:
ans.append(i)
print(len(ans))
print(" ".join(str(i) for i in ans))
|
1609857300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["NO", "YES"]
|
8ea24f3339b2ec67a769243dc68a47b2
| null |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
|
The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_001.jsonl
|
07edbc8ad40aed7fb09604d5456befb9
|
256 megabytes
|
["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"]
|
PASSED
|
n=int(input())
a=[]
for i in range(n):
a.append(list(map(int,input().split())))
c=0
for j in range(3):
s=0
for k in range(n):
s=s+a[k][j]
if s==0:
c+=1
if c==3:
print("YES")
else:
print("NO")
|
1300809600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4\n4\n3\n5\n3"]
|
c0d23fe28ebddbfc960674e3b10122ad
|
NoteIn the first test case, $$$S=\{0,1,3,4\}$$$, $$$a=\operatorname{mex}(S)=2$$$, $$$b=\max(S)=4$$$, $$$\lceil\frac{a+b}{2}\rceil=3$$$. So $$$3$$$ is added into $$$S$$$, and $$$S$$$ becomes $$$\{0,1,3,3,4\}$$$. The answer is $$$4$$$.In the second test case, $$$S=\{0,1,4\}$$$, $$$a=\operatorname{mex}(S)=2$$$, $$$b=\max(S)=4$$$, $$$\lceil\frac{a+b}{2}\rceil=3$$$. So $$$3$$$ is added into $$$S$$$, and $$$S$$$ becomes $$$\{0,1,3,4\}$$$. The answer is $$$4$$$.
|
You are given a multiset $$$S$$$ initially consisting of $$$n$$$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.You will perform the following operation $$$k$$$ times: Add the element $$$\lceil\frac{a+b}{2}\rceil$$$ (rounded up) into $$$S$$$, where $$$a = \operatorname{mex}(S)$$$ and $$$b = \max(S)$$$. If this number is already in the set, it is added again. Here $$$\operatorname{max}$$$ of a multiset denotes the maximum integer in the multiset, and $$$\operatorname{mex}$$$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example: $$$\operatorname{mex}(\{1,4,0,2\})=3$$$; $$$\operatorname{mex}(\{2,5,1\})=0$$$. Your task is to calculate the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.
|
For each test case, print the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.
|
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1\le n\le 10^5$$$, $$$0\le k\le 10^9$$$) — the initial size of the multiset $$$S$$$ and how many operations you need to perform. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_i\le 10^9$$$) — the numbers in the initial multiset. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,100 |
train_104.jsonl
|
f2791a6ebff39aa743b4272f6457cc43
|
256 megabytes
|
["5\n4 1\n0 1 3 4\n3 1\n0 1 4\n3 0\n0 1 4\n3 2\n0 1 2\n3 2\n1 2 3"]
|
PASSED
|
def ceil(a,b):
return ((a+b-1)//b)
for _ in range(int(input())):
n,k = map(int,input().split())
a = set(map(int,input().split()))
if k==0:
print(len(a))
continue
maxi = max(a)
for i in range(maxi+2):
if i not in a:
mex = i
break
length = len(a)
if mex<maxi:
new_one = ceil(mex+maxi,2)
if new_one not in a:
print(length+1)
else:
print(length)
else:
print(length+k)
|
1615377900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["9", "8"]
|
13fa378c913bb7a15612327099b59f83
| null |
Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?
|
Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
|
The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000 |
train_009.jsonl
|
c25a96faa49e3e48658225110b010057
|
256 megabytes
|
["3 4\n3 1 6 -2\n2 3 3\n2 -5 1\n2 3 1 3", "6 1\n4 0 8 -3 -10\n8 3 -2 -5 10 8 -9 -5 -4\n1 0\n1 -3\n3 -8 5 6\n2 9 6\n1"]
|
PASSED
|
(n , m) = map(int,raw_input().split())
arr = []
for i in range (n):
arr.append(map(int,raw_input().split())[1:])
seq = map(int,raw_input().split())
def gao(x):
ans = - 2 ** 64
now = 0
for i in range (len(x)):
now += x[i]
ans = max(ans,now)
return ans;
def gao2(x):
now = x[0]
ans = now
for i in range(1,len(x)):
now = max(x[i] , now + x[i])
ans = max(ans,now)
return ans
def doit(x):
ans = - 2 ** 64
now = 0
for i in range (len(x) - 1, -1 , -1):
now += x[i]
ans = max(ans,now)
return ans;
dp = []
pre = []
s = []
af = []
bak = []
for i in range (n):
pre.append(doit(arr[i]))
s.append(sum(arr[i]))
af.append(gao(arr[i]))
bak.append(gao2(arr[i]))
dp.append([sum(arr[seq[0] - 1]),pre[seq[0] - 1]])
for i in range (1,m):
add = max(dp[-1][0],pre[seq[i-1] - 1])
dp.append([ add + s[seq[i] - 1] , add + af[seq[i] - 1] ] )
ans = - 2 ** 64
for i in range (len(seq)):
ans = max(ans,bak[seq[i] - 1])
for i in range (len(dp)):
ans = max(ans,dp[i][0])
ans = max(ans,dp[i][1])
print ans
|
1302706800
|
[
"math",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
0,
1
] |
|
1 second
|
["? 4\n0 0\n2 0\n2 3\n0 3\n\n? 4\n0 0\n0 1\n3 1\n3 0\n\n! 1.5 0.5"]
|
7921be2d165d9430cedfeadb6e934314
|
NoteIn the first test from the statement, the aliens poisoned a square of corn with vertices at points with coordinates $$$(1.5, 0.5)$$$, $$$(1.5, 1.5)$$$, $$$(2.5, 1.5)$$$, $$$(2.5, 0.5)$$$. In the picture, it is red, the polygon selected in the query is blue, and their intersection is green.Picture for the first query: Picture for the second query:
|
This is an interactive problem.Farmer Stanley grows corn on a rectangular field of size $$$ n \times m $$$ meters with corners in points $$$(0, 0)$$$, $$$(0, m)$$$, $$$(n, 0)$$$, $$$(n, m)$$$. This year the harvest was plentiful and corn covered the whole field.The night before harvest aliens arrived and poisoned the corn in a single $$$1 \times 1$$$ square with sides parallel to field borders. The corn inside the square must not be eaten, but you cannot distinguish it from ordinary corn by sight. Stanley can only collect a sample of corn from an arbitrary polygon and bring it to the laboratory, where it will be analyzed and Stanley will be told the amount of corn in the sample that was poisoned. Since the harvest will soon deteriorate, such a study can be carried out no more than $$$5$$$ times.More formally, it is allowed to make no more than $$$5$$$ queries, each of them calculates the area of intersection of a chosen polygon with a square of poisoned corn. It is necessary to find out the coordinates of the lower-left corner of the drawn square (the vertex of the square with the smallest $$$x$$$ and $$$y$$$ coordinates).
| null |
First line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — field sizes.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_082.jsonl
|
e9d757e6b2150cb1dfe0773e0ad444bb
|
256 megabytes
|
["3 3\n\n\n\n\n\n0.5\n\n\n\n\n\n0.5"]
|
PASSED
|
MIN = '0.000000000000001';n,m=[int(i) for i in input().split()]; print(f'? {2*m+1}',flush=True);print(0,0);
for i in range(m):
print(n,i,flush=True);print(MIN,i+1,flush=True)
hx=float(input());print(f'? {2*n+1}',flush=True);print(0,0)
for i in range(n):
print(i,m,flush=True);print(i+1,MIN,flush=True)
hy = float(input());x=max(n*(1-hx)-0.5,0);y=max(m*(1-hy)-0.5,0);print('!','{:.9f}'.format(x),'{:.9f}'.format(y),flush=True)
|
1661006100
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["First", "Second"]
|
bbf2dbdea6dd3aa45250ab5a86833558
| null |
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
|
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
|
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,300 |
train_000.jsonl
|
d696f88cccde2107b2e4aa60d7554307
|
256 megabytes
|
["aba", "abca"]
|
PASSED
|
s = raw_input()
t = sum( s.count(x)&1 for x in set(s) )
print 'First' if t&1 or t==0 else 'Second'
|
1361719800
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n1\n0"]
|
adf4239de3b0034cc690dad6160cf1d0
|
NoteThe picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates.
|
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $$$n$$$ distinct lines, given by equations $$$y = x + p_i$$$ for some distinct $$$p_1, p_2, \ldots, p_n$$$.Then JLS drew on the same paper sheet $$$m$$$ distinct lines given by equations $$$y = -x + q_i$$$ for some distinct $$$q_1, q_2, \ldots, q_m$$$.DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.
|
For each test case in the input print a single integer — the number of line pairs with integer intersection points.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$), the number of test cases in the input. Then follow the test case descriptions. The first line of a test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of lines drawn by DLS. The second line of a test case contains $$$n$$$ distinct integers $$$p_i$$$ ($$$0 \le p_i \le 10^9$$$) describing the lines drawn by DLS. The integer $$$p_i$$$ describes a line given by the equation $$$y = x + p_i$$$. The third line of a test case contains an integer $$$m$$$ ($$$1 \le m \le 10^5$$$), the number of lines drawn by JLS. The fourth line of a test case contains $$$m$$$ distinct integers $$$q_i$$$ ($$$0 \le q_i \le 10^9$$$) describing the lines drawn by JLS. The integer $$$q_i$$$ describes a line given by the equation $$$y = -x + q_i$$$. The sum of the values of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$. Similarly, the sum of the values of $$$m$$$ over all test cases in the input does not exceed $$$10^5$$$. In hacks it is allowed to use only one test case in the input, so $$$t=1$$$ should be satisfied.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_015.jsonl
|
8da0efa55f63ae2fa4ac0a6cef3fffed
|
512 megabytes
|
["3\n3\n1 3 2\n2\n0 3\n1\n1\n1\n1\n1\n2\n1\n1"]
|
PASSED
|
t = int(input())
for i in range(t):
z1=0
f1=0
z2=0
f2=0
s=0
n = int(input())
p = [int(z) for z in input().split(' ')]
m = int(input())
q = [int(z) for z in input().split(' ')]
for j in range(n):
if p[j] % 2 == 0:
z1=z1+1
else:
f1=f1+1
for k in range(m):
if q[k] % 2 == 0:
z2=z2+1
else:
f2=f2+1
s=z1*z2 + f1*f2
print(s)
|
1571562300
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["-31", "1992"]
|
6d4e18987326dbb0ef69cd6756965835
| null |
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1.In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time ti at section ai. If you are at section x (1 ≤ x ≤ n) at the time of i-th launching, you'll gain happiness value bi - |ai - x| (note that the happiness value might be a negative value).You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness.Note that two or more fireworks can be launched at the same time.
|
Print a single integer — the maximum sum of happiness that you can gain from watching all the fireworks. Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
The first line contains three integers n, m, d (1 ≤ n ≤ 150000; 1 ≤ m ≤ 300; 1 ≤ d ≤ n). Each of the next m lines contains integers ai, bi, ti (1 ≤ ai ≤ n; 1 ≤ bi ≤ 109; 1 ≤ ti ≤ 109). The i-th line contains description of the i-th launching. It is guaranteed that the condition ti ≤ ti + 1 (1 ≤ i < m) will be satisfied.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_012.jsonl
|
aac7bb81a00dce4b5c5ed985816ade48
|
256 megabytes
|
["50 3 1\n49 1 1\n26 1 4\n6 1 10", "10 2 1\n1 1000 4\n9 1000 4"]
|
PASSED
|
class SortedList(list):
def add(self, other):
left = -1
right = len(self)
while right - left > 1:
mid = (right + left) >> 1
if other < self[mid]:
right = mid
else:
left = mid
super().insert(right, other)
INF = int(3e18)
def solve_good(n, m, d, a, b, t):
left = SortedList()
left.append(-INF)
right = SortedList()
right.append(INF)
lborder = -INF
rborder = INF
tprev = 0
ans = 0
for ai, bi, ti in zip(a, b, t):
ans += bi
dt = ti - tprev
interval = dt * d
tprev = ti
lborder += interval
rborder -= interval
lefta = lborder + ai
righta = rborder - (n - ai)
if lefta < left[-1]:
top = left.pop()
ans -= abs(top - lefta)
left.add(lefta)
left.add(lefta)
right.add(rborder - (n - abs(top - lborder)))
elif righta > right[0]:
top = right.pop(0)
ans -= abs(top - righta)
right.add(righta)
right.add(righta)
left.add(lborder + n - abs(top - rborder))
else:
left.add(lefta)
right.add(righta)
return ans
n, m, d = [int(elem) for elem in input().split()]
a, b, t = [], [], []
for i in range(m):
ai, bi, ti = [int(elem) for elem in input().split()]
a.append(ai)
b.append(bi)
t.append(ti)
print(solve_good(n, m, d, a, b, t))
|
1386943200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0 0 0 0", "0 0 0 1 1 2"]
|
2d4dbada60ebcf0bdaead8d0c1c0e2c1
| null |
A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.
|
Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.
|
The first line contains an integer n (3 ≤ n ≤ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi ≠ yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_012.jsonl
|
c1e3ebc8b09d7e1cda084b13f5b22546
|
256 megabytes
|
["4\n1 3\n4 3\n4 2\n1 2", "6\n1 2\n3 4\n6 4\n2 3\n1 3\n3 5"]
|
PASSED
|
from collections import deque
import copy
def bfs(g,root):
Q = deque([root])
visited = [root]
while len(Q) > 0:
v = Q.pop()
for x in g[v]:
if x not in visited and len(g[x]) < 3:
Q.appendleft(x)
visited.append(x)
return visited
def remove(g,vertices):
for v in vertices:
for sosed in g[v]:
g[sosed].remove(v)
del g[v]
def get_cycle(g,deg):
Q = [k for k,v in deg.items() if v == 1] #stopnje 1
g_copy = copy.deepcopy(g)
while len(Q) > 0:
v = Q.pop()
vertices = bfs(g_copy,v)
remove(g_copy,vertices)
return [k for k in g_copy.keys()]
def new_graph(g,cycle):
sosedi = set([])
new_v = max([k for k in g.keys()])+1
g_copy = copy.deepcopy(g)
for v in cycle:
for sosed in g_copy[v]:
if sosed not in cycle:
sosedi.add(sosed)
g_copy[sosed].remove(v)
del g_copy[v]
g_copy[new_v] = list(sosedi)
for x in sosedi:
if x not in cycle:
g_copy[x].append(new_v)
return g_copy
def get_result(g,cycle):
root = max([k for k in g.keys()])
rez = {x:0 for x in cycle}
rez[root] = 0
Q = deque([root])
visited = [root]
while len(Q) > 0:
v = Q.pop()
for x in g[v]:
if x not in visited:
visited.append(x)
Q.appendleft(x)
rez[x] = rez[v]+1
return rez
n = int(raw_input())
g = {i:[] for i in range(1,n+1)}
deg = {i:0 for i in range(1,n+1)}
for i in range(1,n+1):
a,b = map(int, raw_input().split(" "))
g[a].append(b)
g[b].append(a)
deg[a] += 1
deg[b] += 1
cycle = get_cycle(g,deg)
new_g = new_graph(g,cycle)
rez = get_result(new_g,cycle)
for i in range(1,n+1):
print rez[i],
|
1322233200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["8", "28", "0"]
|
03907ca0d34a2c80942ed3968b2c067d
|
NoteIn the first example, the transformations are $$$2 \rightarrow 4 \rightarrow (-2) \rightarrow (-4) \rightarrow 2$$$.In the third example, it is impossible to perform even a single transformation.
|
You are given a positive integer $$$n$$$ greater or equal to $$$2$$$. For every pair of integers $$$a$$$ and $$$b$$$ ($$$2 \le |a|, |b| \le n$$$), you can transform $$$a$$$ into $$$b$$$ if and only if there exists an integer $$$x$$$ such that $$$1 < |x|$$$ and ($$$a \cdot x = b$$$ or $$$b \cdot x = a$$$), where $$$|x|$$$ denotes the absolute value of $$$x$$$.After such a transformation, your score increases by $$$|x|$$$ points and you are not allowed to transform $$$a$$$ into $$$b$$$ nor $$$b$$$ into $$$a$$$ anymore.Initially, you have a score of $$$0$$$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?
|
Print an only integer — the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print $$$0$$$.
|
A single line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the given integer described above.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_043.jsonl
|
49655470591f72f2fc46c4acdde38e74
|
256 megabytes
|
["4", "6", "2"]
|
PASSED
|
class IntegersFun():
def __init__(self, n):
self.n = n
def get_value(self):
sm = 0
for i in range(2,self.n+1):
for j in range(2*i, self.n+1, i):
sm += 4*j/i
return int(sm)
n = int(input())
print(IntegersFun(n).get_value())
|
1542209700
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.