prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
β | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
β | prob_desc_input_spec
stringlengths 38
2.42k
β | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
β | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 seconds
|
["6", "1", "2"]
|
69135ef7422b5811ae935a9d00796f88
|
NoteIn the first example, these are all the hidden strings and their indice sets: a occurs at $$$(1)$$$, $$$(2)$$$, $$$(3)$$$ b occurs at $$$(4)$$$, $$$(5)$$$ ab occurs at $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,4)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$ aa occurs at $$$(1,2)$$$, $$$(1,3)$$$, $$$(2,3)$$$ bb occurs at $$$(4,5)$$$ aab occurs at $$$(1,3,5)$$$, $$$(2,3,4)$$$ aaa occurs at $$$(1,2,3)$$$ abb occurs at $$$(3,4,5)$$$ aaab occurs at $$$(1,2,3,4)$$$ aabb occurs at $$$(2,3,4,5)$$$ aaabb occurs at $$$(1,2,3,4,5)$$$ Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
|
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string $$$s$$$ of lowercase Latin letters. She considers a string $$$t$$$ as hidden in string $$$s$$$ if $$$t$$$ exists as a subsequence of $$$s$$$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $$$1$$$, $$$3$$$, and $$$5$$$, which form an arithmetic progression with a common difference of $$$2$$$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $$$S$$$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden $$$3$$$ times, b is hidden $$$2$$$ times, ab is hidden $$$6$$$ times, aa is hidden $$$3$$$ times, bb is hidden $$$1$$$ time, aab is hidden $$$2$$$ times, aaa is hidden $$$1$$$ time, abb is hidden $$$1$$$ time, aaab is hidden $$$1$$$ time, aabb is hidden $$$1$$$ time, and aaabb is hidden $$$1$$$ time. The number of occurrences of the secret message is $$$6$$$.
|
Output a single integer Β β the number of occurrences of the secret message.
|
The first line contains a string $$$s$$$ of lowercase Latin letters ($$$1 \le |s| \le 10^5$$$) β the text that Bessie intercepted.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_004.jsonl
|
413da263785f4bed8d2237048d4b798d
|
256 megabytes
|
["aaabb", "usaco", "lol"]
|
PASSED
|
from string import ascii_lowercase
s = input()
lc = {c: 0 for c in ascii_lowercase}
llc = dict()
for c in s:
for v in lc:
if v + c not in llc:
llc[v + c] = lc[v]
else:
llc[v + c] += lc[v]
lc[c] += 1
print(max(*lc.values(), *llc.values()))
|
1581953700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
1 second
|
["2\n1 6", "2\n1 4"]
|
dfd60a02670749c67b0f96df1a0709b9
|
NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations.
|
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.
|
The first line should contain integer $$$l$$$Β β the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 1000$$$, $$$0 \leq k \leq 1000$$$)Β β the number of skewers and the number of skewers from each side that are turned in one step.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_011.jsonl
|
b26792ff06cfe7f19202ebaf31e030a2
|
512 megabytes
|
["7 2", "5 1"]
|
PASSED
|
n, k = map(int, input().split())
a = 1000000
af = []
for i in range(k+1):
f = []
for j in range(i+1, n+1, 2*k+1):
f.append(j)
if i+1 > n:
break
if f[-1]+k >= n:
if a > len(f):
a = len(f)
af = f[:]
print(a)
print(*af)
|
1536165300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["NO", "YES\n3 5 4 1\n3 5 3 1\n3 5 2 1"]
|
d2cc50595767485707338a40a6dd9a78
| null |
You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route β the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit).Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.
|
If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1,β...,βpl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO.
|
The first line contains two integers n and m (1ββ€βn,βmββ€β2Β·105) β the number of intersections and roads, respectively. The following m lines contain two integers β the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads.
|
standard output
|
standard input
|
Python 3
|
Python
| 3,100 |
train_003.jsonl
|
ad966cbdab6b8b1b396fdd957d32e934
|
256 megabytes
|
["4 4\n1 2\n2 3\n3 4\n4 1", "5 6\n1 2\n1 3\n1 4\n2 5\n3 5\n4 5"]
|
PASSED
|
from typing import List
import sys
n, m = [int(a) for a in input().split(' ')]
adj: List[List[int]] = [[]] + [[] for _ in range(n)]
visited: List[bool] = [False] * (n + 1)
parent: List[int] = [0] * (n + 1)
depth: List[int] = [0] * (n + 1)
low: List[int] = [0] * (n + 1)
cx: List[int] = [0] * (n + 1)
cy: List[int] = [0] * (n + 1)
qi: List[int] = [0] * (n + 1)
for i in range(m):
u, v = [int(a) for a in input().split(' ')]
adj[u].append(v)
adj[v].append(u)
def solve():
for i in range(1, n + 1):
if not visited[i]:
# dfs(i)
dfs2(i)
print('NO')
def lca(a, b):
while depth[a] > depth[b]:
a = parent[a]
while depth[b] > depth[a]:
b = parent[b]
while a != b:
a = parent[a]
b = parent[b]
return a
def parent_path(a, b):
p = []
while a != b:
p.append(str(a))
a = parent[a]
p.append(str(b))
return p
def gett(a, b, u, v):
if depth[b] > depth[v]:
a, b, u, v = u, v, a, b
e = lca(a, u)
print('YES')
c1 = parent_path(e, v)
print(' '.join([str(len(c1))] + c1))
c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b)))
print(' '.join([str(len(c2))] + c2))
c3 = list(reversed(parent_path(u, e))) + [str(v)]
print(' '.join([str(len(c3))] + c3))
exit(0)
def dfs(i):
visited[i] = True
depth[i] = depth[parent[i]] + 1
for ni in adj[i]:
if parent[i] != ni:
if not visited[ni]:
parent[ni] = i
dfs(ni)
elif depth[ni] < depth[i]:
x = i
while x != ni:
if cx[x] and cy[x]:
gett(cx[x], cy[x], i, ni)
else:
cx[x] = i
cy[x] = ni
x = parent[x]
def dfs2(i):
visited[i] = True
q: List[int] = []
q.append(i)
while len(q) > 0:
u = q[-1]
if qi[u] >= len(adj[u]):
q.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
depth[v] = depth[u] + 1
visited[v] = True
q.append(v)
elif depth[v] < depth[u]:
x = u
while x != v:
if cx[x] and cy[x]:
gett(cx[x], cy[x], u, v)
else:
cx[x] = u
cy[x] = v
x = parent[x]
solve()
|
1425279600
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n-1\n9"]
|
6551be8f4000da2288bf835169662aa2
| null |
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.A common divisor for two positive numbers is a number which both numbers are divisible by.But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. lowββ€βdββ€βhigh. It is possible that there is no common divisor in the given range.You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.
|
Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.
|
The first line contains two integers a and b, the two integers as described above (1ββ€βa,βbββ€β109). The second line contains one integer n, the number of queries (1ββ€βnββ€β104). Then n lines follow, each line contains one query consisting of two integers, low and high (1ββ€βlowββ€βhighββ€β109).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_017.jsonl
|
ead01fbc1a1435a906d5b382815e5ef0
|
256 megabytes
|
["9 27\n3\n1 5\n10 11\n9 11"]
|
PASSED
|
a, b = map(int, input().split())
import math
g = math.gcd(a, b)
lis = [i for i in range(1, int(math.sqrt(g)) + 1) if g%i == 0]
for i in lis[::-1]: lis.append(g//i)
n = int(input())
for _ in range(n):
a, b = map(int , input().split())
import bisect
x = bisect.bisect(lis, b) - 1
if lis[x] < a: print(-1)
else: print(lis[x])
|
1302706800
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["4\nNNYY\nNNYY\nYYNN\nYYNN", "8\nNNYYYNNN\nNNNNNYYY\nYNNNNYYY\nYNNNNYYY\nYNNNNYYY\nNYYYYNNN\nNYYYYNNN\nNYYYYNNN", "2\nNY\nYN"]
|
30a8d761d5b5103a5b926290634c8fbe
|
NoteIn first example, there are 2 shortest paths: 1-3-2 and 1-4-2.In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2.
|
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
|
You should output a graph G with n vertexes (2ββ€βnββ€β1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gijβ=βGji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
|
The first line contains a single integer k (1ββ€βkββ€β109).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_001.jsonl
|
bfa23404a37efcb9776920588ae7d692
|
256 megabytes
|
["2", "9", "1"]
|
PASSED
|
k = int(input())
edges = [['N' for i in range(1010)] for j in range(1010)]
vertices = 2
def add_edge(a, b):
global edges
edges[a][b] = edges[b][a] = 'Y'
for i in range(1, 29 + 1):
vertices += 3
add_edge(i * 3, i * 3 - 1)
add_edge(i * 3, i * 3 + 2)
add_edge(i * 3 + 1, i * 3 - 1)
add_edge(i * 3 + 1, i * 3 + 2)
for bit in range(30):
if (1 << bit) & k:
lst = 1
for i in range((29 - bit) * 2):
vertices += 1
add_edge(lst, vertices)
lst = vertices
add_edge(lst, 3 * bit + 2)
print(vertices)
if 0:
for i in range(1, vertices + 1):
print(i, ':', '\n\t', end='')
for j in range(1, vertices + 1):
if edges[i][j] == 'Y':
print(j, end=' ')
print('')
else:
print('\n'.join(map(lambda x: ''.join(x[1:vertices+1]), edges[1:vertices + 1])))
|
1391442000
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
1 second
|
["2 3 2 3 3", "3 3 3 3 3"]
|
59154ca15716f0c1c91a37d34c5bbf1d
| null |
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1,βa2,β...,βan is the sequence of points earned by the team of students in the non-increasing order (a1ββ₯βa2ββ₯β...ββ₯βan), then skβ=βa1β+βa2β+β...β+βak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
|
Print exactly n integers a1,βa2,β...,βan β the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
|
The first line of the input contains exactly six integers n,βk,βl,βr,βsall,βsk (1ββ€βn,βk,βl,βrββ€β1000; lββ€βr; kββ€βn; 1ββ€βskββ€βsallββ€β106). It's guaranteed that the input is such that the answer exists.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,400 |
train_028.jsonl
|
a5c13a7a7b0f9cbcabb58aa0b6151e77
|
256 megabytes
|
["5 3 1 3 13 9", "5 3 1 3 15 9"]
|
PASSED
|
n,k,l,r,sa,sk=map(int,raw_input().split())
ar=[]
for i in xrange(n):
ar.append(0)
while sk>0:
i=0
while i<k:
if sk>0:
ar[i]+=1
sk-=1
i+=1
else:
break
sa-=sum(ar)
while sa>0:
i=k
while i<n:
if sa>0:
ar[i]+=1
sa-=1
i+=1
else:
break
for i in ar:
print i,
|
1385739000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3 4 2 1", "-1", "4 5 1 2 3"]
|
f52a4f8c4d84733a8e78a5825b63bdbc
| null |
A permutation of length n is an array containing each integer from 1 to n exactly once. For example, qβ=β[4,β5,β1,β2,β3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i]β=βq[q[i]] for each iβ=β1... n. For example, the square of qβ=β[4,β5,β1,β2,β3] is pβ=βq2β=β[2,β3,β4,β5,β1].This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2β=βp. If there are several such q find any of them.
|
If there is no permutation q such that q2β=βp print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1ββ€βqiββ€βn) β the elements of the permutation q. If there are several solutions print any of them.
|
The first line contains integer n (1ββ€βnββ€β106) β the number of elements in permutation p. The second line contains n distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn) β the elements of permutation p.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200 |
train_078.jsonl
|
f72311f55a7ddb13537aedb87076082f
|
256 megabytes
|
["4\n2 1 4 3", "4\n2 1 3 4", "5\n2 3 4 5 1"]
|
PASSED
|
from __future__ import division
from collections import defaultdict
import random
#import numpy as np
def get_cycle(perm, i):
start = i
current = i
res = [i]
while True:
new = perm[current]
perm[current] = -1
current = new
if current == start:
return res
res.append(current)
def invert_odd_cycle(res, cycle):
n = len(cycle)
m = (n - 1) // 2
for i, e in enumerate(cycle):
res[e] = cycle[(n + i - m) % n]
def invert_two_even_cycles(res, cycle1, cycle2):
n = len(cycle1)
for i in range(n):
res[cycle1[i]] = cycle2[i]
res[cycle2[i]] = cycle1[(i+1)%n]
def _sqrtp(perm):
perm = list(perm)
res = [None] * len(perm)
start = 0
even_cycles = defaultdict(list)
while True:
while perm[start] == -1:
start += 1
if start >= len(perm):
for cycles in even_cycles.values():
if len(cycles) % 2 == 1:
return -1
for i in range(len(cycles) // 2):
invert_two_even_cycles(res, cycles[2 * i], cycles[2 * i + 1])
return tuple(res)
cycle = get_cycle(perm, start)
if len(cycle) % 2 == 1:
invert_odd_cycle(res, cycle)
else:
even_cycles[len(cycle)].append(cycle)
def sqrtp(perm):
res = _sqrtp(decp(perm))
if isinstance(res, tuple):
return incp(res)
else:
return res
def _sqrp(perm):
res = [None]*len(perm)
for i,e in enumerate(perm):
res[i] = perm[perm[i]]
return tuple(res)
def sqrp(perm):
return incp(_sqrp(decp(perm)))
def incp(perm):
return tuple(n + 1 for n in perm)
def decp(perm):
return tuple(n - 1 for n in perm)
def randp(n):
res = list(range(n))
for i in range(1, n):
#j = np.random.randint(0, i)
j = random.randint(0, i)
a = res[i]
res[i] = res[j]
res[j] = a
return incp(res)
raw_input()
perm = map(int, raw_input().split())
res = sqrtp(perm)
print(' '.join(map(str, res)) if isinstance(res, tuple) else res)
|
1451055600
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["6\n2"]
|
ca3e121e8c8afe97b5cfdc9027892f00
| null |
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
|
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
|
The first line contains two integers N ΠΈ MΒ β size of the city (1ββ€βN,βMββ€β109). In the next line there is a single integer C (1ββ€βCββ€β105)Β β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1ββ€βxββ€βN, 1ββ€βyββ€βM). The next line contains an integer HΒ β the number of restaurants (1ββ€βHββ€β105). Following H lines contain descriptions of restaurants in the same format. Several restaurants and hotels may be located near the same crossing.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_034.jsonl
|
dfb537ef9894eac3b9ad4f9e86d10fea
|
256 megabytes
|
["10 10\n2\n1 1\n3 3\n2\n1 10\n4 4"]
|
PASSED
|
#!/usr/bin/env python3
n, m = map(int, input().split())
minx = miny = n + m
maxx = maxy = - minx
dist = n + m + 1
c = int(input())
for _ in range(c):
x, y = map(int, input().split())
minx = min(minx, x - y)
miny = min(miny, x + y)
maxx = max(maxx, x - y)
maxy = max(maxy, x + y)
h = int(input())
for i in range(h):
a, b = map(int, input().split())
x = a - b
y = a + b
maxxy = max(
max(abs(minx - x), abs(maxx - x)),
max(abs(miny - y), abs(maxy - y))
)
if maxxy < dist:
dist = maxxy
res = i + 1
print(dist)
print(res)
|
1416519000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["NO\nYES\nYES\nYES"]
|
07e56d4031bcb119d2f684203f7ed133
|
NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.
|
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.
|
For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of polygons in the market. Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_005.jsonl
|
4e9dad38db6f85449065e8d54f5e4a9f
|
256 megabytes
|
["4\n3\n4\n12\n1000000000"]
|
PASSED
|
t=int(input())
for _ in range(t):
n=int(input())
if(n%4==0):
print("YES")
else:
print("NO")
|
1592921100
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2", "3"]
|
81c6342b7229892d71cb43e72aee99e9
|
NoteIn the first sample, sequence of rooms Petya visited could be, for example 1βββ1βββ2, 1βββ2βββ1 or 1βββ2βββ3. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1βββ2βββ3βββ1βββ2βββ1.
|
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
|
In the only line print a single integer β the minimum possible number of rooms in Paris catacombs.
|
The first line contains a single integer n (1ββ€βnββ€β2Β·105) β then number of notes in Petya's logbook. The second line contains n non-negative integers t1,βt2,β...,βtn (0ββ€βtiβ<βi) β notes in the logbook.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_009.jsonl
|
8a240df0e19516399ffaea7bd416a35a
|
256 megabytes
|
["2\n0 0", "5\n0 1 0 1 3"]
|
PASSED
|
n, data = int(input()), list(map(int, input().split()))
time = [0] + [-100] * (3 * (10 ** 5))
rooms = [0]
for i in range(1, n + 1):
if(time[data[i - 1]] != -100 and rooms[time[data[i - 1]]] == data[i - 1]):
rooms[time[data[i - 1]]] = i
time[i] = time[data[i - 1]]
else:
rooms.append(i)
time[i] = len(rooms) - 1
print(len(rooms))
|
1510502700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1", "3", "1"]
|
31014efa929af5e4b7d9987bd9b59918
|
NoteOne of the possible answers to the first example: The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example: The area of this plot is 12, the height of this plot is 3.
|
You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time: Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.
|
Print one integer β the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.
|
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^{18}$$$) β the number of vertices in a plot of a piecewise function and the area we need to obtain.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_003.jsonl
|
38627e93f16ce65a70706e7068032689
|
256 megabytes
|
["4 3", "4 12", "999999999999999999 999999999999999986"]
|
PASSED
|
import math
n,k = list(map(int, input().split(' ')))
print(-(-k//n))
# if k<= n:
# print(1)
# else:
# if k%n:
# print(int(math.ceil(k/n)))
# else:
# print(int(k/n))
|
1536330900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5.000000000000000", "0.400000000000000"]
|
131db180c7afad3e5a3342407408fded
|
NoteFirst sample corresponds to the example in the problem statement.
|
Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.For example, suppose Mikhail is suggested to work on three projects and a1β=β6, b1β=β2, a2β=β1, b2β=β3, a3β=β2, b3β=β6. Also, pβ=β20 and qβ=β20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1Β·2.5β+βa2Β·0β+βa3Β·2.5β=β6Β·2.5β+β1Β·0β+β2Β·2.5β=β20 and b1Β·2.5β+βb2Β·0β+βb3Β·2.5β=β2Β·2.5β+β3Β·0β+β6Β·2.5β=β20.
|
Print a real valueΒ β the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10β-β6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
|
The first line of the input contains three integers n, p and q (1ββ€βnββ€β100β000,β1ββ€βp,βqββ€β1β000β000)Β β the number of projects and the required number of experience and money. Each of the next n lines contains two integers ai and bi (1ββ€βai,βbiββ€β1β000β000)Β β the daily increase in experience and daily income for working on the i-th project.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_017.jsonl
|
82cbd58de2571d6eaed6c581386168df
|
256 megabytes
|
["3 20 20\n6 2\n1 3\n2 6", "4 1 1\n2 3\n3 2\n2 3\n3 2"]
|
PASSED
|
def get_bounds(points):
if len(points) == 1:
return points[:]
points.sort()
bounds = [points[0], points[1]]
for xi, yi in points[2:]:
while len(bounds) > 1 and not is_convex(bounds, xi, yi):
del bounds[-1]
bounds.append((xi, yi))
return bounds
def is_convex(bounds, x2, y2):
x1, y1 = bounds[-1]
x0, y0 = bounds[-2]
return (x1 - x0) * (y2 - y1) < (y1 - y0) * (x2 - x1)
def read_data():
n, p, q = map(int, input().split())
ABs = []
for i in range(n):
a, b = map(int, input().split())
ABs.append((a, b))
return n, p, q, ABs
def solve(n, p, q, ABs):
'''
min sum(ds)
s.t. sum(ds[i] * As[i]) >= p and sum(ds[i] * Bs[i]) >= q
'''
bounds = get_bounds(ABs)
a0, b0 = bounds[0]
if len(bounds) == 1:
return max(p/a0, q/b0)
record = float('Inf')
for a1, b1 in bounds[1:]:
steps = min(max(p/a0, q/b0), max(p/a1, q/b1))
den = a0 * b1 - b0 * a1
if den != 0:
r0 = (b1 * p - a1 * q)/den
r1 = - (b0 * p - a0 * q)/den
if r0 > 0 and r1 > 0:
steps = min(steps, r0 + r1)
a0 = a1
b0 = b1
record = min(record, steps)
return record
n, p, q, ABs = read_data()
print(solve(n, p, q, ABs))
|
1449677100
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["123+45=168", "0+9=9", "1+99=100", "123123123+456456456=579579579"]
|
ae34b6eda34df321a16e272125fb247b
| null |
A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that: character'+' is placed on the left of character '=', characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle partΒ β b and the right partΒ β c), all the three parts a, b and c do not contain leading zeros, it is true that a+b=c. It is guaranteed that in given tests answer always exists.
|
Output the restored expression. If there are several solutions, you can print any of them. Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be. Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples. If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.
|
The first line contains a non-empty string consisting of digits. The length of the string does not exceed 106.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,300 |
train_055.jsonl
|
96493dc2da88fd0c81271d4cfa4e568a
|
256 megabytes
|
["12345168", "099", "199100", "123123123456456456579579579"]
|
PASSED
|
def pp(a, b, c):
t = map(str, a) + ['+'] + map(str, b) + ['='] + map(str, c)
print ''.join(t)
def go(s, a, b, i):
if i != 1 and s[-i] == 0:
return 0
if a != 1 and s[0] == 0:
return 0
if b != 1 and s[a] == 0:
return 0
if max(a, b) < i:
if not a == b and not (a == i - 1 and s[0] == 9) and not (b == i - 1 and s[a] == 9):
return 0
if s[-i] != 1:
return 0
t = 1
if a == i - 1:
for j in xrange(a-b):
t = t * 10 + s[-a+j] - s[j]
if t < 0 or t > 1:
return 0
for j in xrange(b):
t = t * 10 + s[-b+j] - s[a-b+j] - s[a+j]
if t < 0 or t > 1:
return 0
if t == 0:
pp(s[:a], s[a:a+b], s[-i:])
return 1
return 0
else:
for j in xrange(b-a):
t = t * 10 + s[-b+j] - s[a+j]
if t < 0 or t > 1:
return 0
for j in xrange(a):
t = t * 10 + s[-a+j] - s[j] - s[a+b-a+j]
if t < 0 or t > 1:
return 0
if t == 0:
pp(s[:a], s[a:a+b], s[-i:])
return 1
return 0
else:
if a == i:
t = 0
for j in xrange(i-b):
t = t * 10 + s[-a+j] - s[j]
if t < 0 or t > 1:
return 0
for j in xrange(b):
t = t * 10 + s[-b+j] - s[i-b+j] - s[a+j]
if t < 0 or t > 1:
return 0
if t == 0:
pp(s[:a], s[a:a+b], s[-i:])
return 1
return 0
else:
t = 0
for j in xrange(i-a):
t = t * 10 + s[-b+j] - s[a+j]
if t < 0 or t > 1:
return 0
for j in xrange(a):
t = t * 10 + s[-a+j] - s[j] - s[a+i-a+j]
if t < 0 or t > 1:
return 0
if t == 0:
pp(s[:a], s[a:a+b], s[-i:])
return 1
return 0
def main():
s = map(int, raw_input().strip())
l = len(s)
mod = 10007
t = [0] * (l + 1)
u = [1] * (l + 1)
for i in xrange(l):
u[i+1] = u[i] * 10 % mod
t[i+1] = (t[i] * 10 + s[i]) % mod
for i in xrange(1, l - 1):
a, b = i - 1, l - i - i + 1
hi = (t[l] - t[l-i] * u[i]) % mod
if 1 <= b <= i:
if hi == (t[a] + (t[a+b] - t[a] * u[b])) % mod and go(s, a, b, i):
return
if hi == (t[b] + (t[a+b] - t[b] * u[a])) % mod and go(s, b, a, i):
return
a += 1
b -= 1
if 1 <= b <= i:
if hi == (t[a] + (t[a+b] - t[a] * u[b])) % mod and go(s, a, b, i):
return
if hi == (t[b] + (t[a+b] - t[b] * u[a])) % mod and go(s, b, a, i):
return
main()
|
1513424100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["Stannis", "Daenerys", "Stannis"]
|
67e51db4d96b9f7996aea73cbdba3584
|
NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.
|
There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
|
Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.
|
The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_001.jsonl
|
59600dd7f5b1b008b40f64abe03c7848
|
256 megabytes
|
["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"]
|
PASSED
|
import math,string,itertools,fractions,heapq,collections,re,array,bisect
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque
def VI(): return list(map(int,input().split()))
def main(n,k,a):
now = sum(a)
even = sum([x%2==0 for x in a])
odd = sum([x%2==1 for x in a])
d = n-k
D = "Daenerys"
S = "Stannis"
if n==k:
ans = [S,D][now%2==0]
elif d%2==0: # Daenerys last
if k%2==0: ans = D
elif even <= d//2: ans = S
else: ans = D
else: # Stannis last
if k%2==0:
if odd <= d//2 or even <= d//2: ans = D
else: ans = S
else:
if odd <= d//2: ans = D
else: ans = S
print(ans)
def main_input(info=0):
n,k = VI()
a = VI()
main(n,k,a)
if __name__ == "__main__":
main_input()
|
1433595600
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["4\n6", "117\n665496274\n332748143\n831870317\n499122211"]
|
1461fca52a0310fff725b476bfbd3b29
|
NoteIn the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to $$$\frac{1}{2}$$$. So, the expected number of days, until one mirror will say, that he is beautiful is equal to $$$2$$$ and the answer will be equal to $$$4 = 2 + 2$$$.
|
Creatnx has $$$n$$$ mirrors, numbered from $$$1$$$ to $$$n$$$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $$$i$$$-th mirror will tell Creatnx that he is beautiful with probability $$$\frac{p_i}{100}$$$ for all $$$1 \le i \le n$$$.Some mirrors are called checkpoints. Initially, only the $$$1$$$st mirror is a checkpoint. It remains a checkpoint all the time.Creatnx asks the mirrors one by one, starting from the $$$1$$$-st mirror. Every day, if he asks $$$i$$$-th mirror, there are two possibilities: The $$$i$$$-th mirror tells Creatnx that he is beautiful. In this case, if $$$i = n$$$ Creatnx will stop and become happy, otherwise he will continue asking the $$$i+1$$$-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to $$$i$$$. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given $$$q$$$ queries, each query is represented by an integer $$$u$$$: If the $$$u$$$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $$$u$$$-th mirror is no longer a checkpoint.After each query, you need to calculate the expected number of days until Creatnx becomes happy.Each of this numbers should be found by modulo $$$998244353$$$. Formally, let $$$M = 998244353$$$. 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}$$$.
|
Print $$$q$$$ numbersΒ β the answers after each query by modulo $$$998244353$$$.
|
The first line contains two integers $$$n$$$, $$$q$$$ ($$$2 \leq n, q \le 2 \cdot 10^5$$$) Β β the number of mirrors and queries. The second line contains $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq 100$$$). Each of $$$q$$$ following lines contains a single integer $$$u$$$ ($$$2 \leq u \leq n$$$)Β β next query.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400 |
train_082.jsonl
|
37af9be9e83ba129e959a7f854eb2aac
|
256 megabytes
|
["2 2\n50 50\n2\n2", "5 5\n10 20 30 40 50\n2\n3\n4\n5\n3"]
|
PASSED
|
from __future__ import division, print_function
def main():
n, qs = input_as_list()
cpn = ceil_power_of_2(n)
st = array_of(int, n+1)
switch = array_of(bool, n)
def update(i, v):
while i < n:
st[i] += v
i |= i+1
def query(i):
res = 0
while i > 0:
res += st[i-1]
i &= i-1
return res
def lower_bound(s):
if s <= 0: return -1
pos = 0
pw = cpn
while pw > 0:
if (pos + pw <= n) and (st[pos + pw-1] < s):
pos += pw
s -= st[pos-1]
pw //= 2
return pos
def insert(i):
update(i, +1)
def remove(i):
update(i, -1)
def find_by_order(i):
return lower_bound(i)
def order_of(i):
return query(i)
def lr(i):
o = order_of(i)
l = find_by_order(o)
r = find_by_order(o+1)
return l, r
ar = input_as_list()
s1 = [0]
for x in ar:
v = s1[-1]+1
v = mulmod(v, 100)
v = divmod(v, x)
s1.append(v)
s2 = [1]
for x in ar:
v = s2[-1]
v = mulmod(v, 100)
v = divmod(v, x)
s2.append(v)
def f(l, r):
if r <= l:
return 0
a = s1[r]
b = mulmod(s1[l], s2[r])
b = divmod(b, s2[l])
return (a-b)%MOD
insert(0)
insert(n)
ans = s1[-1]
for _ in range(qs):
q = int(input())-1
if switch[q]:
remove(q)
l, r = lr(q)
ans = (ans + f(l, r)) % MOD
ans = (ans - f(l, q)) % MOD
ans = (ans - f(q, r)) % MOD
else:
l, r = lr(q)
ans = (ans - f(l, r)) % MOD
ans = (ans + f(l, q)) % MOD
ans = (ans + f(q, r)) % MOD
insert(q)
switch[q] ^= True
print(ans)
INF = float('inf')
MOD = 998244353
__interactive = False
import os, sys
from atexit import register
from io import BytesIO
import itertools
import __pypy__
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
if "LOCAL_" in os.environ:
debug_print = print
else:
if not __interactive:
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')
debug_print = lambda *x, **y: None
flush = sys.stdout.flush
def mulmod(x, y):
return __pypy__.intop.int_mulmod(x, y, MOD)
def modinv(x):
return pow(x, MOD-2, MOD)
def divmod(x, y):
return mulmod(x, modinv(y))
def gcd(x, y):
while y:
x, y = y, x % y
return x
def input_as_list():
return list(map(int, input().split()))
def input_with_offset(o):
return list(map(lambda x:int(x)+o, 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()
def range_with_count(start, step, count):
return range(start, start + step * count, step)
def indices(l, start=0, end=0):
return range(start, len(l)+end)
def ceil_power_of_2(n):
""" [0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, ...] """
return 2 ** ((n - 1).bit_length())
def ceil_div(x, r):
""" = ceil(x / r) """
return (x + r - 1) // r
main()
|
1575556500
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["sinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja"]
|
efa201456f8703fcdc29230248d91c54
|
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
|
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μλ
, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?
|
Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.
|
The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_005.jsonl
|
b3e21ba6b197b11a6ab8a84e6ac9fed0
|
1024 megabytes
|
["10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020"]
|
PASSED
|
n,m=map(int,input().split())
S=list(map(str,input().split()))
T=list(map(str,input().split()))
q=int(input())
for i in range (q):
y=int(input())
print(S[(y%n)-1]+T[(y%m)-1])
|
1578139500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["0\n1\n0"]
|
5bffe38e3ac9511a30ee02b4ec5cb1d5
|
NoteNote that after applying a few operations, the values of $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ may become negative.In the first test case, $$$4$$$ is already the Arithmetic Mean of $$$3$$$ and $$$5$$$.$$$d(3, 4, 5) = |3 + 5 - 2 \cdot 4| = 0$$$In the second test case, we can apply the following operation:$$$(2, 2, 6)$$$ $$$\xrightarrow[\text{increment $$$a_2$$$}]{\text{decrement $$$a_1$$$}}$$$ $$$(1, 3, 6)$$$$$$d(1, 3, 6) = |1 + 6 - 2 \cdot 3| = 1$$$It can be proven that answer can not be improved any further.In the third test case, we can apply the following operations:$$$(1, 6, 5)$$$ $$$\xrightarrow[\text{increment $$$a_3$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(1, 5, 6)$$$ $$$\xrightarrow[\text{increment $$$a_1$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(2, 4, 6)$$$$$$d(2, 4, 6) = |2 + 6 - 2 \cdot 4| = 0$$$
|
A number $$$a_2$$$ is said to be the arithmetic mean of two numbers $$$a_1$$$ and $$$a_3$$$, if the following condition holds: $$$a_1 + a_3 = 2\cdot a_2$$$. We define an arithmetic mean deviation of three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ as follows: $$$d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$$$.Arithmetic means a lot to Jeevan. He has three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ and he wants to minimize the arithmetic mean deviation $$$d(a_1, a_2, a_3)$$$. To do so, he can perform the following operation any number of times (possibly zero): Choose $$$i, j$$$ from $$$\{1, 2, 3\}$$$ such that $$$i \ne j$$$ and increment $$$a_i$$$ by $$$1$$$ and decrement $$$a_j$$$ by $$$1$$$ Help Jeevan find out the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.
|
For each test case, output the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 5000)$$$ Β β the number of test cases. The first and only line of each test case contains three integers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ $$$(1 \le a_1, a_2, a_3 \le 10^{8})$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_097.jsonl
|
6976109a28fc64a00f32a33fc4c8bc9d
|
256 megabytes
|
["3\n3 4 5\n2 2 6\n1 6 5"]
|
PASSED
|
for x in range(int(input())):
a,b,c=sorted([int(x) for x in input().split()])
a1=abs(2*b-a-c)//3
a2=a1+1
print (min(abs(a-a1+c-2*(b+a1)) ,abs( a+a1+c-2*(b-a1)) , abs(a-a2+c-2*(b+a2)) ,abs( a+a2+c-2*(b-a2)) ))
|
1636727700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["NO\nYES\nNO\nYES"]
|
7cf9bb97385ee3a5b5e28f66eab163d0
| null |
You are given two strings $$$s$$$ and $$$t$$$ both of length $$$n$$$ and both consisting of lowercase Latin letters.In one move, you can choose any length $$$len$$$ from $$$1$$$ to $$$n$$$ and perform the following operation: Choose any contiguous substring of the string $$$s$$$ of length $$$len$$$ and reverse it; at the same time choose any contiguous substring of the string $$$t$$$ of length $$$len$$$ and reverse it as well. Note that during one move you reverse exactly one substring of the string $$$s$$$ and exactly one substring of the string $$$t$$$.Also note that borders of substrings you reverse in $$$s$$$ and in $$$t$$$ can be different, the only restriction is that you reverse the substrings of equal length. For example, if $$$len=3$$$ and $$$n=5$$$, you can reverse $$$s[1 \dots 3]$$$ and $$$t[3 \dots 5]$$$, $$$s[2 \dots 4]$$$ and $$$t[2 \dots 4]$$$, but not $$$s[1 \dots 3]$$$ and $$$t[1 \dots 2]$$$.Your task is to say if it is possible to make strings $$$s$$$ and $$$t$$$ equal after some (possibly, empty) sequence of moves.You have to answer $$$q$$$ independent test cases.
|
For each test case, print the answer on it β "YES" (without quotes) if it is possible to make strings $$$s$$$ and $$$t$$$ equal after some (possibly, empty) sequence of moves and "NO" otherwise.
|
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) β the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the length of $$$s$$$ and $$$t$$$. The second line of the test case contains one string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the test case contains one string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_002.jsonl
|
41c9d60c3785ddba35355952b2a32df9
|
256 megabytes
|
["4\n4\nabcd\nabdc\n5\nababa\nbaaba\n4\nasdf\nasdg\n4\nabcd\nbadc"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
s1, s2 = input(), input()
a1, a2 = [0]*26, [0]*26
for v in map(ord, s1):
a1[v-97] += 1
for v in map(ord, s2):
a2[v-97] += 1
if a1 != a2:
print('NO')
continue
if max(a1) > 1:
print('YES')
continue
inv1 = sum(c1 > c2 for i, c1 in enumerate(s1) for c2 in s1[i+1:])
inv2 = sum(c1 > c2 for i, c1 in enumerate(s2) for c2 in s2[i+1:])
print('YES' if inv1 % 2 == inv2 % 2 else 'NO')
|
1572873300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["YES\n112323", "NO"]
|
52c634955e1d78971d94098ba1c667d9
| null |
You are given an undirected graph without self-loops or multiple edges which consists of $$$n$$$ vertices and $$$m$$$ edges. Also you are given three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$.Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that: Each vertex should be labeled by exactly one number 1, 2 or 3; The total number of vertices with label 1 should be equal to $$$n_1$$$; The total number of vertices with label 2 should be equal to $$$n_2$$$; The total number of vertices with label 3 should be equal to $$$n_3$$$; $$$|col_u - col_v| = 1$$$ for each edge $$$(u, v)$$$, where $$$col_x$$$ is the label of vertexΒ $$$x$$$. If there are multiple valid labelings, print any of them.
|
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length $$$n$$$ consisting of 1, 2 and 3. The $$$i$$$-th letter should be equal to the label of the $$$i$$$-th vertex. If there is no valid labeling, print "NO" (without quotes).
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$)Β β the number of vertices and edges in the graph. The second line contains three integers $$$n_1$$$, $$$n_2$$$ and $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$)Β β the number of labels 1, 2 and 3, respectively. It's guaranteed that $$$n_1 + n_2 + n_3 = n$$$. Next $$$m$$$ lines contan description of edges: the $$$i$$$-th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) β the vertices the $$$i$$$-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_007.jsonl
|
0c6a800ffc85cbd29fb4b9e7e7581907
|
256 megabytes
|
["6 3\n2 2 2\n3 1\n5 4\n2 5", "5 9\n0 2 3\n1 2\n1 3\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"]
|
PASSED
|
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n, m = nm()
a = nl()
G = [list() for _ in range(n)]
for _ in range(m):
u, v = nm()
u -= 1; v -= 1
G[u].append(v)
G[v].append(u)
color = [-1]*n
roots = list()
def dfs(v, p):
siz, bla = 1, color[v]
for x in G[v]:
if x == p: continue
if color[x] < 0:
color[x] = color[v] ^ 1
rs, rb = dfs(x, v)
siz += rs
bla += rb
elif color[x] == color[v]:
print('NO')
exit()
return siz, bla
for v in range(n):
if color[v] < 0:
color[v] = 0
siz, bla = dfs(v, -1)
roots.append((v, siz, bla))
dp = [1]*(len(roots) + 1)
for i, (v, siz, bla) in enumerate(roots):
dp[i+1] = dp[i] << bla | dp[i] << (siz - bla)
if dp[len(roots)] >> a[1] & 1 == 0:
print('NO')
return
cur = a[1]
ans = [0]*n
def dfs2(v, p, c):
if c ^ color[v]:
if a[0]:
ans[v] = 1
a[0] -= 1
else:
ans[v] = 3
a[2] -= 1
else:
ans[v] = 2
a[1] -= 1
for x in G[v]:
if not ans[x]:
dfs2(x, v, c)
for i in range(len(roots)-1, -1, -1):
v, siz, bla = roots[i]
if cur >= bla and dp[i] >> (cur - bla) & 1:
fl = 1
cur -= bla
else:
fl = 0
cur -= siz - bla
dfs2(v, -1, fl)
print('YES')
print(*ans, sep='')
return
solve()
# T = ni()
# for _ in range(T):
# solve()
|
1589707200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["8\n4\n0\n2\n1\n5"]
|
8e9ba5a2472984cd14b99790a157acd5
|
NoteThe first test case is analyzed in the statement.In the second test case, you can get a total value equal to $$$4$$$ if you put the first and second goods in the first package and the third and fourth goods in the second package.In the third test case, the cost of each item is $$$0$$$, so the total cost will also be $$$0$$$.
|
A batch of $$$n$$$ goods ($$$n$$$Β β an even number) is brought to the store, $$$i$$$-th of which has weight $$$a_i$$$. Before selling the goods, they must be packed into packages. After packing, the following will be done: There will be $$$\frac{n}{2}$$$ packages, each package contains exactly two goods; The weight of the package that contains goods with indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) is $$$a_i + a_j$$$. With this, the cost of a package of weight $$$x$$$ is always $$$\left \lfloor\frac{x}{k}\right\rfloor$$$ burles (rounded down), where $$$k$$$Β β a fixed and given value.Pack the goods to the packages so that the revenue from their sale is maximized. In other words, make such $$$\frac{n}{2}$$$ pairs of given goods that the sum of the values $$$\left \lfloor\frac{x_i}{k} \right \rfloor$$$, where $$$x_i$$$ is the weight of the package number $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$), is maximal.For example, let $$$n = 6, k = 3$$$, weights of goods $$$a = [3, 2, 7, 1, 4, 8]$$$. Let's pack them into the following packages. In the first package we will put the third and sixth goods. Its weight will be $$$a_3 + a_6 = 7 + 8 = 15$$$. The cost of the package will be $$$\left \lfloor\frac{15}{3}\right\rfloor = 5$$$ burles. In the second package put the first and fifth goods, the weight is $$$a_1 + a_5 = 3 + 4 = 7$$$. The cost of the package is $$$\left \lfloor\frac{7}{3}\right\rfloor = 2$$$ burles. In the third package put the second and fourth goods, the weight is $$$a_2 + a_4 = 2 + 1 = 3$$$. The cost of the package is $$$\left \lfloor\frac{3}{3}\right\rfloor = 1$$$ burle. With this packing, the total cost of all packs would be $$$5 + 2 + 1 = 8$$$ burles.
|
For each test case, print on a separate line a single number β the maximum possible total cost of all the packages.
|
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β βthe number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) and $$$k$$$ ($$$1 \le k \le 1000$$$). The number $$$n$$$Β β is even. The second line of each test case contains exactly $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all the test cases does not exceed $$$2\cdot10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,500 |
train_094.jsonl
|
0155778ceea34bdfebd53f38bfaa6e85
|
256 megabytes
|
["6\n\n6 3\n\n3 2 7 1 4 8\n\n4 3\n\n2 1 5 6\n\n4 12\n\n0 0 0 0\n\n2 1\n\n1 1\n\n6 10\n\n2 0 0 5 9 4\n\n6 5\n\n5 3 8 6 3 2"]
|
PASSED
|
t = int(input())
for z in range(t):
n, k = map(int,input().split())
arr = list(map(int,input().split()))
count = 0
for i in range(len(arr)):
count += arr[i]//k
arr[i] = arr[i]%k
# ΡΠ·Π½Π°Π»ΠΈ ΡΠΊΠΎΠ»ΡΠΊΠΎ ΡΠ΅Π»ΡΡ
k Π±ΡΠ΄Π΅Ρ Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ΅
# ΡΠΎΠ·Π΄Π°Π»ΠΈ ΠΌΠ°ΡΡΠΈΠ² ΠΎΡΡΠ°ΡΠΊΠΎΠ²
# ΠΊΠ°ΠΆΠ΄ΡΠΉ ΠΎΡΡΠ°ΡΠΎΠΊ ΠΏΠΎ ΠΎΠ΄ΠΈΠ½ΠΎΡΠΊΠ΅ Π·Π°Π²Π΅Π΄ΠΎΠΌΠΎ ΠΌΠ΅Π½ΡΡΠ΅ k
# ΡΡΠΌΠΌΠ° Π΄Π²ΡΡ
ΠΎΡΡΠ°ΡΠΊΠΎΠ² ΠΏΡΠΈ Π΄Π΅Π»Π΅Π½ΠΈΠΈ Π½Π° k Π½Π°ΡΠ΅Π»ΠΎ ΠΌΠΎΠΆΠ΅Ρ Π΄Π°ΡΡ Π»ΠΈΠ±ΠΎ 1 Π»ΠΈΠ±ΠΎ 0
# Π½ΡΠΆΠ½ΠΎ ΠΏΠΎΠ»ΡΡΠΈΡΡ ΡΠΏΠΈΡΠΎΠΊ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² Ρ ΠΈΡ
ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎΠΌ
# ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² Π±ΡΠ΄Π΅Ρ Π½Π΅ Π±ΠΎΠ»ΡΡΠ΅ k (ΠΎΡ Π½ΡΠ»Ρ Π΄ΠΎ k-1)
# ΠΏΠΎΠΏΡΠΎΠ±ΡΠ΅ΠΌ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎ ΠΏΡΠΈΠ±Π°Π²Π»ΡΡΡ ΠΊ ΡΠ°ΠΌΠΎΠΌΡ Π±ΠΎΠ»ΡΡΠΎΠΌΡ ΡΠ°ΠΌΠΎΠ΅ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ΅, ΠΊΠΎΡΠΎΡΠΎΠ΅ Π΅ΡΡΡ Π² Π΄ΠΎΡΡΡΠΏΠ΅
# ΠΈ ΠΊΠΎΡΠΎΡΡΠΉ Π² ΡΡΠΌΠΌΠ΅ Ρ Π½ΠΈΠΌ Π΄Π°Π΅Ρ ΠΏΡΠΈ Π΄Π΅Π»Π΅Π½ΠΈΠΈ Π½Π° k Π½Π°ΡΠ΅Π»ΠΎ Π΅Π΄ΠΈΠ½ΠΈΡΡ
# Π΅ΡΠ»ΠΈ ΡΠ°ΠΊΠΎΠ³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ° Π½Π΅ Π½Π°ΡΠ»ΠΎΡΡ, Π·Π½Π°ΡΠΈΡ Π±ΠΎΠ»ΡΡΠ΅Π΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ ΠΏΠΎΠ»ΡΡΠΈΡΡ Π½Π΅Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ
# ΡΠΎΠ·Π΄Π°Π΄ΠΈΠΌ ΡΠΏΠΈΡΠΎΠΊ Ρ ΡΠ½ΠΈΠΊΠ°Π»ΡΠ½ΡΠΌΠΈ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°ΠΌΠΈ, ΠΎΡΡΠ°ΡΠΊΠ°ΠΌΠΈ ΠΎΡ Π΄Π΅Π»Π΅Π½ΠΈΡ ΠΏΠ΅ΡΠ²ΠΎΠ½Π°ΡΠ°Π»ΡΠ½ΠΎΠ³ΠΎ ΡΠΏΠΈΡΠΊΠ°
# ΡΡΠΎΠ±Ρ Π½Π΅ ΠΈΡΠΊΠ°ΡΡ ΡΠ»Π΅ΠΌΠ΅Π½ΡΡ ΠΏΠΎ ΠΈΠ½Π΄Π΅ΠΊΡΡ ΠΊΠ°ΠΆΠ΄ΡΠΉ ΡΠ°Π·, ΠΌΡ ΡΠΎΠ·Π΄Π°Π΄ΠΈΠΌ ΠΈΠ·Π±ΡΡΠΎΡΠ½ΡΠΉ ΡΠΏΠΈΡΠΎΠΊ ΡΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΡΠΌΠΈ ΠΎΡ 0
# Π΄ΠΎ k-1
elements = list([[i,0] for i in range(k)])
for i in range(len(arr)):
elements[arr[i]][1] += 1
for i in reversed(range(len(elements))):
if elements[i][1] == 0:
elements.pop(i)
elements.sort(reverse = True)
# ΡΠ΅ΠΏΠ΅ΡΡ Ρ Π½Π°Ρ Π΅ΡΡΡ ΠΎΡΡΠΎΡΡΠΈΡΠΎΠ²Π°Π½Π½ΡΠΉ ΠΏΠΎ ΡΠ±ΡΠ²Π°Π½ΠΈΡ ΡΠΏΠΈΡΠΎΠΊ ΠΎΡΡΠ°ΡΠΊΠΎΠ²
# ΠΈΡ
Π²ΡΠ΅Π³Π΄Π° Π±ΡΠ΄Π΅Ρ ΠΏΠ°ΡΠ½ΠΎΠ΅ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ
# ΡΠ΅ΠΏΠ΅ΡΡ Π½ΡΠΆΠ½ΠΎ ΠΎΡΠ³Π°Π½ΠΈΠ·ΠΎΠ²Π°ΡΡ ΠΏΡΠΎΡΠ΅Π΄ΡΡΡ ΠΏΠΎΠΈΡΠΊΠ° ΠΏΠΎΠ΄Ρ
ΠΎΠ΄ΡΡΠΈΡ
Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ
# Π½Π°ΡΠ½Π΅ΠΌ ΠΌΡ Ρ ΡΠ°ΠΌΠΎΠ³ΠΎ Π±ΠΎΠ»ΡΡΠΎΠ³ΠΎ
# ΠΊ Π½Π΅ΠΌΡ Π½ΡΠΆΠ½ΠΎ ΠΏΠΎΠ΄ΠΎΠ±ΡΠ°ΡΡ Π½Π°ΠΈΠΌΠ΅Π½ΡΡΠ΅Π΅ ΠΏΠΎΠ΄Ρ
ΠΎΠ΄ΡΡΠ΅Π΅
# print('elements',elements)
for i in range(len(elements)):
val = elements[i][0]
qua = elements[i][1]
j = len(elements)-1
while (j>=i) and (qua>0):
if elements[j][0] + val >= k:
# print('svinable!')
# subtraction - ΡΡΠΎ ΡΠΊΠΎΠ»ΡΠΊΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² ΠΌΡ ΡΠΌΠΎΠ³Π»ΠΈ ΠΈΠ·ΡΠ°ΡΡ
ΠΎΠ΄ΠΎΠ²Π°ΡΡ Π·Π° ΠΎΠ΄Π½Ρ ΠΈΡΠ΅ΡΠ°ΡΠΈΡ
if i != j:
subtraction = min(qua,elements[j][1])
# Π·Π½Π°ΡΠΈΡ, ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΠΈΡ
ΡΡΠΌΠΌ Π΄Π°ΡΡ Π½Π°ΠΌ ΡΡΠΎΠ»ΡΠΊΠΎ Π΅Π΄ΠΈΠ½ΠΈΡ ΠΏΡΠΈΠ±Π°Π²ΠΊΠΈ
count += subtraction
qua -= subtraction
elements[j][1] -= subtraction
elif qua >= 2:
got = qua // 2
count += got
elements[j][1] -= 2*got
j-= 1
# Π΅ΡΠ»ΠΈ ΠΏΠΎΡΠ»Π΅ ΡΠΈΠΊΠ»Π° while Ρ Π½Π°Ρ Π½Π΅ ΠΈΠ·ΡΠ°ΡΡ
ΠΎΠ΄ΠΎΠ²Π°Π»ΠΈΡΡ Π²ΡΠ΅ ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½ΡΠ΅ ΡΠ»Π΅ΠΌΠ΅Π½ΡΡ, ΡΠΎ Π΄Π°Π»ΡΡΠ΅ ΠΏΠΎΠΈΡΠΊ Π½Π΅
# ΠΏΡΠΈΠ½Π΅ΡΠ΅Ρ ΡΠ΅Π·ΡΠ»ΡΡΠ°ΡΠΎΠ²
# Ρ Π½Π΅ ΡΡΠ΅Π» Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΡΡΡ ΡΠΊΠ»Π°Π΄ΡΠ²Π°ΡΡ Ρ ΡΠ°ΠΌΠΈΠΌ ΡΠΎΠ±ΠΎΠΉ!
if qua > 0:
break
print(count)
|
1654612500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2 5\n3 1\n0 0"]
|
f7defb09175c842de490aa13a4f5a0c9
| null |
You are given two integers $$$x$$$ and $$$y$$$. You want to choose two strictly positive (greater than zero) integers $$$a$$$ and $$$b$$$, and then apply the following operation to $$$x$$$ exactly $$$a$$$ times: replace $$$x$$$ with $$$b \cdot x$$$.You want to find two positive integers $$$a$$$ and $$$b$$$ such that $$$x$$$ becomes equal to $$$y$$$ after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.For example: if $$$x = 3$$$ and $$$y = 75$$$, you may choose $$$a = 2$$$ and $$$b = 5$$$, so that $$$x$$$ becomes equal to $$$3 \cdot 5 \cdot 5 = 75$$$; if $$$x = 100$$$ and $$$y = 100$$$, you may choose $$$a = 3$$$ and $$$b = 1$$$, so that $$$x$$$ becomes equal to $$$100 \cdot 1 \cdot 1 \cdot 1 = 100$$$; if $$$x = 42$$$ and $$$y = 13$$$, there is no answer since you cannot decrease $$$x$$$ with the given operations.
|
If it is possible to choose a pair of positive integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$ after the aforementioned process, print these two integers. The integers you print should be not less than $$$1$$$ and not greater than $$$10^9$$$ (it can be shown that if the answer exists, there is a pair of integers $$$a$$$ and $$$b$$$ meeting these constraints). If there are multiple such pairs, print any of them. If it is impossible to choose a pair of integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$, print the integer $$$0$$$ twice.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 100$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_107.jsonl
|
c5a164d64b2dea2beee239ea8cddd782
|
512 megabytes
|
["3\n\n3 75\n\n100 100\n\n42 13"]
|
PASSED
|
t = int(input())
for _ in range(t):
x, y = map(int, input().split())
if y % x != 0:
print(0, 0)
else:
print(1, y//x)
|
1651502100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n3 1 2 3\n3 1 2 3", "6\n3 5 4 2\n3 3 1 5\n4 4 5 2 3\n4 4 3 2 1\n3 4 2 1\n3 3 1 5"]
|
1a4907c76ecd935ca345570e54bc5c31
| null |
In order to fly to the Moon Mister B just needs to solve the following problem.There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?
|
If there is no answer, print -1. Otherwise, in the first line print k (1ββ€βkββ€βn2)Β β the number of cycles in your solution. In each of the next k lines print description of one cycle in the following format: first print integer m (3ββ€βmββ€β4)Β β the length of the cycle, then print m integers v1,βv2,β...,βvm (1ββ€βviββ€βn)Β β the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.
|
The only line contains single integer n (3ββ€βnββ€β300).
|
standard output
|
standard input
|
Python 2
|
Python
| 2,800 |
train_034.jsonl
|
27acfa7a1e3726a7e146abd22f453908
|
256 megabytes
|
["3", "5"]
|
PASSED
|
def f(n):
if n == 3:
return [[1, 2, 3], [1, 2, 3]]
elif n % 2 == 1:
a = f(n - 2)
for i in xrange(1, n - 2, 2):
a.append([i, n, i + 1, n - 1])
a.append([i, n, i + 1, n - 1])
a.append([n, n - 1, n - 2])
a.append([n, n - 1, n - 2])
return a
else:
a = f(n - 1)[::2]
for v in a:
for i in xrange(len(v)):
if v[i] == n - 1:
v[i] += 1
a.extend(f(n - 1)[::2])
for i in xrange(1, n - 3, 2):
a.append([i, n, i + 1, n - 1])
a.append([n, n - 1, n - 2])
a.append([n, n - 1, n - 3])
return a
n = int(raw_input())
a = f(n)
print len(a)
for v in a:
print len(v), " ".join(map(str, v))
|
1498574100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
4 seconds
|
["3 4 2", "199999", "6"]
|
07484b6a6915c5cb5fdf1921355f2a6a
| null |
Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations: Firstly, let the array $$$b$$$ be equal to the array $$$a$$$; Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$: if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$); otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$; Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any.
|
In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order β the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any.
|
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_006.jsonl
|
d0979b3daabd5b6984d7e79732d1052c
|
256 megabytes
|
["3\n3 5 2 3 2 4", "1\n2750131 199999", "1\n3 6"]
|
PASSED
|
import collections,math
n=int(input())
a=list(map(int, input().split()))
a.sort(reverse=True)
primes_arr=[-1]
maxi = 2750131+1
primes_sieve=[0 for _ in range(maxi)]
def sieve():
for i in range(2, maxi):
if not primes_sieve[i]:
primes_arr.append(i)
primes_sieve[i] = 1
for j in range(i*i, maxi, i):
if not primes_sieve[j]:
primes_sieve[j] = i
sieve()
# print(primes_sieve[:20])
d=collections.defaultdict(int)
z=collections.defaultdict(int)
ans=[]
primes = []
for i in range(n*2):
x=a[i]//primes_sieve[a[i]]
if d[a[i]] > 0:
d[a[i]]-=1
elif x!=a[i]:
d[x]+=1
ans.append(a[i])
else:
primes.append(a[i])
primes=primes[::-1]
for i in range(len(primes)):
if z[primes[i]]>0:
z[primes[i]]-=1
else:
z[primes_arr[primes[i]]]+=1
ans.append(primes[i])
print(*ans)
|
1560090900
|
[
"number theory",
"graphs"
] |
[
0,
0,
1,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["0 0\n3 0\n0 3\n1 1", "-1", "10 0\n-10 0\n10 1\n9 1\n9 -1\n0 -2", "176166 6377\n709276 539564\n654734 174109\n910147 434207\n790497 366519\n606663 21061\n859328 886001"]
|
2e9f2bd3c02ba6ba41882334deb35631
| null |
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.
|
If there is no solution, print "-1". Otherwise, print n pairs of integers β the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value.
|
The single line contains two integers n and m (3ββ€βmββ€β100,βmββ€βnββ€β2m).
|
standard output
|
standard input
|
Python 2
|
Python
| 2,300 |
train_062.jsonl
|
32333ceef06116e55c5c581010be1c51
|
256 megabytes
|
["4 3", "6 3", "6 6", "7 4"]
|
PASSED
|
n, m = map( int, raw_input().split() )
if( ( m == 3 ) and ( n >= 5 ) ):
print -1
else:
for i in xrange( m ):
print i, ( i * i )
for i in xrange( n - m ):
print ( i * i + 12345 ), i
|
1362065400
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "1", "0"]
|
bc532d5c9845940b5f59485394187bf6
|
NoteIn the first example, one possible way to unlock $$$3$$$ chests is as follows: Use first key to unlock the fifth chest, Use third key to unlock the second chest, Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).In the third example, no key can unlock the given chest.
|
On a random day, Neko found $$$n$$$ treasure chests and $$$m$$$ keys. The $$$i$$$-th chest has an integer $$$a_i$$$ written on it and the $$$j$$$-th key has an integer $$$b_j$$$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.The $$$j$$$-th key can be used to unlock the $$$i$$$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $$$a_i + b_j \equiv 1 \pmod{2}$$$. One key can be used to open at most one chest, and one chest can be opened at most once.Find the maximum number of chests Neko can open.
|
Print the maximum number of chests you can open.
|
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$)Β β the number of chests and the number of keys. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)Β β the numbers written on the treasure chests. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 10^9$$$)Β β the numbers written on the keys.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_005.jsonl
|
536d3cf8a7725e9c3f39675a99211f67
|
256 megabytes
|
["5 4\n9 14 6 2 11\n8 4 7 20", "5 1\n2 4 6 8 10\n5", "1 4\n10\n20 30 40 50"]
|
PASSED
|
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ae=0
ao=0
be=0
bo=0
for ele in a:
if ele%2:
ao+=1
else:
ae+=1
for i in b:
if i%2:
bo+=1
else:
be+=1
print(min(ao,be)+min(ae,bo))
|
1556116500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["2 2 6 6 0", "1 2 11 20 15 10 5 0"]
|
40a2d69987359fc83a9c3e5eff52ce34
| null |
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of $$$m$$$. You can make hacks only if both versions are solved.Chiori loves dolls and now she is going to decorate her bedroom!Β As a doll collector, Chiori has got $$$n$$$ dolls. The $$$i$$$-th doll has a non-negative integer value $$$a_i$$$ ($$$a_i < 2^m$$$, $$$m$$$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $$$2^n$$$ different picking ways.Let $$$x$$$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $$$x = 0$$$). The value of this picking way is equal to the number of $$$1$$$-bits in the binary representation of $$$x$$$. More formally, it is also equal to the number of indices $$$0 \leq i < m$$$, such that $$$\left\lfloor \frac{x}{2^i} \right\rfloor$$$ is odd.Tell her the number of picking ways with value $$$i$$$ for each integer $$$i$$$ from $$$0$$$ to $$$m$$$. Due to the answers can be very huge, print them by modulo $$$998\,244\,353$$$.
|
Print $$$m+1$$$ integers $$$p_0, p_1, \ldots, p_m$$$ Β β $$$p_i$$$ is equal to the number of picking ways with value $$$i$$$ by modulo $$$998\,244\,353$$$.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 35$$$) Β β the number of dolls and the maximum value of the picking way. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^m$$$) Β β the values of dolls.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_072.jsonl
|
fe093b357f67a7d61068e7b425fd9f98
|
512 megabytes
|
["4 4\n3 5 8 14", "6 7\n11 45 14 9 19 81"]
|
PASSED
|
MOD = 998244353
BOUND = 19
n, m = map(int, input().split())
l = list(map(int,input().split()))
basis = []
for p in range(m-1,-1,-1):
p2 = pow(2,p)
nex = -1
for i in range(n):
if l[i] >= p2:
nex = l[i]
break
if nex != -1:
basis.append(nex)
for i in range(n):
if l[i] >= p2:
l[i] ^= nex
extra = n - len(basis)
def add(a, b):
out = [0] * (max(len(a), len(b)))
for i in range(len(a)):
out[i] = a[i]
for i in range(len(b)):
out[i] += b[i]
out[i] %= MOD
return out
def addSh(a, b):
out = [0] * (max(len(a) + 1, len(b)))
for i in range(len(a)):
out[i + 1] = a[i]
for i in range(len(b)):
out[i] += b[i]
out[i] %= MOD
return out
i = 0
curr = dict()
curr[0] = [1]
for p in range(m-1,-1,-1):
p2 = pow(2,p)
if i < len(basis) and basis[i] >= p2:
currN = dict(curr)
for v in curr:
if v ^ basis[i] not in currN:
currN[v ^ basis[i]] = [0]
currN[v ^ basis[i]] = add(curr[v], currN[v ^ basis[i]])
curr = currN
i += 1
currN = dict(curr)
for v in curr:
if v >= p2:
if v ^ p2 not in currN:
currN[v ^ p2] = [0]
currN[v ^ p2] = addSh(curr[v], currN[v ^ p2])
del currN[v]
curr = currN
out = curr[0]
while len(out) < m + 1:
out.append(0)
for i in range(m + 1):
out[i] *= pow(2, extra, MOD)
out[i] %= MOD
print(' '.join(map(str,out)))
|
1586961300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4 7 3 5 3", "2 6 4 5 8 8 6"]
|
c51e15aeb3f287608a26b85865546e85
| null |
Leha like all kinds of strange things. Recently he liked the function F(n,βk). Consider all possible k-element subsets of the set [1,β2,β...,βn]. For subset find minimal element in it. F(n,βk) β mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i,βj such that 1ββ€βi,βjββ€βm the condition Aiββ₯βBj holds. Help Leha rearrange the numbers in the array A so that the sum is maximally possible, where A' is already rearranged array.
|
Output m integers a'1,βa'2,β...,βa'm β array A' which is permutation of the array A.
|
First line of input data contains single integer m (1ββ€βmββ€β2Β·105) β length of arrays A and B. Next line contains m integers a1,βa2,β...,βam (1ββ€βaiββ€β109) β array A. Next line contains m integers b1,βb2,β...,βbm (1ββ€βbiββ€β109) β array B.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_017.jsonl
|
8c464fa54ce1bc101b8be289968ad171
|
256 megabytes
|
["5\n7 3 5 3 4\n2 1 3 2 3", "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2"]
|
PASSED
|
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
bb = list(enumerate(b))
bb = sorted(bb, key = lambda x:x[1])
#print (bb)
a.sort(reverse=True)
c = [0] * n
for i in range(n):
#print (bb[i][0])
c[bb[i][0]] = a[i]
print (*c)
|
1503068700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1\n0\n1337"]
|
dc67dd2102c70ea476df642b863ae8d3
|
NoteThere is only one suitable pair in the first test case: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \cdot 9 = 19$$$).
|
You are given two integers $$$A$$$ and $$$B$$$, calculate the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true; $$$conc(a, b)$$$ is the concatenation of $$$a$$$ and $$$b$$$ (for example, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). $$$a$$$ and $$$b$$$ should not contain leading zeroes.
|
Print one integer β the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true.
|
The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. Each test case contains two integers $$$A$$$ and $$$B$$$ $$$(1 \le A, B \le 10^9)$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_023.jsonl
|
ea215df988ca773d780e59bf8f6efab1
|
256 megabytes
|
["3\n\n1 11\n\n4 2\n\n191 31415926"]
|
PASSED
|
from math import ceil
def ii():return int(input())
def mi():return map(int,input().split())
def li():return list(mi())
def si():return input()
t=ii()
while(t):
t-=1
a,b=mi()
x=9
c=0
while(b>=x):
c+=1
x=x*10+9
print(a*c)
|
1579012500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["ckpuv\naababab\nzzzzzz"]
|
80fd03a1cbdef86a5f00ada85e026890
|
NoteA 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$$$.In the first test case, $$$f(t) = 0$$$ and the values of prefix function are $$$[0, 0, 0, 0, 0]$$$ for any permutation of letters. String ckpuv is the lexicographically smallest permutation of letters of string vkcup.In the second test case, $$$f(t) = 1$$$ and the values of prefix function are $$$[0, 1, 0, 1, 0, 1, 0]$$$.In the third test case, $$$f(t) = 5$$$ and the values of prefix function are $$$[0, 1, 2, 3, 4, 5]$$$.
|
Prefix function of string $$$t = t_1 t_2 \ldots t_n$$$ and position $$$i$$$ in it is defined as the length $$$k$$$ of the longest proper (not equal to the whole substring) prefix of substring $$$t_1 t_2 \ldots t_i$$$ which is also a suffix of the same substring.For example, for string $$$t = $$$ abacaba the values of the prefix function in positions $$$1, 2, \ldots, 7$$$ are equal to $$$[0, 0, 1, 0, 1, 2, 3]$$$.Let $$$f(t)$$$ be equal to the maximum value of the prefix function of string $$$t$$$ over all its positions. For example, $$$f($$$abacaba$$$) = 3$$$.You are given a string $$$s$$$. Reorder its characters arbitrarily to get a string $$$t$$$ (the number of occurrences of any character in strings $$$s$$$ and $$$t$$$ must be equal). The value of $$$f(t)$$$ must be minimized. Out of all options to minimize $$$f(t)$$$, choose the one where string $$$t$$$ is the lexicographically smallest.
|
For each test case print a single string $$$t$$$. The multisets of letters in strings $$$s$$$ and $$$t$$$ must be equal. The value of $$$f(t)$$$, the maximum of prefix functions in string $$$t$$$, must be as small as possible. String $$$t$$$ must be the lexicographically smallest string out of all strings satisfying the previous conditions.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The only line of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase English letters. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100 |
train_105.jsonl
|
4bdd501ed70881341216ac6f0f1b69cf
|
512 megabytes
|
["3\nvkcup\nabababa\nzzzzzz"]
|
PASSED
|
import sys
input = sys.stdin.readline
inf = float('inf')
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
t = getInt()
# t = 1
# observations, the maximum number of Good Assignments = len(set(a)) (i.e the number of unuquie elements in the array a)
# how to we assign so that all res[i] != i
# let define too set, good = set(a), i.e the people who defnitely receive gifts by a people whose wish is fullfied
# bad = the set people who no one wish to give to
# for set good, if we assign a person in set good to another person in set good, then the bad person might be left over then he could assign to himself
# hence, one possilbe approach is to fullfill the request of people in the bad group first
# we notice that the wish of the first people in the bad group can always be fullied
# we keep fullfiled the wishes of people in the bad group, if we can not , the we should assign the smallest bad people which no one is assinged to for him, this is always possible since the wish of first bad people always be filled
# now traverse through the array again, now we know we would only process peoople in the good list, fullfill his wish if we can, otherwise assign him to the next bad people who one is assinged to again (since the set of good and bad do not itersect so no res[i] = i would not happen)
# and we know that some good people would take up all other good assignments, so the godo peole who are not assigned have to assign to bad people, so the algoritm works correctly
def solve():
s = getStr()
n = len(s)
from collections import Counter
cnt = Counter(s)
a = sorted(cnt)
if min(s) == max(s):
print(s)
elif min(cnt.values()) == 1:
it = min(i for i in cnt if cnt[i] == 1)
res = it + "".join(sorted(s.replace(it, "")))
print(res)
else:
# if okay when the frquent of the other is enough to cover i
i = min(a)
if n - cnt[i] >= cnt[i] - 2:
# can make i, i
res = [i, i]
pool = sorted(j for j in s if j > i)
for k in range(len(pool)):
res.append(pool[k])
if k < cnt[i]-2:
res.append(i)
print(*res, sep="")
else:
# can not make ii, make ij
if len(cnt) == 2:
res = i + a[1] * cnt[a[1]] + i * (cnt[i]-1)
else:
res = i + a[1] + i * (cnt[i]-1) + a[2]
for i in range(1, len(a)):
res += a[i] * (cnt[a[i]] - (i <= 2))
print(res)
# min frequent is 1 easy
# now all char >= 2 frequent
# can always make f(t) = 1
# choose the strnig so that f(t) = 1
# the answer muts be of frefix xx, then as long as xx not in t then ok
for _ in range(t):
solve()
|
1626532500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["0\n10\n-1\n0\n-1\n21\n0\n273000"]
|
3035265a44fcc3bb6317bf1b9662fc76
|
NoteFor the first testcase, $$$B=\{-3,-2,-1,0,1,2,3\}$$$ and $$$C=\{-1,1,3,5\}$$$. There is no such arithmetic progression which can be equal to $$$A$$$ because $$$5$$$ is not present in $$$B$$$ and for any $$$A$$$, $$$5$$$ should not be present in $$$C$$$ also. For the second testcase, $$$B=\{-9,-6,-3,0,3,6,9,12,15,18,21\}$$$ and $$$C=\{0,6,12\}$$$. There are $$$10$$$ possible arithmetic progressions which can be $$$A$$$: $$$\{0,6,12\}$$$ $$$\{0,2,4,6,8,10,12\}$$$ $$$\{0,2,4,6,8,10,12,14\}$$$ $$$\{0,2,4,6,8,10,12,14,16\}$$$ $$$\{-2,0,2,4,6,8,10,12\}$$$ $$$\{-2,0,2,4,6,8,10,12,14\}$$$ $$$\{-2,0,2,4,6,8,10,12,14,16\}$$$ $$$\{-4,-2,0,2,4,6,8,10,12\}$$$ $$$\{-4,-2,0,2,4,6,8,10,12,14\}$$$ $$$\{-4,-2,0,2,4,6,8,10,12,14,16\}$$$ For the third testcase, $$$B=\{2,7,12,17,22\}$$$ and $$$C=\{7,12,17,22\}$$$. There are infinitely many arithmetic progressions which can be $$$A$$$ like: $$$\{7,12,17,22\}$$$ $$$\{7,12,17,22,27\}$$$ $$$\{7,12,17,22,27,32\}$$$ $$$\{7,12,17,22,27,32,37\}$$$ $$$\{7,12,17,22,27,32,37,42\}$$$ $$$\ldots$$$
|
Long ago, you thought of two finite arithmetic progressions $$$A$$$ and $$$B$$$. Then you found out another sequence $$$C$$$ containing all elements common to both $$$A$$$ and $$$B$$$. It is not hard to see that $$$C$$$ is also a finite arithmetic progression. After many years, you forgot what $$$A$$$ was but remember $$$B$$$ and $$$C$$$. You are, for some reason, determined to find this lost arithmetic progression. Before you begin this eternal search, you want to know how many different finite arithmetic progressions exist which can be your lost progression $$$A$$$. Two arithmetic progressions are considered different if they differ in their first term, common difference or number of terms.It may be possible that there are infinitely many such progressions, in which case you won't even try to look for them! Print $$$-1$$$ in all such cases. Even if there are finite number of them, the answer might be very large. So, you are only interested to find the answer modulo $$$10^9+7$$$.
|
For each testcase, print a single line containing a single integer. If there are infinitely many finite arithmetic progressions which could be your lost progression $$$A$$$, print $$$-1$$$. Otherwise, print the number of finite arithmetic progressions which could be your lost progression $$$A$$$ modulo $$$10^9+7$$$. In particular, if there are no such finite arithmetic progressions, print $$$0$$$.
|
The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) denoting the number of testcases. The first line of each testcase contains three integers $$$b$$$, $$$q$$$ and $$$y$$$ ($$$-10^9\leq b\leq 10^9$$$, $$$1\leq q\leq 10^9$$$, $$$2\leq y\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$B$$$ respectively. The second line of each testcase contains three integers $$$c$$$, $$$r$$$ and $$$z$$$ ($$$-10^9\leq c\leq 10^9$$$, $$$1\leq r\leq 10^9$$$, $$$2\leq z\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$C$$$ respectively.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_096.jsonl
|
ef8202a9f9096c5fd19ef569e12d4c17
|
256 megabytes
|
["8\n\n-3 1 7\n\n-1 2 4\n\n-9 3 11\n\n0 6 3\n\n2 5 5\n\n7 5 4\n\n2 2 11\n\n10 5 3\n\n0 2 9\n\n2 4 3\n\n-11 4 12\n\n1 12 2\n\n-27 4 7\n\n-17 8 2\n\n-8400 420 1000000000\n\n0 4620 10"]
|
PASSED
|
import sys
ipt=sys.stdin.readline
def sq(x):
st=0
en=10**10
while st<en:
y=(st+en)//2+1
if y**2>x:
en=y-1
else:
st=y
return st
def gcd(xx, yy):
return xx if yy==0 else gcd(yy, xx%yy)
mod=10**9+7
T=int(ipt())
for _ in range(T):
b, q, y=map(int, ipt().split())
c, r, z=map(int, ipt().split())
if r%q or b>c or (b+q*(y-1))<(c+r*(z-1)) or (c-b)%q:
print(0)
continue
if c-r<b or c+z*r>b+(y-1)*q:
print(-1)
continue
ans=0
for i in range(1, sq(r)+1):
if r%i==0:
if i**2==r:
if r==q*i//gcd(q, i):
ans=(ans+i**2)%mod
else:
if r==q*i//gcd(q, i):
ans=(ans+(r//i)**2)%mod
if r==q*(r//i)//gcd(q, r//i):
ans=(ans+i**2)%mod
print(ans)
|
1651329300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["1\n2\n3\n3\n5\n4"]
|
0eee4b8f074e02311329d5728138c7fe
| null |
$$$2^k$$$ teams participate in a playoff tournament. The tournament consists of $$$2^k - 1$$$ games. They are held as follows: first of all, the teams are split into pairs: team $$$1$$$ plays against team $$$2$$$, team $$$3$$$ plays against team $$$4$$$ (exactly in this order), and so on (so, $$$2^{k-1}$$$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $$$2^{k-1}$$$ teams remain. If only one team remains, it is declared the champion; otherwise, $$$2^{k-2}$$$ games are played: in the first one of them, the winner of the game "$$$1$$$ vs $$$2$$$" plays against the winner of the game "$$$3$$$ vs $$$4$$$", then the winner of the game "$$$5$$$ vs $$$6$$$" plays against the winner of the game "$$$7$$$ vs $$$8$$$", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with $$$k = 3$$$: Let the string $$$s$$$ consisting of $$$2^k - 1$$$ characters describe the results of the games in chronological order as follows: if $$$s_i$$$ is 0, then the team with lower index wins the $$$i$$$-th game; if $$$s_i$$$ is 1, then the team with greater index wins the $$$i$$$-th game; if $$$s_i$$$ is ?, then the result of the $$$i$$$-th game is unknown (any team could win this game). Let $$$f(s)$$$ be the number of possible winners of the tournament described by the string $$$s$$$. A team $$$i$$$ is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team $$$i$$$ is the champion.You are given the initial state of the string $$$s$$$. You have to process $$$q$$$ queries of the following form: $$$p$$$ $$$c$$$Β β replace $$$s_p$$$ with character $$$c$$$, and print $$$f(s)$$$ as the result of the query.
|
For each query, print one integerΒ β $$$f(s)$$$.
|
The first line contains one integer $$$k$$$ ($$$1 \le k \le 18$$$). The second line contains a string consisting of $$$2^k - 1$$$ charactersΒ β the initial state of the string $$$s$$$. Each character is either ?, 0, or 1. The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$)Β β the number of queries. Then $$$q$$$ lines follow, the $$$i$$$-th line contains an integer $$$p$$$ and a character $$$c$$$ ($$$1 \le p \le 2^k - 1$$$; $$$c$$$ is either ?, 0, or 1), describing the $$$i$$$-th query.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,800 |
train_085.jsonl
|
2cb9dce8b147673c6414b28cbc35a4ac
|
256 megabytes
|
["3\n0110?11\n6\n5 1\n6 ?\n7 ?\n1 ?\n5 ?\n1 1"]
|
PASSED
|
import sys
def upd(ix, cur):
if s[ix] == '?':
tree[cur] = tree[cur << 1] + tree[(cur << 1) + 1]
else:
tree[cur] = tree[(cur << 1) + (int(s[ix]) ^ 1)]
input = lambda: sys.stdin.buffer.readline().decode().strip()
ispow2 = lambda x: x and (not (x & (x - 1)))
k, s = int(input()), list(input())
tree, n, out = [1] * (1 << (k + 1)), len(s), []
for i in range(len(s)):
cur = n - i
upd(i, cur)
for i in range(int(input())):
ix, ch = input().split()
ix = int(ix) - 1
cur, s[ix] = n - ix, ch
while cur:
upd(ix, cur)
cur >>= 1
ix = n - cur
out.append(tree[1])
print('\n'.join(map(str, out)))
|
1622817300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["1 1 0 1 \n0 1 1 0 0 0 1 \n0 0 0 \n0 0 0 1 \n1 0 1"]
|
9dc1bee4e53ced89d827826f2d83dabf
|
NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$: $$$B_1=[\color{blue}{1},1,0,1]$$$; $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$; $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$; $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$ And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.
|
Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.
|
For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) Β β the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_110.jsonl
|
f3d4714fc7e831eadbe1b17d4a2e5d34
|
256 megabytes
|
["5\n4\n2 4 2 4\n7\n0 3 4 2 3 2 7\n3\n0 0 0\n4\n0 0 0 4\n3\n1 2 3"]
|
PASSED
|
import sys
input = lambda: sys.stdin.buffer.readline().decode().strip()
for _ in range(int(input())):
n, a = int(input()), [int(x) for x in input().split()]
ans, ones = [], sum(a) // n
mem = [0] * (n + 1)
for i in reversed(range(n)):
mem[i] += mem[i + 1]
a[i] -= mem[i]
if a[i] == i + 1:
mem[i] += 1
mem[i - ones] -= 1
ones -= 1
ans.append(1)
elif a[i] == 1:
mem[i] += 1
mem[i - ones] -= 1
ans.append(0)
else:
ans.extend([0] * (i + 1))
break
print(*ans[::-1])
|
1650206100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3 4 2 1\n-1\n6 7 4 5 3 2 1\n5 4 1 2 3\n2 1"]
|
cdcf95e29d3260a07dded74286fc3798
|
NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[3, 2, 1]$$$ have fixed points, and in $$$[2, 3, 1]$$$ and $$$[3, 1, 2]$$$ the first condition is met not for all positions.
|
A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences $$$[3, 1, 4, 2]$$$, [$$$1$$$] and $$$[2,1]$$$ are permutations, but $$$[1,2,1]$$$, $$$[0,1]$$$ and $$$[1,3,4]$$$ are not.For a given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time: For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \le i \le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$. the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \le i \le n$$$), $$$p_i \neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since: to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$; to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$; to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$; to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$. for all $$$i$$$ is $$$p_i \ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.
|
For each test case, print on a separate line: any funny permutation $$$p$$$ of length $$$n$$$; or the number -1 if the permutation you are looking for does not exist.
|
The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. The description of the test cases follows. Each test case consists of f single line containing one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). 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
| 800 |
train_084.jsonl
|
36f2fb77e33b93be891fec3c83348a49
|
256 megabytes
|
["5\n\n4\n\n3\n\n7\n\n5\n\n2"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
if n == 3:
print('-1')
else :
print( n, n-1, *range(1,n-1) )
|
1665498900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["YES\n001100\nNO\nYES\n01100110\nYES\n0110", "YES\n0101100100", "YES\n1010000011"]
|
328291f7ef1de8407d8167a1881ec2bb
|
NoteHere are the graphs from the first example. The vertices in the lenient vertex covers are marked red.
|
You are given a simple connected undirected graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$.A vertex cover of a graph is a set of vertices such that each edge has at least one of its endpoints in the set.Let's call a lenient vertex cover such a vertex cover that at most one edge in it has both endpoints in the set.Find a lenient vertex cover of a graph or report that there is none. If there are multiple answers, then print any of them.
|
For each testcase, the first line should contain YES if a lenient vertex cover exists, and NO otherwise. If it exists, the second line should contain a binary string $$$s$$$ of length $$$n$$$, where $$$s_i = 1$$$ means that vertex $$$i$$$ is in the vertex cover, and $$$s_i = 0$$$ means that vertex $$$i$$$ isn't. If there are multiple answers, then print any of them.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^6$$$; $$$n - 1 \le m \le \min(10^6, \frac{n \cdot (n - 1)}{2})$$$)Β β the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$)Β β the descriptions of the edges. For each testcase, the graph is connected and doesn't have multiple edges. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^6$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,600 |
train_083.jsonl
|
f5fb58c7f9711e30e04b01aef52310f8
|
512 megabytes
|
["4\n\n6 5\n\n1 3\n\n2 4\n\n3 4\n\n3 5\n\n4 6\n\n4 6\n\n1 2\n\n2 3\n\n3 4\n\n1 4\n\n1 3\n\n2 4\n\n8 11\n\n1 3\n\n2 4\n\n3 5\n\n4 6\n\n5 7\n\n6 8\n\n1 2\n\n3 4\n\n5 6\n\n7 8\n\n7 2\n\n4 5\n\n1 2\n\n2 3\n\n3 4\n\n1 3\n\n2 4", "1\n\n10 15\n\n9 4\n\n3 4\n\n6 4\n\n1 2\n\n8 2\n\n8 3\n\n7 2\n\n9 5\n\n7 8\n\n5 10\n\n1 4\n\n2 10\n\n5 3\n\n5 7\n\n2 9", "1\n\n10 19\n\n7 9\n\n5 3\n\n3 4\n\n1 6\n\n9 4\n\n1 4\n\n10 5\n\n7 1\n\n9 2\n\n8 3\n\n7 3\n\n10 9\n\n2 10\n\n9 8\n\n3 2\n\n1 5\n\n10 7\n\n9 5\n\n1 2"]
|
PASSED
|
input = __import__('sys').stdin.readline
DFS_IN = 0
DFS_OUT = 1
def solve():
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
u, v = map(lambda x: int(x)-1, input().split())
adj[u].append(v)
adj[v].append(u)
cnt_odd = 0
dfs_in = [0]*n
dfs_out = [0]*n
depth = [0]*n + [-1]
color = [-1]*n + [1]
removed_back_edge = None
dp = [[0]*2 for _ in range(n+1)]
i = 0
stack = [(0, -1, DFS_IN)]
while len(stack) > 0:
i += 1
u, par, state = stack.pop()
if state == DFS_IN:
if color[u] != -1:
continue
dfs_in[u] = i
color[u] = color[par]^1
depth[u] = depth[par] + 1
stack.append((u, par, DFS_OUT))
for v in adj[u]:
if color[v] == -1:
stack.append((v, u, DFS_IN))
elif depth[v] - depth[u] not in (-1, 1) and depth[u] > depth[v]:
# back edge
if color[u] == color[v]:
if removed_back_edge is None:
removed_back_edge = (u, v)
else:
removed_back_edge = (n, n)
parity = color[u] ^ color[v] ^ 1
dp[u][parity] += 1
dp[v][parity] -= 1
cnt_odd += parity
if state == DFS_OUT:
dfs_out[u] = i
# update dp
dp[par][0] += dp[u][0]
dp[par][1] += dp[u][1]
color.pop()
if removed_back_edge is None or removed_back_edge != (n, n):
# remove back edge if possible
xor = 1 if removed_back_edge is not None and (color[removed_back_edge[0]], color[removed_back_edge[1]]) == (0, 0) else 0
print('YES')
print(''.join(str(x ^ xor) for x in color))
return
# try removing a span edge
invert_node = next((u for u in range(1, n) if dp[u][1] == cnt_odd and dp[u][0] == 0), None)
if invert_node is None:
print('NO')
return
xor = color[invert_node]
xor_subtree = lambda u: dfs_in[invert_node] <= dfs_in[u] <= dfs_out[invert_node]
print('YES')
print(''.join(str(x ^ (1 if xor_subtree(u) else 0) ^ xor) for u, x in enumerate(color)))
for _ in range(int(input())):
solve()
|
1652452500
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["Yes", "No", "Yes"]
|
65efbc0a1ad82436100eea7a2378d4c2
|
NoteBy we define the remainder of integer division of i by k.In first sample case: On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.
|
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to nβ-β1 and 0 to mβ-β1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.
|
If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".
|
The first line contains two integer n and m (1ββ€βn,βmββ€β100). The second line contains integer b (0ββ€βbββ€βn), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1,βx2,β...,βxb (0ββ€βxiβ<βn), denoting the list of indices of happy boys. The third line conatins integer g (0ββ€βgββ€βm), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1,βy2,β... ,βyg (0ββ€βyjβ<βm), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,300 |
train_013.jsonl
|
fc705760b608d2a0f184bd7d93b224d4
|
256 megabytes
|
["2 3\n0\n1 0", "2 4\n1 0\n1 2", "2 3\n1 0\n1 1"]
|
PASSED
|
n, m = map(int, raw_input().split())
hb = [0] * n
hg = [0] * m
for i in map(int, raw_input().split())[1:]:
hb[i] = 1
for i in map(int, raw_input().split())[1:]:
hg[i] = 1
for i in range(2 * n * m):
hb[i % n] = hg[i % m] = hb[i % n] | hg[i % m]
print "Yes" if hb.count(1) + hg.count(1) == n + m else "No"
|
1424190900
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["17", "71"]
|
bc6b8fda79c257e6c4e280d7929ed8a1
|
NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71.
|
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXXΒ β beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1βββ2βββ...βββnβββ1. Formally, for every 1ββ€βiβ<βn there is a road between i-th and iβ+β1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1ββ€βiββ€βn,ββiββ βx, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ciΒ·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (aβ<βb), such that there is a road between a and b you are to find sum of products caΒ·cb. Will you help her?
|
Print the only integerΒ β summary price of passing each of the roads in XXX.
|
The first line of the input contains two integers n and k (3ββ€βnββ€β100β000,β1ββ€βkββ€βn)Β β the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1,βc2,β...,βcn (1ββ€βciββ€β10β000)Β β beauty values of the cities. The third line of the input contains k distinct integers id1,βid2,β...,βidk (1ββ€βidiββ€βn)Β β indices of capital cities. Indices are given in ascending order.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400 |
train_018.jsonl
|
65e3138e770d1b3537a3e0c6f9834dac
|
256 megabytes
|
["4 1\n2 3 1 2\n3", "5 2\n3 5 2 2 4\n1 4"]
|
PASSED
|
n, k = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
ids = [(int(x)-1) for x in input().split()]
s = sum(c)
ans = 0
for i in range(n):
ans += (c[i] * c[(i+1)%n])
for i in range(k):
if (abs(ids[i] - ids[(i+1)%k]) == 1) or (ids[i] == n-1 and ids[0] == 0):
ans += c[ids[i]]*c[ids[(i+1)%k]]
temp = 0
for i in range(k):
ans += c[ids[i]] * (s - c[(ids[i]-1)%n] - c[(ids[i]+1)%n] - c[ids[i]])
ans -= c[ids[i]]*temp
temp += c[ids[i]]
print(repr(ans))
|
1470323700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["4", "5", "164"]
|
2fad8bea91cf6db14b34271e88ab093c
|
NoteThe queries in the first example are $$$0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0$$$. The answers are $$$11, 9, 7, 3, 1, 5, 8, 7, 5, 7, 11$$$. The queries in the second example are $$$3, 0, 2, 1, 6, 0, 3, 5, 4, 1$$$. The answers are $$$14, 19, 15, 16, 11, 19, 14, 12, 13, 16$$$. The queries in the third example are $$$75, 0, 0, \dots$$$. The answers are $$$50, 150, 150, \dots$$$.
|
You are given a connected weighted undirected graph, consisting of $$$n$$$ vertices and $$$m$$$ edges.You are asked $$$k$$$ queries about it. Each query consists of a single integer $$$x$$$. For each query, you select a spanning tree in the graph. Let the weights of its edges be $$$w_1, w_2, \dots, w_{n-1}$$$. The cost of a spanning tree is $$$\sum \limits_{i=1}^{n-1} |w_i - x|$$$ (the sum of absolute differences between the weights and $$$x$$$). The answer to a query is the lowest cost of a spanning tree.The queries are given in a compressed format. The first $$$p$$$ $$$(1 \le p \le k)$$$ queries $$$q_1, q_2, \dots, q_p$$$ are provided explicitly. For queries from $$$p+1$$$ to $$$k$$$, $$$q_j = (q_{j-1} \cdot a + b) \mod c$$$.Print the xor of answers to all queries.
|
Print a single integerΒ β the xor of answers to all queries.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 50$$$; $$$n - 1 \le m \le 300$$$)Β β the number of vertices and the number of edges in the graph. Each of the next $$$m$$$ lines contains a description of an undirected edge: three integers $$$v$$$, $$$u$$$ and $$$w$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$; $$$0 \le w \le 10^8$$$)Β β the vertices the edge connects and its weight. Note that there might be multiple edges between a pair of vertices. The edges form a connected graph. The next line contains five integers $$$p, k, a, b$$$ and $$$c$$$ ($$$1 \le p \le 10^5$$$; $$$p \le k \le 10^7$$$; $$$0 \le a, b \le 10^8$$$; $$$1 \le c \le 10^8$$$)Β β the number of queries provided explicitly, the total number of queries and parameters to generate the queries. The next line contains $$$p$$$ integers $$$q_1, q_2, \dots, q_p$$$ ($$$0 \le q_j < c$$$)Β β the first $$$p$$$ queries.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,400 |
train_104.jsonl
|
bf177dedfa21c7c12d0d1f67579a4632
|
256 megabytes
|
["5 8\n4 1 4\n3 1 0\n3 5 3\n2 5 4\n3 4 8\n4 3 4\n4 2 8\n5 3 9\n3 11 1 1 10\n0 1 2", "6 7\n2 4 0\n5 4 7\n2 4 0\n2 1 7\n2 6 1\n3 4 4\n1 4 8\n4 10 3 3 7\n3 0 2 1", "3 3\n1 2 50\n2 3 100\n1 3 150\n1 10000000 0 0 100000000\n75"]
|
PASSED
|
from bisect import bisect_left
from collections import defaultdict
I = lambda: [int(x) for x in input().split()]
class DSU:
def __init__(self, N):
self.p = list(range(N))
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, x, y):
self.p[self.find(x)] = self.find(y)
edges = []
n, m = I()
for _ in range(m):
x, y, w = I()
edges += [(x - 1, y - 1, w)]
p, k, a, b, c = I()
Q = I()
for _ in range(k - p):
Q += [(Q[-1] * a + b) % c]
def kruskal(x):
dsu, ans, W, sgn = DSU(n), [], 0, 0
E = sorted(edges, key=lambda q: abs(x - q[2]))
for u, v, w in E:
if dsu.find(u) == dsu.find(v): continue
s = -1 + 2 * int(x <= w)
dsu.union(u, v)
ans += [w]
W += w * s
sgn += s
return sorted(ans), W, sgn
points = defaultdict(tuple)
at, maxval = 0, 10**8
while at <= maxval:
cur_weights = kruskal(at)[0]
lo, hi = at, maxval
while lo < hi:
mid = (lo + hi + 1) // 2
if kruskal(mid)[0] == cur_weights:
lo = mid
else:
hi = mid - 1
points[lo] = kruskal(lo)
at = lo + 1
for _, _, w in edges:
points[w] = kruskal(w)
w, out = sorted(points), 0
for x in Q:
idx = bisect_left(w, x)
if idx >= len(w): idx -= 1
out ^= (points[w[idx]][1] - x*points[w[idx]][2])
print(out)
|
1643639700
|
[
"math",
"trees",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
1
] |
|
2 seconds
|
["NO\nYES\nNO\nYES\nYES\nNO"]
|
f4958b4833cafa46fa71357ab1ae41af
| null |
You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.
|
For each test case, output on a separate line: "YES" if $$$n$$$ has an odd divisor, greater than one; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 900 |
train_086.jsonl
|
1d3091aa2b9448512e0bb7478a7a623b
|
256 megabytes
|
["6\n2\n3\n4\n5\n998244353\n1099511627776"]
|
PASSED
|
n=int(input())
for i in range (n):
t=int(input())
while t%2==0:
t/=2
if t>1:
print("YES")
else:
print("NO")
|
1611586800
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["2\n2 1\n4\n2 1 4 3\n9\n6 9 1 2 3 4 5 7 8\n3\n1 2 3"]
|
677972c7d86ce9fd0808105331f77fe0
|
NoteIn the first test case, the subset $$$\{a_2, a_1\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\{a_1, a_3\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset.
|
A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.
|
Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.
|
Each test consists of 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 line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 100$$$)Β β the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 200$$$)Β β the elements of the array.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_087.jsonl
|
690c00858cc49b20512653923ed3d513
|
256 megabytes
|
["4\n3\n8 1 2\n4\n6 9 4 2\n9\n1 2 3 4 5 6 7 8 9\n3\n200 199 198"]
|
PASSED
|
tt = int(input())
fa = []
n = 500000
for i in range(n + 1):
fa.append(i)
fa[1] = 0
i = 2
while i <= n:
if fa[i] != 0:
j = i + i
while j <= n:
fa[j] = 0
j = j + i
i += 1
fa = set(fa)
fa.remove(0)
for i in range(tt):
ar = []
f = int(input())
y = input()
ar = y.split()
ar = list(map(int, ar))
a = sum(ar)
k = 0
if (a not in fa):
print(len(ar))
for x in range(1, len(ar) + 1):
print(x, end=' ')
print('')
else:
for j in range(len(ar)):
b = a - ar[j]
if b not in fa:
print(len(ar) - 1)
for y in range(j):
print(y + 1, end=' ')
for y in range(j + 1, len(ar)):
print(y + 1, end=' ')
print('')
break
else:
for j in range(len(ar)):
ty = False
for p in range(j, len(ar)):
b = a - ar[j] - ar[p]
if b not in fa and b > 0:
print(len(ar) - 1)
for y in range(j):
print(y + 1, end=' ')
for y in range(j + 1, len(ar)):
print(y + 1, end=' ')
print('')
ty = True
break
if ty:
ty = False
break
|
1634468700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["2", "1\n0", "5\n3\n3\n4"]
|
776706f09cd446bc144a2591e424e437
| null |
You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon.
|
The output should contain t integer numbers, each on a separate line, where i-th number is the answer for the i-th point. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
|
The first line contains integer n β the number of vertices of the polygon (3ββ€βnββ€β100000). The polygon description is following: n lines containing coordinates of the vertices in clockwise order (integer x and y not greater than 109 by absolute value). It is guaranteed that the given polygon is nondegenerate and convex (no three points lie on the same line). The next line contains integer t (1ββ€βtββ€β20) β the number of points which you should count the answer for. It is followed by t lines with coordinates of the points (integer x and y not greater than 109 by absolute value).
|
standard output
|
standard input
|
Python 2
|
Python
| 2,500 |
train_069.jsonl
|
6cfac2fef6d680a86fe8556abfd8af65
|
256 megabytes
|
["4\n5 0\n0 0\n0 5\n5 5\n1\n1 3", "3\n0 0\n0 5\n5 0\n2\n1 1\n10 10", "5\n7 6\n6 3\n4 1\n1 2\n2 4\n4\n3 3\n2 3\n5 5\n4 2"]
|
PASSED
|
import sys
import gc
gc.disable()
rl = sys.stdin.readline
n = int(rl())
p = [complex(float(x),float(y)) for x,y in map(str.split,map(rl,[-1]*n))]
pi = [c.conjugate() for c in p]
fn = [0.5*x*(x-1) for x in xrange(0,n+1)]
fnn = fn[::-1]
for jj in xrange(int(rl())):
a = complex(*map(float,rl().split()))
pp = map(a.__rsub__,p)
pc = map(a.conjugate().__rsub__,pi)
i = 1
ri = 0
b = pp[0]
try:
for j,c in enumerate(pc):
while (b*c).imag<0:
ri += fn[j-i]
b=pp[i]
i+=1
for j,c in enumerate(pc):
while (b*c).imag<0:
ri += fnn[i-j]
b=pp[i]
i+=1
except:
print n*(n-1)*(n-2)/6-int(ri)
else:
print 0
|
1294992000
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES", "NO"]
|
52f4f2a48063c9d0e412a5f78c873e6f
|
NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations: Decrease $$$a_1$$$ and $$$a_2$$$, Decrease $$$a_3$$$ and $$$a_4$$$, Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.
|
You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.
|
Print "YES" if it is possible to make all elements zero, otherwise print "NO".
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$)Β β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β the elements of the array.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_005.jsonl
|
c5ab9a828ef6ba4a275b204bbec3c526
|
256 megabytes
|
["4\n1 1 2 2", "6\n1 2 3 4 5 6"]
|
PASSED
|
x=int(input())
a=list(map(int,input().split()))
c=sum(a)
d=max(a)
if d<=c//2 and x>1 and c%2==0:
print("YES")
else:
print("NO")
|
1564936500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["392\n1 1", "240\n2 3"]
|
45ac482a6b95f44a26b7363e6756c8d1
|
NoteIn the first test case the total time of guessing all cars is equal to 3Β·8β+β3Β·8β+β4Β·8β+β9Β·8β+β5Β·40β+β1Β·40β=β392.The coordinate system of the field:
|
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has nβ+β1 dividing lines drawn from west to east and mβ+β1 dividing lines drawn from north to south, which divide the parking lot into nΒ·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i,βj) so that the square in the north-west corner has coordinates (1,β1) and the square in the south-east corner has coordinates (n,βm). See the picture in the notes for clarifications.Before the game show the organizers offer Yura to occupy any of the (nβ+β1)Β·(mβ+β1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes cΒ·d2 seconds. The time Yura spends on turning his head can be neglected.It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.
|
In the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers li and lj (0ββ€βliββ€βn,β0ββ€βljββ€βm) β the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller li. If there are still multiple such points, print the point with smaller lj. 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.
|
The first line contains two integers n and m (1ββ€βn,βmββ€β1000) β the sizes of the parking lot. Each of the next n lines contains m integers: the j-th number in the i-th line describes the "rarity" cij (0ββ€βcijββ€β100000) of the car that is located in the square with coordinates (i,βj).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_067.jsonl
|
5cc96ee4a879573f49625082bc47ddba
|
256 megabytes
|
["2 3\n3 4 5\n3 9 1", "3 4\n1 0 0 0\n0 0 3 0\n0 0 5 5"]
|
PASSED
|
def getmin(c, m):
l, r = 0, m
cx = lambda x:sum([c[i]*((x-i)*4-2)**2 for i in range(m)])
while True:
ml = (l*2+r)/3
mr = (l+r*2)/3
l, r = (ml, r) if cx(ml) > cx(mr) else (l, mr)
if r<=l+10:
px = cx(l)+1
for i in xrange(r-l+2):
if px <= cx(l+i):
r, x = (px, l+i-1)
break
px = cx(l+i)
break
return r, x
n, m = [int(i) for i in raw_input().split()]
vsum = [0]*m
hsum = [0]*n
for i in xrange(n):
row = [int(k) for k in raw_input().split()]
hsum[i] = sum(row)
vsum = [i+j for i, j in zip(vsum, row)]
r1, rx = getmin(vsum, m)
r2, ry = getmin(hsum, n)
print r1+r2
print ry, rx
|
1340983800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2"]
|
86efef40ebbdb42fbcbf2dfba7143433
|
Note Explanation: Friends should send signals 2 times to each other, first time around point $$$A2$$$ and $$$B2$$$ and second time during A's travel from point $$$A3$$$ to $$$A4$$$ while B stays in point $$$B3=B4$$$.
|
Two friends are travelling through Bubble galaxy. They say "Hello!" via signals to each other if their distance is smaller or equal than $$$d_1$$$ and it's the first time they speak to each other or at some point in time after their last talk their distance was greater than $$$d_2$$$. We need to calculate how many times friends said "Hello!" to each other. For $$$N$$$ moments, you'll have an array of points for each friend representing their positions at that moment. A person can stay in the same position between two moments in time, but if a person made a move we assume this movement as movement with constant speed in constant direction.
|
Output contains one integer number that represents how many times friends will say "Hello!" to each other.
|
The first line contains one integer number $$$N$$$ ($$$2 \leq N \leq 100\,000$$$) representing number of moments in which we captured positions for two friends. The second line contains two integer numbers $$$d_1$$$ and $$$d_2 \ (0 < d_1 < d_2 < 1000)$$$. The next $$$N$$$ lines contains four integer numbers $$$A_x,A_y,B_x,B_y$$$ ($$$0 \leq A_x, A_y, B_x, B_y \leq 1000$$$) representing coordinates of friends A and B in each captured moment.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_048.jsonl
|
848e1b3d36261192dd8a4b3162076cee
|
256 megabytes
|
["4\n2 5\n0 0 0 10\n5 5 5 6\n5 0 10 5\n14 7 10 5"]
|
PASSED
|
from sys import stdin
stdin = iter(stdin)
class Vector:
''''''
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def dot(self, vec2):
return self.x * vec2.x + self.y * vec2.y
def cross(self, vec2):
return self.x * vec2.y - self.y * vec2.x
def norm_square(self):
return self.dot(self)
def __str__(self):
return str((self.x, self.y))
__radd__ = __add__
__rsub__ = __sub__
def min_distnace_less_than_d1(ab1: Vector, ab2: Vector, d1: int):
''' '''
L = ab2 - ab1
proj1 = ab1.dot(L)
proj2 = ab2.dot(L)
between = (proj1 * proj2 < 0)
if between:
# altitude is minimum
# return altitude < d
# return |ab1.cross(L)| / sqrt(L.norm_square()) < d
return ab1.cross(L)**2 <= d1**2 * L.norm_square()
else:
# minimum edge is minimum distnace
minSquare = min([ab1.norm_square(), ab2.norm_square()])
return minSquare <= d1**2
if __name__ == "__main__":
N = int(next(stdin))
d1, d2 = (int(x) for x in next(stdin).split())
ABs = []
for _ in range(N):
Ax, Ay, Bx, By = (int(x) for x in next(stdin).split())
ABs.append(Vector(Bx, By) - Vector(Ax, Ay))
resetState = True
count = 0
for i in range(len(ABs)-1):
ab1, ab2 = ABs[i:i+2]
if resetState and min_distnace_less_than_d1(ab1, ab2, d1):
count += 1
resetState = False
resetState = resetState or (ab2.norm_square() > d2**2)
print(count)
|
1537612500
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["0 3 1 2 1 1 2 3 \n0 0 3 \n1 2 2 \n0 1 2 1 1 2 2 1 1"]
|
8629aa74df60537987611c6c1ef1a140
|
NoteThe first example is clarified in the statement.In the second example: $$$r_2=0$$$, since the path to $$$2$$$ has an amount of $$$a_j$$$ equal to $$$1$$$, only the prefix of this path of length $$$0$$$ has a smaller or equal amount of $$$b_j$$$; $$$r_3=0$$$, since the path to $$$3$$$ has an amount of $$$a_j$$$ equal to $$$1+1=2$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$100$$$ ($$$100 > 2$$$); $$$r_4=3$$$, since the path to $$$4$$$ has an amount of $$$a_j$$$ equal to $$$1+1+101=103$$$, the prefix of length $$$3$$$ of this path has an amount of $$$b_j$$$ equal to $$$102$$$, .
|
You are given a rooted tree. It contains $$$n$$$ vertices, which are numbered from $$$1$$$ to $$$n$$$. The root is the vertex $$$1$$$.Each edge has two positive integer values. Thus, two positive integers $$$a_j$$$ and $$$b_j$$$ are given for each edge.Output $$$n-1$$$ numbers $$$r_2, r_3, \dots, r_n$$$, where $$$r_i$$$ is defined as follows.Consider the path from the root (vertex $$$1$$$) to $$$i$$$ ($$$2 \le i \le n$$$). Let the sum of the costs of $$$a_j$$$ along this path be $$$A_i$$$. Then $$$r_i$$$ is equal to the length of the maximum prefix of this path such that the sum of $$$b_j$$$ along this prefix does not exceed $$$A_i$$$. Example for $$$n=9$$$. The blue color shows the costs of $$$a_j$$$, and the red color shows the costs of $$$b_j$$$. Consider an example. In this case: $$$r_2=0$$$, since the path to $$$2$$$ has an amount of $$$a_j$$$ equal to $$$5$$$, only the prefix of this path of length $$$0$$$ has a smaller or equal amount of $$$b_j$$$; $$$r_3=3$$$, since the path to $$$3$$$ has an amount of $$$a_j$$$ equal to $$$5+9+5=19$$$, the prefix of length $$$3$$$ of this path has a sum of $$$b_j$$$ equal to $$$6+10+1=17$$$ ( the number is $$$17 \le 19$$$); $$$r_4=1$$$, since the path to $$$4$$$ has an amount of $$$a_j$$$ equal to $$$5+9=14$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$6$$$ (this is the longest suitable prefix, since the prefix of length $$$2$$$ already has an amount of $$$b_j$$$ equal to $$$6+10=16$$$, which is more than $$$14$$$); $$$r_5=2$$$, since the path to $$$5$$$ has an amount of $$$a_j$$$ equal to $$$5+9+2=16$$$, the prefix of length $$$2$$$ of this path has a sum of $$$b_j$$$ equal to $$$6+10=16$$$ (this is the longest suitable prefix, since the prefix of length $$$3$$$ already has an amount of $$$b_j$$$ equal to $$$6+10+1=17$$$, what is more than $$$16$$$); $$$r_6=1$$$, since the path up to $$$6$$$ has an amount of $$$a_j$$$ equal to $$$2$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$1$$$; $$$r_7=1$$$, since the path to $$$7$$$ has an amount of $$$a_j$$$ equal to $$$5+3=8$$$, the prefix of length $$$1$$$ of this path has an amount of $$$b_j$$$ equal to $$$6$$$ (this is the longest suitable prefix, since the prefix of length $$$2$$$ already has an amount of $$$b_j$$$ equal to $$$6+3=9$$$, which is more than $$$8$$$); $$$r_8=2$$$, since the path up to $$$8$$$ has an amount of $$$a_j$$$ equal to $$$2+4=6$$$, the prefix of length $$$2$$$ of this path has an amount of $$$b_j$$$ equal to $$$1+3=4$$$; $$$r_9=3$$$, since the path to $$$9$$$ has an amount of $$$a_j$$$ equal to $$$2+4+1=7$$$, the prefix of length $$$3$$$ of this path has a sum of $$$b_j$$$ equal to $$$1+3+3=7$$$.
|
For each test case, output $$$n-1$$$ integer in one line: $$$r_2, r_3, \dots, r_n$$$.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases in the test. The descriptions of test cases follow. Each description begins with a line that contains an integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) β the number of vertices in the tree. This is followed by $$$n-1$$$ string, each of which contains three numbers $$$p_j, a_j, b_j$$$ ($$$1 \le p_j \le n$$$; $$$1 \le a_j,b_j \le 10^9$$$) β the ancestor of the vertex $$$j$$$, the first and second values an edge that leads from $$$p_j$$$ to $$$j$$$. The value of $$$j$$$ runs through all values from $$$2$$$ to $$$n$$$ inclusive. It is guaranteed that each set of input data has a correct hanged tree with a root at the vertex $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all input test cases does not exceed $$$2\cdot10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_102.jsonl
|
a23de9d86a5b8f8ef22dd604bccb9ca6
|
256 megabytes
|
["4\n\n9\n\n1 5 6\n\n4 5 1\n\n2 9 10\n\n4 2 1\n\n1 2 1\n\n2 3 3\n\n6 4 3\n\n8 1 3\n\n4\n\n1 1 100\n\n2 1 1\n\n3 101 1\n\n4\n\n1 100 1\n\n2 1 1\n\n3 1 101\n\n10\n\n1 1 4\n\n2 3 5\n\n2 5 1\n\n3 4 3\n\n3 1 5\n\n5 3 5\n\n5 2 1\n\n1 3 2\n\n6 2 1"]
|
PASSED
|
import sys, io, os
import time
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def find_prefix_length(b_stack, sum_a_, starting_prefix):
lo = starting_prefix
hi = len(b_stack) - 1
while (hi - lo) > 1:
mid = (lo + hi) // 2
if b_stack[mid] <= sum_a_:
lo = mid
else:
hi = mid - 1
if b_stack[hi] <= sum_a_:
return hi
return lo
def estimate_prefix(tree, n):
global start
b_stack = []
output = [None] * n
started = [False] * n
stack = [(0, 0, 0, 0)]
count = 0
while len(stack) > 0:
node, sum_a, prefix_length, old_b = stack[-1]
if started[node]:
b_stack.pop()
stack.pop()
continue
else:
sum_b = 0
if len(b_stack) > 0:
sum_b = b_stack[-1]
b_stack.append(sum_b + old_b)
started[node] = True
count += 1
output[node] = prefix_length
for child_node, a, b in tree[node]:
sum_a_ = sum_a + a
b_stack.append(b_stack[-1] + b)
prefix_length_ = find_prefix_length(b_stack, sum_a_, prefix_length)
stack += [(child_node, sum_a_, prefix_length_, b)]
b_stack.pop()
return output
for _ in range(int(input())):
start = time.time()
n = int(input())
tree = [[] for _ in range(n)]
for i in range(1, n):
p, a, b = map(int, input().split())
tree[p - 1] += [(i, a, b)]
b_stack = []
output = estimate_prefix(tree, n)
sys.stdout.write(f"{' '.join(map(str, output[1:]))}\n")
|
1659364500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["1\n12\n830455698\n890287984"]
|
19a2550af6a46308fd92c7a352f12a5f
|
Note$$$n=1$$$, there is only one permutation that satisfies the condition: $$$[1,2].$$$In permutation $$$[1,2]$$$, $$$p_1<p_2$$$, and there is one $$$i=1$$$ satisfy the condition. Since $$$1 \geq n$$$, this permutation should be counted. In permutation $$$[2,1]$$$, $$$p_1>p_2$$$. Because $$$0<n$$$, this permutation should not be counted.$$$n=2$$$, there are $$$12$$$ permutations: $$$[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].$$$
|
CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example: Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example: $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$, $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.
|
For each test case, print the answer in a single line.
|
The input consists of multiple test cases. The first line contains an integer $$$t (t \geq 1)$$$ β the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \leq n \leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_089.jsonl
|
a66427931928da61b17f883432f76b8e
|
256 megabytes
|
["4\n1\n2\n9\n91234"]
|
PASSED
|
mod = (10**9)+7
def fact( n ):
f = 1
for i in range( 3 , n+1):
f = (f* i) % mod
return f
for _ in range(int(input())):
a = int(input()) * 2
print( fact(a) )
|
1632996900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2", "1", "-1"]
|
b0ffab0bf169f8278af48fe2d58dcd2d
| null |
Ksusha is a beginner coder. Today she starts studying arrays. She has array a1,βa2,β...,βan, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
|
Print a single integer β the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.
|
The first line contains integer n (1ββ€βnββ€β105), showing how many numbers the array has. The next line contains integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the array elements.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,000 |
train_023.jsonl
|
9c30ff70c458b25dc43f08ed4c190da6
|
256 megabytes
|
["3\n2 2 4", "5\n2 1 3 1 6", "3\n2 3 5"]
|
PASSED
|
def main():
n = int(raw_input())
a = map(int,raw_input().split())
minx = min(a)
print([minx,-1][min(1,sum(map(lambda t:t%minx,a)))])
main()
|
1366644600
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["even", "odd", "odd", "even"]
|
ee105b664099808143a94a374d6d5daa
|
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
|
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
|
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
|
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$)Β β the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i < b$$$)Β β the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_008.jsonl
|
8ff31b782402842031891f689dd9b386
|
256 megabytes
|
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
|
PASSED
|
b, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
n = 0
for i in range(0, k - 1):
n += a[i] * b
if a[k - 1] % 2 != 0:
n += 1
if n % 2 == 0:
print('even')
else:
print('odd')
|
1549546500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "-1"]
|
b0e6a9b500b3b75219309b5e6295e105
|
NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.
|
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1,βa2,β...,βak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another nβ-βk cities, and, of course, flour delivery should be paidΒ β for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (aiββ βb for every 1ββ€βiββ€βk) and choose a storage in some city s (sβ=βaj for some 1ββ€βjββ€βk) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.
|
Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print β-β1 in the only line.
|
The first line of the input contains three integers n, m and k (1ββ€βn,βmββ€β105, 0ββ€βkββ€βn)Β β the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1ββ€βu,βvββ€βn, 1ββ€βlββ€β109, uββ βv) meaning that there is a road between cities u and v of length of l kilometers . If kβ>β0, then the last line of the input contains k distinct integers a1,βa2,β...,βak (1ββ€βaiββ€βn)Β β the number of cities having flour storage located in. If kβ=β0 then this line is not presented in the input.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,300 |
train_002.jsonl
|
5af3ecf810a8c1c34831af4f084e7302
|
256 megabytes
|
["5 4 2\n1 2 5\n1 2 3\n2 3 4\n1 4 10\n1 5", "3 1 1\n1 2 3\n3"]
|
PASSED
|
'''input
3 1 1
1 2 3
3
'''
n, m, k = map(int, raw_input().split())
if k == 0:
print -1
else:
A = [map(int, raw_input().split()) for _ in xrange(m)]
storages = map(int, raw_input().split())
mark = [True] * (n + 1)
for i in storages: mark[i] = False
res = 10000000000
for u, v, l in A:
if mark[u] != mark[v]:
res = min(res, l)
print res if res != 10000000000 else -1
|
1471698300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["8\n4\n1\n1"]
|
f2f9f63a952794f27862eb24ccbdbf36
|
NoteIn the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element ($$$5$$$) because he or she was forced by you to take the last element. After this turn the remaining array will be $$$[2, 9, 2, 3, 8]$$$; the second person will take the first element ($$$2$$$) because he or she was forced by you to take the first element. After this turn the remaining array will be $$$[9, 2, 3, 8]$$$; if the third person will choose to take the first element ($$$9$$$), at your turn the remaining array will be $$$[2, 3, 8]$$$ and you will take $$$8$$$ (the last element); if the third person will choose to take the last element ($$$8$$$), at your turn the remaining array will be $$$[9, 2, 3]$$$ and you will take $$$9$$$ (the first element). Thus, this strategy guarantees to end up with at least $$$8$$$. We can prove that there is no strategy that guarantees to end up with at least $$$9$$$. Hence, the answer is $$$8$$$.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with $$$4$$$.
|
You and your $$$n - 1$$$ friends have found an array of integers $$$a_1, a_2, \dots, a_n$$$. You have decided to share it in the following way: All $$$n$$$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the $$$m$$$-th position in the line. Before the process starts, you may choose up to $$$k$$$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer $$$x$$$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to $$$x$$$?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.
|
For each test case, print the largest integer $$$x$$$ such that you can guarantee to obtain at least $$$x$$$.
|
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) Β β the number of test cases. The description of the test cases follows. The first line of each test case contains three space-separated integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$) Β β the number of elements in the array, your position in line and the number of people whose choices you can fix. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3500$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_004.jsonl
|
e5623983689a3dede5b593e13113b27a
|
256 megabytes
|
["4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2"]
|
PASSED
|
def inp(dtype=str, strip=True):
s = input()
res = [dtype(p) for p in s.split()]
res = res[0] if len(res) == 1 and strip else res
return res
def problemA():
t = int(input())
for _ in range(t):
n = int(input())
s = input()
s = [int(el) for el in s]
res = '-1'
cum = sum(s)
i = 1
while i <= n:
if s[-i] % 2 != 0 and cum % 2 == 0:
res = ''.join([str(s[j]) for j in range(n - i + 1)])
break
cum -= s[-i]
i += 1
print(res)
def problemB():
t = int(input())
for tcase in range(t):
n = int(input())
a = inp(int, strip=False)
next = a[0] + 1 if a[0] <= 0 else 1
i = 1
while i < n and a[i] >= next:
if a[i] < 0:
next = a[i] + 1
elif next <= 0:
next = 1
else:
next += 1
i += 1
if i == n:
print('YES')
continue
ileft = i - 1
gapleft = a[ileft] < next - 1
i = n - 1
next = a[i] + 1 if a[i] <= 0 else 1
i -= 1
while i >= 0 and a[i] >= next:
if a[i] < 0:
next = a[i] + 1
elif next <= 0:
next = 1
else:
next += 1
i -= 1
if i < 0:
print('YES')
continue
iright = i + 1
gapright = a[iright] < next - 1
# print(tcase, ileft, iright)
if ileft + 1 > iright:
print('YES')
elif ileft + 1 == iright:
if a[ileft] != a[iright]:
print('YES')
elif a[ileft] > 0 and (gapleft or gapright):
print('YES')
else:
print('NO')
else:
print('NO')
def problemC():
t = int(input())
for _ in range(t):
n, m, k = inp(int)
k = min(k, m - 1)
a = inp(int, strip=False)
b = [max(a[i], a[i + (n - m)]) for i in range(0, m)]
x = max(min(b[i:i+(m-k)]) for i in range(k+1))
print(x)
if __name__ == '__main__':
# problemA()
# problemB()
problemC()
|
1580652300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2.5 seconds
|
["0", "4"]
|
40a32523f982e24fba2c785fc6a27881
|
NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations: Add $$$1$$$ to the second element, making it equal to $$$9$$$. Subtract $$$1$$$ from the third element, making it equal to $$$6$$$. Add $$$1$$$ to the fifth element, making it equal to $$$2$$$. Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
|
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!
|
Print a single integer Β β the minimum number of operations required to make the array good.
|
The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) Β β the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$) Β β the elements of the array.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,500 |
train_007.jsonl
|
2d1412b4f25a917b6e48da92aac3c952
|
256 megabytes
|
["3\n6 2 4", "5\n9 8 7 3 1"]
|
PASSED
|
import random
n = int(raw_input())
a = list(map(int, raw_input().split()))
limit = min(8, n)
iterations = [x for x in range(n)]
random.shuffle(iterations)
iterations = iterations[:limit]
def factorization(x):
primes = []
i = 2
while i * i <= x:
if x % i == 0:
primes.append(i)
while x % i == 0: x //= i
i = i + 1
if x > 1: primes.append(x)
return primes
def solve_with_fixed_gcd(arr, gcd):
result = 0
for x in arr:
if x < gcd: result += (gcd - x)
else:
remainder = x % gcd
result += min(remainder, gcd - remainder)
return result
answer = float("inf")
prime_list = set()
for index in iterations:
for x in range(-1, 2):
tmp = factorization(a[index]-x)
for z in tmp: prime_list.add(z)
for prime in prime_list:
answer = min(answer, solve_with_fixed_gcd(a, prime))
if answer == 0: break
print(answer)
|
1583246100
|
[
"number theory",
"math",
"probabilities"
] |
[
0,
0,
0,
1,
1,
1,
0,
0
] |
|
2 seconds
|
["4\n0"]
|
332340a793eb3ec14131948e2b6bdf2f
|
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
|
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
|
For each test print one line, containing one integer β the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_008.jsonl
|
a6857ccf57418e193d24e71258e2f192
|
256 megabytes
|
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
|
PASSED
|
from collections import deque
from sys import stdin, stdout
input = stdin.readline
print = stdout.write
anss = []
t = int(input())
for test_count in range(t):
ans = 1
part = 0
factor = 0
queue = deque([])
n, m = map(int, input().split())
if m > (n // 2) * ( n // 2 + 1):
anss.append(0)
for edge_count in range(m):
input()
continue
edge = [[] for i in range(n + 1)]
flag = [-1] * (n + 1)
assure = 1
for edge_count in range(m):
u, v = map(int, input().split())
edge[u].append(v)
edge[v].append(u)
flag[1] = 0
queue.append(1)
break_all = False
while not break_all:
even, odd = 1, 0
while queue and not break_all:
search = queue.popleft()
# print('searching vertex {0}, {1}'.format(search, edge[search]))
current = flag[search]
for to in edge[search]:
if flag[to] == -1:
flag[to] = current ^ 1
if flag[to] & 1:
odd += 1
else:
even += 1
queue.append(to)
elif flag[to] == current:
break_all = True
else:
assert flag[to] == current ^ 1
# print(flag)
if break_all:
# print('break_all')
ans = 0
else:
if (even, odd) == (1, 0):
factor += 1
else:
ans *= pow(2, even, 998244353) + pow(2, odd, 998244353)
ans %= 998244353
while assure <= n:
if flag[assure] == -1:
part += 1
flag[assure] = 2 * part
queue.append(assure)
break
assure += 1
if assure == n + 1:
break
ans *= pow(3, factor, 998244353)
ans %= 998244353
anss.append(ans)
print('\n'.join(map(str, anss)))
# print(time.time() - start)
|
1544884500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES\nBABA", "NO"]
|
d126ef6b94e9ab55624cf7f2a96c7ed1
| null |
Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).
|
If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.
|
The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ β the multiset $$$s$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,500 |
train_022.jsonl
|
ad3a20cc87e13794b47c3fc3058f4a1d
|
256 megabytes
|
["4\n3 5 7 1", "3\n3 5 1"]
|
PASSED
|
raw_input()
s = map(int, raw_input().split())
MAX_SIZE = 101
count = [0] * MAX_SIZE
for num in s:
count[num] += 1
nUnique = 0
a, b = [0] * MAX_SIZE, [0] * MAX_SIZE
turn = 0
for num in xrange(1, MAX_SIZE):
if count[num] == 1:
nUnique += 1
if turn == 0:
a[num] = 1
else:
b[num] = 1
turn ^= 1
for num in xrange(1, MAX_SIZE):
if nUnique & 1 == 1 and count[num] > 2:
nUnique += 1
b[num] = 1
a[num] = count[num] - 1
elif count[num] > 1:
a[num] = count[num]
if nUnique & 1 == 1:
print 'NO'
else:
print 'YES'
ret = ''
for num in s:
if a[num] > 0:
ret += 'A'
a[num] -= 1
else:
ret += 'B'
b[num] -= 1
print ret
|
1537454700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3", "18", "4.5"]
|
b2031a328d72b464f965b4789fd35b93
|
NotePasha also has candies that he is going to give to girls but that is another task...
|
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.
|
Print a single real number β the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10β-β6.
|
The first line of the input contains two integers, n and w (1ββ€βnββ€β105, 1ββ€βwββ€β109)Β β the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1ββ€βaiββ€β109, 1ββ€βiββ€β2n)Β βΒ the capacities of Pasha's tea cups in milliliters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_001.jsonl
|
8f4fb2203d74e4e065844cec1cc6f4ea
|
256 megabytes
|
["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"]
|
PASSED
|
n, w = map(int, input().split())
cups = sorted([int(x) for x in input().split()])
girl = cups[0]
boys = cups[n]
both = min(girl, boys/2)
print(min(n*both + 2*n*both, w))
|
1435676400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n2"]
|
b46244f39e30c0cfab592a97105c60f4
|
NoteIn the first test case, $$$\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$$$.In the second test case, $$$2$$$ is the maximum possible value, corresponding to $$$\mathrm{gcd}(2, 4)$$$.
|
Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\mathrm{gcd}(a, b)$$$, where $$$1 \leq a < b \leq n$$$.The greatest common divisor, $$$\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.
|
For each test case, output the maximum value of $$$\mathrm{gcd}(a, b)$$$ among all $$$1 \leq a < b \leq n$$$.
|
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 only line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^6$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_005.jsonl
|
dc5d966edc948ebb88a4a08ae02bccd1
|
256 megabytes
|
["2\n3\n5"]
|
PASSED
|
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
from collections import *
for _ in range(ii()):
n=ii()
if(n%2==0):
print(n//2)
elif(n<=3):
print(1)
else:
print((n-1)//2)
|
1592663700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["3\n6\n5", "3\n4\n5\n7\n8\n1\n2\n3\n4\n5", "10\n10"]
|
0646a23b550eefea7347cef831d1c69d
|
NoteIn the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
|
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c β Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
|
Output q lines: for each work plan, output one line containing an integer β the largest Koyomity achievable after repainting the garland according to it.
|
The first line of input contains a positive integer n (1ββ€βnββ€β1β500) β the length of the garland. The second line contains n lowercase English letters s1s2... sn as a string β the initial colours of paper pieces on the garland. The third line contains a positive integer q (1ββ€βqββ€β200β000) β the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer mi (1ββ€βmiββ€βn) β the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci β Koyomi's possible favourite colour.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_031.jsonl
|
e78d549bd428f3826ce67361ba449415
|
256 megabytes
|
["6\nkoyomi\n3\n1 o\n4 o\n4 m", "15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b", "10\naaaaaaaaaa\n2\n10 b\n10 z"]
|
PASSED
|
import string
import bisect
import sys
def main():
lines = sys.stdin.readlines()
n = int(lines[0])
s = lines[1]
vals = {}
for c in string.ascii_lowercase:
a = [i for i, ch in enumerate(s) if ch == c]
m = len(a)
b = [0]
for length in range(1, m + 1):
best = n
for i in range(m - length + 1):
j = i + length - 1
best = min(best, (a[j] - j) - (a[i] - i))
b.append(best)
vals[c] = b
q = int(lines[2])
r = []
idx = 3
while q > 0:
q -= 1
query = lines[idx].split()
idx += 1
m = int(query[0])
c = query[1]
i = bisect.bisect_right(vals[c], m)
r.append(str(min(n, i + m - 1)))
print('\n'.join(r))
main()
|
1496837700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["NO", "YES\n4\n3 6 1\n4 6 3\n3 4 7\n4 5 2"]
|
0ef40ec5578a61c93254149c59282ee3
|
NoteThe configuration from the first sample is drawn below, and it is impossible to achieve. The sequence of operations from the second sample is illustrated below.
|
Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any integer number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$. Note that in previous subtask $$$x$$$ was allowed to be any real, here it has to be integer.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-1$$$ on the path from $$$4$$$ to $$$5$$$. You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section.Leave is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.
|
If there aren't any sequences of operations which lead to the given configuration, output "NO". If it exists, output "YES" in the first line. In the second line output $$$m$$$Β β number of operations you are going to apply ($$$0 \le m \le 10^5$$$). Note that you don't have to minimize the number of the operations! In the next $$$m$$$ lines output the operations in the following format: $$$u, v, x$$$ ($$$1 \le u, v \le n$$$, $$$u \not = v$$$, $$$x$$$Β β integer, $$$-10^9 \le x \le 10^9$$$), where $$$u, v$$$Β β leaves, $$$x$$$Β β number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$)Β β the number of nodes in a tree. Each of the next $$$n-1$$$ lines contains three integers $$$u$$$, $$$v$$$, $$$val$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$, $$$0 \le val \le 10\,000$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ with $$$val$$$ written on it. It is guaranteed that these edges form a tree. It is guaranteed that all $$$val$$$ numbers are pairwise different and even.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,500 |
train_003.jsonl
|
0c688992e3f3c663189296850df19f89
|
256 megabytes
|
["5\n1 2 2\n2 3 4\n3 4 10\n3 5 18", "6\n1 2 6\n1 3 8\n1 4 12\n2 5 2\n2 6 4"]
|
PASSED
|
from sys import stdin
class solution():
def dfs(self, x, par, adj_arr):
for adj in adj_arr[x]:
if adj != par:
return self.dfs(adj, x, adj_arr)
return x
def get_two_child(self, x, y, adj_arr):
if len(adj_arr[x]) == 1:
return x + 1, x + 1
child1 = adj_arr[x][0]
child2 = adj_arr[x][1]
if child1 == y:
child1 = child2
child2 = adj_arr[x][2]
if child2 == y:
child2 = adj_arr[x][2]
return self.dfs(child1, x, adj_arr) + 1, self.dfs(child2, x, adj_arr) + 1
def main(self):
n = int(stdin.readline())
a = [[] for _ in range(n)]
edges = []
for i in range(n - 1):
x, y, w = [int(val) for val in stdin.readline().split(" ")]
x -= 1
y -= 1
a[x].append(y)
a[y].append(x)
edges.append((x, y, w))
for val in a:
if len(val) == 2:
print "NO"
return
print "YES"
result = []
for x, y, w in edges:
if w == 0:
continue
l1, l2 = self.get_two_child(x, y, a)
r1, r2 = self.get_two_child(y, x, a)
result.append((l1, r1, w / 2))
result.append((l2, r2, w / 2))
if l1 != l2:
result.append((l1, l2, -(w / 2)))
if r1 != r2:
result.append((r1, r2, -(w / 2)))
print len(result)
for x in result:
print " ".join([str(y) for y in x])
x = solution()
x.main()
|
1562339100
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["Yes\n1 4", "No", "Yes\n2 7 7"]
|
55bd1849ef13b52788a0b5685c4fcdac
| null |
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
|
If it is not possible to select k numbers in the desired way, output Β«NoΒ» (without the quotes). Otherwise, in the first line of output print Β«YesΒ» (without the quotes). In the second line print k integers b1,βb2,β...,βbkΒ β the selected numbers. If there are multiple possible solutions, print any of them.
|
First line contains three integers n, k and m (2ββ€βkββ€βnββ€β100β000, 1ββ€βmββ€β100β000)Β β number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β109)Β β the numbers in the multiset.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_012.jsonl
|
b2db76c83a87a51fb05376832ef508bd
|
512 megabytes
|
["3 2 3\n1 8 4", "3 3 3\n1 8 4", "4 3 5\n2 7 7 7"]
|
PASSED
|
n,k,m = map(int,input().split())
arr = list(map(int,input().split()))
ans = {}
for i in arr:
if i%m not in ans:
ans[i%m] = [i]
else:
ans[i%m].append(i)
check = False
for i in ans:
if len(ans[i]) >= k:
check = True
break
if check:
print('Yes')
j = 0
while j<=k-1:
print(ans[i][j],end = ' ')
j+=1
else:
print('No')
|
1508151900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["6"]
|
db1c28e9ac6251353fbad8730f4705ea
| null |
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer β the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
|
Print a single integer β the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
|
The first line contains integer n (2ββ€βnββ€β105), showing the number of vertices in the tree. The next line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow nβ-β1 lines, describing the tree edges. Each line contains a pair of integers xi,βyi (1ββ€βxi,βyiββ€βn,βxiββ βyi) β the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,100 |
train_038.jsonl
|
45da84cab5cefd8816c9b1be2ee2db11
|
256 megabytes
|
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
|
PASSED
|
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a // gcd(a, b) * b
def cal((f1, k1), (f2, k2)):
if f1 > f2:
f1, k1, f2, k2 = f2, k2, f1, k1
A = (f1 - f2) % k2
B = 0
x1 = 0
k11 = k1 % k2
k1x1 = 0
while B != A and k1x1 <= f1:
if B < A:
dx1 = (A - B) // k11
else:
dx1 = (A + k2 - B) // k11
dx1 = max(dx1, 1)
B = (B + k11 * dx1) % k2
x1 += dx1
k1x1 += k1 * dx1
f = f1 - k1x1
if f <= 0:
return (0, 1)
k = lcm(k1, k2)
return (f, k)
def cals(fks):
fk0 = None
for fk in fks:
if fk0 is None:
fk0 = fk
else:
# print fk, fk0
fk0 = cal(fk0, fk)
if fk0[0] == 0:
return fk0
return fk0
def solve():
n = int(raw_input())
a = map(int, raw_input().split())
chs = [[] for i in xrange(n)]
for i in xrange(n-1):
u, v = map(int, raw_input().split())
u, v = u - 1, v - 1
chs[u].append(v)
chs[v].append(u)
p = []
stk = [0]
vis = {0}
chs1 = [[] for i in xrange(n)]
while stk:
u = stk.pop()
p.append(u)
for v in chs[u]:
if not v in vis:
stk.append(v)
chs1[u].append(v)
vis.add(v)
chs = chs1
p.reverse()
ws = [0] * n
for u in p:
ws[u] = a[u] + sum(ws[v] for v in chs[u])
fks = [None] * n
for u in p:
if not chs[u]:
fks[u] = (a[u], 1)
else:
f, k = cals(fks[v] for v in chs[u])
nc = len(chs[u])
fks[u] = (a[u] + f * nc, k * nc)
# print chs
# print zip(a, fks)
return ws[0] - fks[0][0]
print solve()
|
1380295800
|
[
"number theory",
"trees"
] |
[
0,
0,
0,
0,
1,
0,
0,
1
] |
|
2 seconds
|
["3 1\n3 10\n3 15\n3 20\n3 25\n3 30\n1 1378716"]
|
abcafb310d4dcf3f7e34fc4eda1ee324
|
NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.
|
Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following: For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.
|
For each test case, output one line containing two integers β the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) β the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_089.jsonl
|
a0ce67748ddec0dbe81633a8141dd685
|
256 megabytes
|
["7\n3 9\n0 1 2 0 0 2 1 1 0\n0 1 1 1 2 0 0 2 0\n0 1 2 0 0 1 2 1 0\n3 7\n25 15 20 15 25 20 20\n26 14 20 14 26 20 20\n25 15 20 15 20 20 25\n3 9\n25 15 20 15 25 20 20 20 20\n26 14 20 14 26 20 20 20 20\n25 15 20 15 25 15 20 20 25\n3 11\n25 15 20 15 25 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20\n25 15 20 15 25 20 15 20 20 20 25\n3 13\n25 15 20 15 25 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 15 20 20 20 20 25\n3 15\n25 15 20 15 25 20 20 20 20 20 20 20 20 20 20\n26 14 20 14 26 20 20 20 20 20 20 20 20 20 20\n25 15 20 15 25 20 20 20 15 20 20 20 20 20 25\n3 9\n909459 479492 676924 224197 162866 164495 193268 742456 728277\n948845 455424 731850 327890 304150 237351 251763 225845 798316\n975446 401170 792914 272263 300770 242037 236619 334316 725899"]
|
PASSED
|
from collections import Counter, deque, defaultdict
import math
from itertools import permutations, accumulate
from sys import *
from heapq import *
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from random import randint
xor = randint(10 ** 7, 10**8)
# https://docs.python.org/3/library/bisect.html
on = lambda mask, pos: (mask & (1 << pos)) > 0
lcm = lambda x, y: (x * y) // math.gcd(x,y)
rotate = lambda seq, k: seq[k:] + seq[:k]
input = stdin.readline
'''
Check for typos before submit, Check if u can get hacked with Dict (use xor)
Observations/Notes:
O(n)
'''
for _ in range(int(input())):
n, m = map(int, input().split())
arrs = [list(map(int, input().split())) for i in range(n)]
ans = [sum(v * (i + 1) for i, v in enumerate(arrs[i])) for i in range(n)]
print(ans.index(max(ans)) + 1, max(ans) - min(ans))
|
1659276300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES", "NO"]
|
a37c3f2828490c70301b5b5deeee0f88
|
NoteIn first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.In second example there are no love triangles.
|
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1ββ€βfiββ€βn and fiββ βi.We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.
|
Output Β«YESΒ» if there is a love triangle consisting of planes on Earth. Otherwise, output Β«NOΒ». You can output any letter in lower case or in upper case.
|
The first line contains a single integer n (2ββ€βnββ€β5000)Β β the number of planes. The second line contains n integers f1,βf2,β...,βfn (1ββ€βfiββ€βn, fiββ βi), meaning that the i-th plane likes the fi-th.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800 |
train_002.jsonl
|
43b71c4367751f48edcac07b986827ce
|
256 megabytes
|
["5\n2 4 5 1 3", "5\n5 5 5 5 1"]
|
PASSED
|
from sys import stdin, stdout
ti = lambda : stdin.readline().strip()
ma = lambda fxn, ti : map(fxn, ti.split())
ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n')
os = lambda i : stdout.write(str(i) + '\n')
olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n')
n = int(ti())
f = ma(int, ti())
d = {}
for i in range(n):
d[i+1] = f[i]
for a in d.iterkeys():
b = d[a]
c = d[b]
if c == a:
continue
else:
adash = d[c]
if adash == a:
os("YES")
exit()
os("NO")
|
1518861900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1869", "18690"]
|
3b10e984d7ca6d4071fd4e743394bb60
| null |
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
|
Print a number in the decimal notation without leading zeroes β the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
|
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_020.jsonl
|
72774130eeb0da55aae9b2085f94e21e
|
256 megabytes
|
["1689", "18906"]
|
PASSED
|
import itertools
import StringIO
def tonum(a):
return int("".join(map(str, a)))
def genDict():
nums = map(tonum, itertools.permutations([1,6,8,9]))
d = {}
for n in nums: d[n%7] = str(n)
return d
def solve(a, b, mod):
if b == 0:
return 0
for i in xrange(mod):
if (a*i-b)%mod == 0:
return i
s = raw_input().strip()
a = [s.count(chr(i + 48)) for i in xrange(10)]
a[1] -= 1
a[6] -= 1
a[8] -= 1
a[9] -= 1
t, r = 1, 0
for i in xrange(10):
for j in xrange(a[i]):
r += i*t
t = t*10%7
r = 7 - r
k = solve(t, r, 7)
d = genDict()
output = StringIO.StringIO()
output.write(d[k])
for i in xrange(9, -1, -1):
output.write(chr(i+48)*a[i])
print output.getvalue()
|
1387893600
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["12", "-1", "4"]
|
4b4c7e7d9d5c45c8635b403bae997891
|
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
|
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
|
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
|
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_007.jsonl
|
ab6f9af8a3b4e2fb47926d1b510582d7
|
256 megabytes
|
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
|
PASSED
|
n, m = [int(i) for i in input().split()]
mins = [int(i) for i in input().split()]
maxs = [int(i) for i in input().split()]
temp = mins[:]
temp.sort()
pivot = temp[-1]
pivot2 = temp[-2]
ans = sum(mins)*m
ans += sum(maxs)
ans -= pivot*(m-1) + pivot2
bad = False
# for a in maxs:
# if a < pivot:
# bad = True
q = min(maxs)
if q < pivot:
print(-1)
elif q == pivot:
print(ans +pivot2 - pivot)
else:
print(ans)
|
1557671700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["b", "Az", "tFrg4", "AB"]
|
bb6e2f728e1c7e24d86c9352740dea38
|
NoteIn the first example during the first operation both letters 'a' are removed, so the string becomes "bc". During the second operation the letter 'c' (on the second position) is removed, and the string becomes "b".In the second example during the first operation Petya removes '0' from the second position. After that the string becomes "Az". During the second operations the string doesn't change.
|
Petya has a string of length n consisting of small and large English letters and digits.He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string remains the same or decreases after each operation.Find how the string will look like after Petya performs all m operations.
|
Print the string Petya will obtain after performing all m operations. If the strings becomes empty after all operations, print an empty line.
|
The first string contains two integers n and m (1ββ€βn,βmββ€β2Β·105) β the length of the string and the number of operations. The second line contains the string of length n, consisting of small and large English letters and digits. Positions in the string are enumerated from 1. Each of the next m lines contains two integers l and r (1ββ€βlββ€βr), followed by a character c, which is a small or large English letter or a digit. This line describes one operation. It is guaranteed that r doesn't exceed the length of the string s before current operation.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_036.jsonl
|
ed8497e60d221c421f3dbee1f5052a0b
|
256 megabytes
|
["4 2\nabac\n1 3 a\n2 2 c", "3 2\nA0z\n1 3 0\n1 1 z", "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a", "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A"]
|
PASSED
|
from collections import defaultdict
import sys
input = raw_input
range = xrange
def lower_bound(A, x):
a = 0
b = len(A)
while a < b:
c = (a + b) >> 1
if A[c] < x:
a = c + 1
else:
b = c
return a
def upper_bound(A, x):
a = 0
b = len(A)
while a < b:
c = (a + b) >> 1
if A[c] <= x:
a = c + 1
else:
b = c
return a
class FenwickTree:
def __init__(self, x):
self.bit = []
self.build(x)
def build(self, x):
"""transform x into a BIT"""
self.bit[:] = x
bit = self.bit
size = self.size = len(x)
for i in range(size):
j = i | (i + 1)
if j < size:
bit[j] += bit[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
while idx < self.size:
self.bit[idx] += x
idx |= idx + 1
def __call__(self, end):
"""calc sum(bit[:end])"""
x = 0
while end:
x += self.bit[end - 1]
end &= end - 1
return x
def find_kth(self, k):
"""Find largest idx such that sum(bit[:idx]) <= k"""
idx = -1
for d in reversed(range(self.size.bit_length())):
right_idx = idx + (1 << d)
if right_idx < self.size and self.bit[right_idx] <= k:
idx = right_idx
k -= self.bit[idx]
return idx + 1, k
block_size = 700
class blocksorter:
def __init__(self):
self.macro = []
self.micros = [[]]
self.micro_size = [0]
self.fenwick = FenwickTree([])
self.size = 0
# Cache last prev_count(i) call
self.cached_i = 0
self.cached_size = 0
# Cache _lower_bound(x)
self.cached_x = None
self.cached_index = (-1,0)
def lower_bound(self, x):
i,j = self._lower_bound(x)
return self.prev_count(i) + j
def upper_bound(self, x):
i = upper_bound(self.macro, x)
i -= i and self.micro_size[i - 1] and x < self.micros[i - 1][-1]
return self.prev_count(i) + upper_bound(self.micros[i], x)
def insert(self, x):
i,j = self._lower_bound(x)
self.micros[i].insert(j, x)
self.size += 1
self.micro_size[i] += 1
self.fenwick.update(i, 1)
self.cached_size += i < self.cached_i
if len(self.micros[i]) >= block_size:
self.cached_index = (-1, 0)
self.cached_i += i < self.cached_i
self.micros[i : i + 1] = self.micros[i][:block_size >> 1], self.micros[i][block_size >> 1:]
self.micro_size[i : i + 1] = block_size >> 1, block_size >> 1
self.fenwick.size = 0
self.macro [i : i + 1] = self.micros[i][0], self.micros[i + 1][0]
if len(self.micros) == len(self.macro):
self.macro.pop()
def remove(self, x):
i,j = self._lower_bound(x)
self._delete(i,j)
def __delitem__(self, k):
i,j = self.find_kth(k)
self._delete(i,j)
def __getitem__(self, k):
i,j = self.find_kth(k)
return self.micros[i][j]
def __len__(self):
return self.size
def __contains__(self, x):
i,j = self._lower_bound(x)
return j < len(self.micros[i]) and self.micros[i][j] == x
# Internal functions
def find_kth(self, k):
if k < 0:
k += self.size
if k < self.cached_size:
self.cached_i -= 1
self.cached_size -= self.micro_size[self.cached_i]
elif self.cached_size + self.micro_size[self.cached_i] <= k:
self.cached_size += self.micro_size[self.cached_i]
self.cached_i += 1
if k < self.cached_size or self.cached_size + self.micro_size[self.cached_i] <= k:
if self.fenwick.size == 0:
self.fenwick.build(self.micro_size)
self.cached_i,j = self.fenwick.find_kth(k)
if j < self.micro_size[self.cached_i]:
self.cached_size = k - j
else:
self.cached_i -= 1
self.cached_size = k - self.micro_size[i - 1] - 1
return self.cached_i, k - self.cached_size
def prev_count(self, i):
if i == self.cached_i:
return self.cached_size
if i < 10:
self.cached_size = 0
for j in range(i):
self.cached_size += self.micro_size[j]
elif len(self.micro_size) - i < 10:
self.cached_size = self.size
for j in range(i, len(self.micros)):
self.cached_size -= self.micro_size[j]
elif -10 < self.cached_i - i < 10:
for j in range(i, self.cached_i):
self.cached_size -= self.micro_size[j]
for j in range(self.cached_i, i):
self.cached_size += self.micro_size[j]
else:
if self.fenwick.size == 0:
self.fenwick.build(self.micro_size)
self.cached_size = self.fenwick(i)
self.cached_i = i
return self.cached_size
def _lower_bound(self, x):
if self.cached_index[0] >= 0 and self.cached_x == x:
return self.cached_index
i = lower_bound(self.macro, x)
i -= i and self.micro_size[i - 1] and x <= self.micros[i - 1][-1]
j = lower_bound(self.micros[i], x)
self.cached_x = x
self.cached_index = (i,j)
return i, j
def _delete(self, i, j):
del self.micros[i][j]
self.size -= 1
self.micro_size[i] -= 1
self.fenwick.update(i, -1)
if i == self.cached_index[0] and j < self.cached_index[1]:
self.cached_index = (i, self.cached_index[1] - 1)
self.cached_size -= i < self.cached_i
if 1 < i + 1 < len(self.micro_size) and self.micro_size[i - 1] + self.micro_size[i] + self.micro_size[i + 1] < block_size:
self.cached_index = (-1, 0)
if self.cached_i == i:
self.cached_size -= self.micro_size[i - 1]
elif self.cached_i == i + 1:
self.cached_size -= self.micro_size[i - 1] + self.micro_size[i]
self.cached_i -= (i <= self.cached_i) + (i < self.cached_i)
self.micros[i - 1] += self.micros[i]
self.micros[i - 1] += self.micros[i + 1]
self.micro_size[i - 1] += self.micro_size[i] + self.micro_size[i + 1]
del self.macro[i - 1: i + 1], self.micros[i: i + 2], self.micro_size[i: i + 2]
self.fenwick.size = 0
inp = sys.stdin.read().split(); ii = 0
n = int(inp[ii]); ii += 1
m = int(inp[ii]); ii += 1
S = inp[ii]; ii += 1
B = blocksorter()
Bc = defaultdict(lambda : blocksorter())
for i in range(n):
B.insert(i)
Bc[S[i]].insert(i)
for _ in range(m):
l = int(inp[ii]) - 1; ii += 1
r = int(inp[ii]) - 1; ii += 1
c = inp[ii]; ii += 1
Bcc = Bc[c]
L = B[l]
R = B[r]
k = Bcc.lower_bound(L)
while k < len(Bcc) and Bcc[k] <= R:
B.remove(Bcc[k])
del Bcc[k]
print ''.join(S[i] for b in B.micros for i in b)
|
1513492500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["4", "0", "-8"]
|
c7cca8c6524991da6ea1b423a8182d24
|
NoteIn the first example: d(a1,βa2)β=β0; d(a1,βa3)β=β2; d(a1,βa4)β=β0; d(a1,βa5)β=β2; d(a2,βa3)β=β0; d(a2,βa4)β=β0; d(a2,βa5)β=β0; d(a3,βa4)β=ββ-β2; d(a3,βa5)β=β0; d(a4,βa5)β=β2.
|
Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai,βaj) over all pairs (i,βj) such that 1ββ€βiββ€βjββ€βn.
|
Print one integer β the sum of d(ai,βaj) over all pairs (i,βj) such that 1ββ€βiββ€βjββ€βn.
|
The first line contains one integer n (1ββ€βnββ€β200000) β the number of elements in a. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β109) β elements of the array.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_005.jsonl
|
c7b34015d82e882cfc2613b163a5f8b7
|
256 megabytes
|
["5\n1 2 3 1 3", "4\n6 6 5 5", "4\n6 6 4 4"]
|
PASSED
|
n = int(input())
a = list(map(int,input().split()))
s = 0
mx = a[0]
dic = dict()
for i in range(n):
dic[a[i]] = 0
for i in range(n):
s = s - a[i]*(n-i-1) + a[i]*i
if a[i]-1 in dic:
s = s + dic[a[i]-1]*(a[i] - 1 - a[i])
if a[i]+1 in dic:
s = s + dic[a[i]+1]*(a[i] + 1 - a[i])
d = dic[a[i]]+1
t = {a[i]:d}
dic.update(t)
print(s)
|
1513091100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1.532000000000\n1.860000000000\n5.005050776521\n4.260163673896"]
|
738939f55bcc636c0340838818381d2f
|
NoteFor the first test case, the possible drawing sequences are: P with a probability of $$$0.6$$$; CP with a probability of $$$0.2\cdot 0.7 = 0.14$$$; CMP with a probability of $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; CMMP with a probability of $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$; MP with a probability of $$$0.2\cdot 0.7 = 0.14$$$; MCP with a probability of $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; MCCP with a probability of $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$. So, the expected number of races is equal to $$$1\cdot 0.6 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 = 1.532$$$.For the second test case, the possible drawing sequences are: P with a probability of $$$0.4$$$; CP with a probability of $$$0.4\cdot 0.6 = 0.24$$$; CMP with a probability of $$$0.4\cdot 0.4\cdot 1 = 0.16$$$; MP with a probability of $$$0.2\cdot 0.5 = 0.1$$$; MCP with a probability of $$$0.2\cdot 0.5\cdot 1 = 0.1$$$. So, the expected number of races is equal to $$$1\cdot 0.4 + 2\cdot 0.24 + 3\cdot 0.16 + 2\cdot 0.1 + 3\cdot 0.1 = 1.86$$$.
|
After defeating a Blacklist Rival, you get a chance to draw $$$1$$$ reward slip out of $$$x$$$ hidden valid slips. Initially, $$$x=3$$$ and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are $$$c$$$, $$$m$$$, and $$$p$$$, respectively. There is also a volatility factor $$$v$$$. You can play any number of Rival Races as long as you don't draw a Pink Slip. Assume that you win each race and get a chance to draw a reward slip. In each draw, you draw one of the $$$x$$$ valid items with their respective probabilities. Suppose you draw a particular item and its probability of drawing before the draw was $$$a$$$. Then, If the item was a Pink Slip, the quest is over, and you will not play any more races. Otherwise, If $$$a\leq v$$$, the probability of the item drawn becomes $$$0$$$ and the item is no longer a valid item for all the further draws, reducing $$$x$$$ by $$$1$$$. Moreover, the reduced probability $$$a$$$ is distributed equally among the other remaining valid items. If $$$a > v$$$, the probability of the item drawn reduces by $$$v$$$ and the reduced probability is distributed equally among the other valid items. For example, If $$$(c,m,p)=(0.2,0.1,0.7)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,0.15,0.75)$$$. If $$$(c,m,p)=(0.1,0.2,0.7)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,0.25,0.75)$$$. If $$$(c,m,p)=(0.2,Invalid,0.8)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,Invalid,0.9)$$$. If $$$(c,m,p)=(0.1,Invalid,0.9)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,Invalid,1.0)$$$. You need the cars of Rivals. So, you need to find the expected number of races that you must play in order to draw a pink slip.
|
For each test case, output a single line containing a single real numberΒ β the expected number of races that you must play in order to draw a Pink Slip. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10$$$) Β β the number of test cases. The first and the only line of each test case contains four real numbers $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ ($$$0 < c,m,p < 1$$$, $$$c+m+p=1$$$, $$$0.1\leq v\leq 0.9$$$). Additionally, it is guaranteed that each of $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ have at most $$$4$$$ decimal places.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_091.jsonl
|
3903a36a38cfb3339b7c5038928ef924
|
256 megabytes
|
["4\n0.2 0.2 0.6 0.2\n0.4 0.2 0.4 0.8\n0.4998 0.4998 0.0004 0.1666\n0.3125 0.6561 0.0314 0.2048"]
|
PASSED
|
from decimal import Decimal
import datetime
from functools import cache
class Solution:
@cache
def compute_ev(self, c, m, p, v) -> int:
ans = 1
#only compute probability from c if c > 0...else no need to compute
if c > 0:
if c > v:
red_c = v
else:
red_c = c
if m != 0 and p != 0:
new_c, new_m, new_p = max(0, c - v), m + red_c / 2, p + red_c / 2
elif m != 0:
new_c, new_m, new_p = max(0, c - v), m + red_c, p
elif p != 0:
new_c, new_m, new_p = max(0, c - v), m, p + red_c
ans += c * self.compute_ev(new_c, new_m, new_p, v)
#mirror case below to the above
if m > 0:
if m > v:
red_m = v
else:
red_m = m
if c != 0 and p != 0:
new_c, new_m, new_p = c + red_m / 2, max(0, m - v), p + red_m / 2
elif c != 0:
new_c, new_m, new_p = c + red_m, max(0, m - v), p
elif p != 0:
new_c, new_m, new_p = c, max(0, m - v), p + red_m
ans += m * self.compute_ev(new_c, new_m, new_p, v)
return ans
# t1 = datetime.datetime.now()
solution_obj = Solution()
for case in range(int(input())):
c, m, p, v = [Decimal(x) for x in input().split()]
print(solution_obj.compute_ev(c, m, p, v))
# t2 = datetime.datetime.now()
# print(t2 - t1)
|
1625668500
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second
|
["2\n3\n-1"]
|
f5bcde6e3008405f61cead4e3f44806e
|
NoteIn the first test case, the subarray $$$[2,3]$$$ has sum of elements $$$5$$$, which isn't divisible by $$$3$$$.In the second test case, the sum of elements of the whole array is $$$6$$$, which isn't divisible by $$$4$$$.In the third test case, all subarrays have an even sum, so the answer is $$$-1$$$.
|
Ehab loves number theory, but for some reason he hates the number $$$x$$$. Given an array $$$a$$$, find the length of its longest subarray such that the sum of its elements isn't divisible by $$$x$$$, or determine that such subarray doesn't exist.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
For each testcase, print the length of the longest subarray whose sum isn't divisible by $$$x$$$. If there's no such subarray, print $$$-1$$$.
|
The first line contains an integer $$$t$$$ $$$(1 \le t \le 5)$$$Β β the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^4$$$)Β β the number of elements in the array $$$a$$$ and the number that Ehab hates. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 10^4$$$)Β β the elements of the array $$$a$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,200 |
train_002.jsonl
|
40d387ca3ba9c90847af71ccfdf27a0c
|
256 megabytes
|
["3\n3 3\n1 2 3\n3 4\n1 2 3\n2 2\n0 6"]
|
PASSED
|
ncases = int(input())
for i in range(ncases):
line1 = input().split(' ')
line2 = input().split(' ')
hate = int(line1[1])
arr = []
count = 0
for ele in line2:
ele = int(ele)
if (ele%hate == 0):
count += 1
arr.append(ele)
if (count == len(arr)):
print(-1)
elif (sum(arr)% hate != 0):
print (len(arr))
else:
s = []
for j in range(len(arr)):
find = arr[j]
if (find%hate!= 0):
s.append(j)
break
for k in range(-1,-(len(arr)+1),-1):
find = arr[k]
if (find%hate != 0):
s.append(k)
break
arr1 = arr[s[0]+1:]
arr2 = arr[0:s[1]]
print (max(len(arr1),len(arr2)))
|
1592060700
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["010", "010", "0000000", "0011001100001011101000"]
|
a3c844e3ee6c9596f1ec9ab46c6ea872
|
NoteIn the first example: For the substrings of the length $$$1$$$ the length of the longest non-decreasing subsequnce is $$$1$$$; For $$$l = 1, r = 2$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{2}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{2}$$$ is $$$01$$$; For $$$l = 1, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{3}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{3}$$$ is $$$00$$$; For $$$l = 2, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{2}s_{3}$$$ is $$$1$$$ and the longest non-decreasing subsequnce of the substring $$$t_{2}t_{3}$$$ is $$$1$$$; The second example is similar to the first one.
|
The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.Kirk has a binary string $$$s$$$ (a string which consists of zeroes and ones) of length $$$n$$$ and he is asking you to find a binary string $$$t$$$ of the same length which satisfies the following conditions: For any $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) the length of the longest non-decreasing subsequence of the substring $$$s_{l}s_{l+1} \ldots s_{r}$$$ is equal to the length of the longest non-decreasing subsequence of the substring $$$t_{l}t_{l+1} \ldots t_{r}$$$; The number of zeroes in $$$t$$$ is the maximum possible.A non-decreasing subsequence of a string $$$p$$$ is a sequence of indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$i_1 < i_2 < \ldots < i_k$$$ and $$$p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$$$. The length of the subsequence is $$$k$$$.If there are multiple substrings which satisfy the conditions, output any.
|
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
|
The first line contains a binary string of length not more than $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_006.jsonl
|
1f4190a2a2f7dd0fd8eb8a41ba3d4591
|
256 megabytes
|
["110", "010", "0001111", "0111001100111011101000"]
|
PASSED
|
data = [int(i) for i in input()]
n = len(data)
minval = [0]* n
minval[-1] = 2 * data[-1] - 1
for i in range(n-2, -1, -1):
if data[i] == 1:
minval[i] = min(1, minval[i+1] + 1)
else:
minval[i] = min(-1, minval[i+1] - 1)
ans = [i for i in data]
for i in range(n-1, -1, -1):
if minval[i] == 1:
ans[i] = 0
ans2 = [str(i) for i in ans]
print("".join(ans2))
# print(minval)
|
1566311700
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
d6e44bd8ac03876cb03be0731f7dda3d
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
Output a single numberΒ β the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$)Β β the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$)Β β the initial powers of the superheroes in the cast of avengers.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_009.jsonl
|
327bb837a7e263317bafe00dda4c2e95
|
256 megabytes
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
PASSED
|
n,k,m = input().split()
k = int(k)
m = int(m)
n = int(n)
niz = [int(n) for n in input().split()]
niz.sort()
suma = sum(niz)
curMax = (suma+min(m,n*k)) / n
for i in range(1,min(n-1,m)+1):
suma -= niz[i-1]
tempMax = (suma + min(m-i, (n-i)*k)) /(n-i)
if tempMax > curMax:
curMax = tempMax
print(curMax)
|
1549208100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["6\n4\n1\n3\n10"]
|
091e91352973b18040e2d57c46f2bf8a
| null |
You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$.
|
For each query print one integer: the answer to this query.
|
The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,000 |
train_007.jsonl
|
c0bc48891737715506189442883b5e64
|
256 megabytes
|
["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"]
|
PASSED
|
q = int(input())
for q in range(0, q):
k = [int(a) for a in input().split()]
l = k[0]
r = k[1]
d = k[2]
if d < l or d > r:
x = d
else:
x = r - (r % d) + d
print(x)
|
1547217300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["0 25 60 40 20", "0 13 26 39 26 13"]
|
9fc5a320b5b33deced64d7c571b313d5
|
NoteThe minimum possible sum of times required to pass each road in the first example is $$$85$$$ β exactly one of the roads with passing time $$$25$$$ must be abandoned. Note that after one of these roads is abandoned, it's now impossible to travel between settlements $$$1$$$ and $$$3$$$ in time $$$50$$$.
|
Codefortia is a small island country located somewhere in the West Pacific. It consists of $$$n$$$ settlements connected by $$$m$$$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to $$$a$$$ or $$$b$$$ seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that: it will be possible to travel between each pair of cities using the remaining roads only, the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight), among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement $$$1$$$) and the parliament house (in settlement $$$p$$$) using the remaining roads only will be minimum possible. The king, however, forgot where the parliament house was. For each settlement $$$p = 1, 2, \dots, n$$$, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement $$$p$$$) after some roads are abandoned?
|
Output a single line containing $$$n$$$ integers. The $$$p$$$-th of them should denote the minimum possible time required to travel from $$$1$$$ to $$$p$$$ after the selected roads are abandoned. Note that for each $$$p$$$ you can abandon a different set of roads.
|
The first line of the input contains four integers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 70$$$, $$$n - 1 \leq m \leq 200$$$, $$$1 \leq a < b \leq 10^7$$$) β the number of settlements and gravel roads in Codefortia, and two possible travel times. Each of the following lines contains three integers $$$u, v, c$$$ ($$$1 \leq u, v \leq n$$$, $$$u \neq v$$$, $$$c \in \{a, b\}$$$) denoting a single gravel road between the settlements $$$u$$$ and $$$v$$$, which requires $$$c$$$ minutes to travel. You can assume that the road network is connected and has no loops or multiedges.
|
standard output
|
standard input
|
Python 2
|
Python
| 3,000 |
train_067.jsonl
|
9fe53e729061e672fd941ae8d7f0fbf9
|
512 megabytes
|
["5 5 20 25\n1 2 25\n2 3 25\n3 4 20\n4 5 20\n5 1 20", "6 7 13 22\n1 2 13\n2 3 13\n1 4 22\n3 4 13\n4 5 13\n5 6 13\n6 1 13"]
|
PASSED
|
import heapq
n,m,a,b=map(int,raw_input().split())
graph={i:[] for i in range(n)}
for i in range(m):
u,v,w=map(int,raw_input().split())
graph[u-1].append((v-1,w))
graph[v-1].append((u-1,w))
components=[-1]*n
comp=-1
for i in range(n):
if components[i]==-1:
comp+=1
components[i]=comp
prev=[]
layer=[i]
while layer!=[]:
newlayer=[]
for guy in layer:
for guy1 in graph[guy]:
if guy1[1]==a and components[guy1[0]]==-1:
newlayer.append(guy1[0])
components[guy1[0]]=comp
prev=layer[:]
layer=newlayer[:]
useless=[]
for guy in graph:
for neigh in graph[guy]:
if components[guy]==components[neigh[0]] and neigh[1]==b:
useless.append((guy,neigh))
for guy in useless:
graph[guy[0]].remove(guy[1])
counts=[0]*(comp+1)
for i in range(n):
counts[components[i]]+=1
bad=[]
for i in range(comp+1):
if counts[i]<=3:
bad.append(i)
for j in range(n):
if components[j]==i:
components[j]=-1
for guy in bad[::-1]:
for i in range(n):
if components[i]>guy:
components[i]-=1
comp-=len(bad)
comp+=1
dists=[[float("inf") for i in range(2**comp)] for j in range(n)]
dists[0][0]=0
pq=[]
heapq.heappush(pq,[0,0,0])
remaining=n
visited=[0]*n
while len(pq)>0 and remaining>0:
dist,vert,mask=heapq.heappop(pq)
if visited[vert]==0:
visited[vert]=1
remaining-=1
for neigh in graph[vert]:
if neigh[1]==b:
if components[vert]==components[neigh[0]] and components[vert]!=-1:
continue
if components[neigh[0]]!=-1:
if mask & (2**components[neigh[0]])>0:
continue
if components[vert]!=-1:
maskn=mask+2**(components[vert])
else:
maskn=mask
else:
maskn=mask
if dist+neigh[1]<dists[neigh[0]][maskn]:
dists[neigh[0]][maskn]=dist+neigh[1]
heapq.heappush(pq,[dist+neigh[1],neigh[0],maskn])
optimal=[str(min(dists[i])) for i in range(n)]
print(" ".join(optimal))
|
1556548500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["bncdenqbdr", "aaacaba"]
|
e70708f72da9a203b21fc4112ede9268
|
NoteString s is lexicographically smaller than some other string t of the same length if there exists some 1ββ€βiββ€β|s|, such that s1β=βt1,βs2β=βt2,β...,βsiβ-β1β=βtiβ-β1, and siβ<βti.
|
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?
|
Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.
|
The only line of the input contains the string s (1ββ€β|s|ββ€β100β000) consisting of lowercase English letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_000.jsonl
|
91e764601631797e938f9b7ba6be3675
|
256 megabytes
|
["codeforces", "abacaba"]
|
PASSED
|
a,s,iz='',input(),0
if set(s)=={'a'}:a+=s[:-1]+'z'
elif len(set(s))==1:a+=(chr(ord(s[0])-1))*len(s)
while len(a)!=len(s):
if s[len(a)]!='a':
a,iz=a+chr(ord(s[len(a)])-1),iz+1
elif s[len(a)]=='a' and iz<1:a+=s[len(a)]
else:a+=s[len(a):]
print(a)
|
1472056500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["10", "52", "131"]
|
c44554273f9c53d11aa1b0edeb121113
|
NoteA bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.In the first sample the available paths are: city 1 to itself with a distance of 1, city 2 to itself with a distance of 2, city 3 to itself with a distance of 3, city 1 to city 2 with a distance of , city 1 to city 3 with a distance of , city 2 to city 3 with a distance of . The total distance between all pairs of cities equals 1β+β2β+β3β+β3β+β0β+β1β=β10.
|
Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by nβ-β1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where is bitwise xor operation.Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.
|
Output one number denoting the total distance between all pairs of cities.
|
The first line contains integer n (1ββ€βnββ€β105) β the number of cities in Mahmoud and Ehab's country. Then the second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106) which represent the numbers attached to the cities. Integer ai is attached to the city i. Each of the next nββ-ββ1 lines contains two integers u and v (1βββ€ββu,ββvβββ€ββn, uβββ ββv), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_069.jsonl
|
40d132764e77b33986f4a65d633fe7e1
|
256 megabytes
|
["3\n1 2 3\n1 2\n2 3", "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n3 5", "5\n10 9 8 7 6\n1 2\n2 3\n3 4\n3 5"]
|
PASSED
|
import operator
n = input()
city_numbers = [0]
city_numbers.extend(map(int, raw_input().split()))
adjacent_cities = [[] for _ in xrange(n + 1)]
for _ in xrange(1, n):
u, v = map(int, raw_input().split())
adjacent_cities[u].append(v)
adjacent_cities[v].append(u)
city_bit_path_counts = [[0, 0] for _ in xrange(n + 1)]
# def dfs(curr_city, prev_city, bit):
# result = 0
#
# city_bit = (city_numbers[curr_city] >> bit) & 1
# city_bit_another = 1 - city_bit
# curr_count = city_bit_path_counts[curr_city]
# curr_count[city_bit] = 1
# curr_count[city_bit_another] = 0
#
# cities = adjacent_cities[curr_city]
# if len(cities) > 1 or prev_city == 0:
# for next_city in cities:
# if next_city == prev_city:
# continue
# result += dfs(next_city, curr_city, bit)
# next_count = city_bit_path_counts[next_city]
# result += curr_count[0] * next_count[1] + curr_count[1] * next_count[0]
# curr_count[city_bit] += next_count[0]
# curr_count[city_bit_another] += next_count[1]
#
# return result
def dfs_ex(bit):
stack_i = [None] * n
stack_i[0] = (1, 0)
stack_j = [None] * n
i = j = 0
while i >= 0:
curr_city, prev_city = stack_i[i]
i -= 1
city_bit = (city_numbers[curr_city] >> bit) & 1
city_bit_another = 1 - city_bit
curr_count = city_bit_path_counts[curr_city]
curr_count[city_bit] = 1
curr_count[city_bit_another] = 0
cities = adjacent_cities[curr_city]
if len(cities) > 1 or prev_city == 0:
for next_city in cities:
if next_city != prev_city:
i += 1
stack_i[i] = (next_city, curr_city)
stack_j[j] = (curr_count, city_bit, city_bit_path_counts[next_city])
j += 1
result = 0
while j > 0:
j -= 1
curr_count, city_bit, next_count = stack_j[j]
result += curr_count[0] * next_count[1] + curr_count[1] * next_count[0]
curr_count[city_bit] += next_count[0]
curr_count[1 - city_bit] += next_count[1]
return result
result = sum(city_numbers)
# ceil(log2(10**6)) is 20
op = reduce(operator.or_, city_numbers)
for i in xrange(20):
if (op >> i) & 1:
# result += dfs(1, 0, i) << i
result += dfs_ex(i) << i
print result
|
1486487100
|
[
"math",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
0,
1
] |
|
2 seconds
|
["YES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823"]
|
0f7ceecdffe11f45d0c1d618ef3c6469
| null |
You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$ and $$$a \cdot b \cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer on it. Print "NO" if it is impossible to represent $$$n$$$ as $$$a \cdot b \cdot c$$$ for some distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$. Otherwise, print "YES" and any possible such representation.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The next $$$n$$$ lines describe test cases. The $$$i$$$-th test case is given on a new line as one integer $$$n$$$ ($$$2 \le n \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_005.jsonl
|
8842322a670790c54ce36c85751dc47e
|
256 megabytes
|
["5\n64\n32\n97\n2\n12345"]
|
PASSED
|
def factors(n):
factor = []
for i in range(2, int(n**0.5)+1):
if n % i == 0:
factor.append(i)
return factor
t = int(input())
for l in range(t):
n = int(input())
x = 0
factor = factors(n)
lenfactor = len(factor)
for i in range(lenfactor):
for j in range(i+1, lenfactor):
k = n/(factor[i]*factor[j])
if k%1 == 0 and k != factor[i] and k != factor[j]:
print('YES')
print(str(factor[i]) + ' ' + str(factor[j]) + ' ' + str(int(k)) )
x = 1
break
if x == 1:
break
if x == 0:
print('NO')
|
1579703700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2", "23", "1"]
|
f898d3a58e0ae6ac07d0d14620d47d27
|
NoteIn the first example, the strings we are interested in are $$$[1\, 2\, 2]$$$ and $$$[2\, 1\, 2]$$$. The string $$$[2\, 2\, 1]$$$ is lexicographically larger than the string $$$[2\, 1\, 2\, 1]$$$, so we don't count it.In the second example, all strings count except $$$[4\, 3\, 2\, 1]$$$, so the answer is $$$4! - 1 = 23$$$.In the third example, only the string $$$[1\, 1\, 1\, 2]$$$ counts.
|
While looking at the kitchen fridge, the little boy Tyler noticed magnets with symbols, that can be aligned into a string $$$s$$$.Tyler likes strings, and especially those that are lexicographically smaller than another string, $$$t$$$. After playing with magnets on the fridge, he is wondering, how many distinct strings can be composed out of letters of string $$$s$$$ by rearranging them, so that the resulting string is lexicographically smaller than the string $$$t$$$? Tyler is too young, so he can't answer this question. The alphabet Tyler uses is very large, so for your convenience he has already replaced the same letters in $$$s$$$ and $$$t$$$ to the same integers, keeping that different letters have been replaced to different integers.We call a string $$$x$$$ lexicographically smaller than a string $$$y$$$ if one of the followings conditions is fulfilled: There exists such position of symbol $$$m$$$ that is presented in both strings, so that before $$$m$$$-th symbol the strings are equal, and the $$$m$$$-th symbol of string $$$x$$$ is smaller than $$$m$$$-th symbol of string $$$y$$$. String $$$x$$$ is the prefix of string $$$y$$$ and $$$x \neq y$$$. Because the answer can be too large, print it modulo $$$998\,244\,353$$$.
|
Print a single numberΒ β the number of strings lexicographically smaller than $$$t$$$ that can be obtained by rearranging the letters in $$$s$$$, modulo $$$998\,244\,353$$$.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 200\,000$$$)Β β the lengths of strings $$$s$$$ and $$$t$$$ respectively. The second line contains $$$n$$$ integers $$$s_1, s_2, s_3, \ldots, s_n$$$ ($$$1 \le s_i \le 200\,000$$$)Β β letters of the string $$$s$$$. The third line contains $$$m$$$ integers $$$t_1, t_2, t_3, \ldots, t_m$$$ ($$$1 \le t_i \le 200\,000$$$)Β β letters of the string $$$t$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_091.jsonl
|
ecc14ace4b8f29d14fae45f6e540df95
|
256 megabytes
|
["3 4\n1 2 2\n2 1 2 1", "4 4\n1 2 3 4\n4 3 2 1", "4 3\n1 1 1 2\n1 1 2"]
|
PASSED
|
from __future__ import print_function
from bisect import bisect_left, bisect_right, insort
from collections import Sequence, MutableSequence
from functools import wraps
from itertools import chain, repeat, starmap
from math import log as log_e
import operator as op
from operator import iadd, add
from sys import hexversion
if hexversion < 0x03000000:
from itertools import izip as zip
from itertools import imap as map
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
LOAD = 1000
def recursive_repr(func):
repr_running = set()
@wraps(func)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return '...'
repr_running.add(key)
try:
return func(self)
finally:
repr_running.discard(key)
return wrapper
class SortedList(MutableSequence):
def __init__(self, iterable=None):
self._len = 0
self._lists = []
self._maxes = []
self._index = []
self._load = LOAD
self._half = LOAD >> 1
self._dual = LOAD << 1
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedListWithKey)
else:
raise TypeError('inherit SortedListWithKey for key argument')
@property
def key(self):
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._half = load >> 1
self._dual = load << 1
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, val):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, val)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(val)
_maxes[pos] = val
else:
insort(_lists[pos], val)
self._expand(pos)
else:
_lists.append([val])
_maxes.append(val)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_index = self._index
if len(_lists[pos]) > self._dual:
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, val):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, val)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], val)
return _lists[pos][idx] == val
def discard(self, val):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, val)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], val)
if _lists[pos][idx] == val:
self._delete(pos, idx)
def remove(self, val):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(val))
pos = bisect_left(_maxes, val)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(val))
_lists = self._lists
idx = bisect_left(_lists[pos], val)
if _lists[pos][idx] == val:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(val))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > self._half:
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
pos += self._offset
while pos:
if not pos & 1:
total += _index[pos - 1]
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, idx):
if isinstance(idx, slice):
start, stop, step = idx.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(idx)
self._delete(pos, idx)
_delitem = __delitem__
def __getitem__(self, idx):
_lists = self._lists
if isinstance(idx, slice):
start, stop, step = idx.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
if start_pos == stop_pos:
return _lists[start_pos][start_idx:stop_idx]
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if idx == 0:
return _lists[0][0]
elif idx == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= idx < len(_lists[0]):
return _lists[0][idx]
len_last = len(_lists[-1])
if -len_last < idx < 0:
return _lists[-1][len_last + idx]
pos, idx = self._pos(idx)
return _lists[pos][idx]
_getitem = __getitem__
def _check_order(self, idx, val):
_len = self._len
_lists = self._lists
pos, loc = self._pos(idx)
if idx < 0:
idx += _len
if idx > 0:
idx_prev = loc - 1
pos_prev = pos
if idx_prev < 0:
pos_prev -= 1
idx_prev = len(_lists[pos_prev]) - 1
if _lists[pos_prev][idx_prev] > val:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
if idx < (_len - 1):
idx_next = loc + 1
pos_next = pos
if idx_next == len(_lists[pos_next]):
pos_next += 1
idx_next = 0
if _lists[pos_next][idx_next] < val:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
def __setitem__(self, index, value):
_lists = self._lists
_maxes = self._maxes
_check_order = self._check_order
_pos = self._pos
if isinstance(index, slice):
_len = self._len
start, stop, step = index.indices(_len)
indices = range(start, stop, step)
values = tuple(value)
if step != 1:
if len(values) != len(indices):
raise ValueError(
'attempt to assign sequence of size %s'
' to extended slice of size %s'
% (len(values), len(indices)))
log = []
_append = log.append
for idx, val in zip(indices, values):
pos, loc = _pos(idx)
_append((idx, _lists[pos][loc], val))
_lists[pos][loc] = val
if len(_lists[pos]) == (loc + 1):
_maxes[pos] = val
try:
for idx, _, newval in log:
_check_order(idx, newval)
except ValueError:
for idx, oldval, _ in log:
pos, loc = _pos(idx)
_lists[pos][loc] = oldval
if len(_lists[pos]) == (loc + 1):
_maxes[pos] = oldval
raise
else:
if start == 0 and stop == _len:
self._clear()
return self._update(values)
if stop < start:
stop = start
if values:
alphas = iter(values)
betas = iter(values)
next(betas)
pairs = zip(alphas, betas)
if not all(alpha <= beta for alpha, beta in pairs):
raise ValueError('given values not in sort order')
if start and self._getitem(start - 1) > values[0]:
message = '{0!r} not in sort order at index {1}'.format(
values[0], start)
raise ValueError(message)
if stop != _len and self._getitem(stop) < values[-1]:
message = '{0!r} not in sort order at index {1}'.format(
values[-1], stop)
raise ValueError(message)
self._delitem(index)
_insert = self.insert
for idx, val in enumerate(values):
_insert(start + idx, val)
else:
pos, loc = _pos(index)
_check_order(index, value)
_lists[pos][loc] = value
if len(_lists[pos]) == (loc + 1):
_maxes[pos] = value
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError('.reverse() not defined')
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
elif min_pos == max_pos and not reverse:
return iter(_lists[min_pos][min_idx:max_idx])
elif min_pos == max_pos and reverse:
return reversed(_lists[min_pos][min_idx:max_idx])
elif min_pos + 1 == max_pos and not reverse:
return chain(_lists[min_pos][min_idx:], _lists[max_pos][:max_idx])
elif min_pos + 1 == max_pos and reverse:
return chain(
reversed(_lists[max_pos][:max_idx]),
reversed(_lists[min_pos][min_idx:]),
)
elif not reverse:
return chain(
_lists[min_pos][min_idx:],
chain.from_iterable(_lists[(min_pos + 1):max_pos]),
_lists[max_pos][:max_idx],
)
temp = map(reversed, reversed(_lists[(min_pos + 1):max_pos]))
return chain(
reversed(_lists[max_pos][:max_idx]),
chain.from_iterable(temp),
reversed(_lists[min_pos][min_idx:]),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
return self._len
def bisect_left(self, val):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, val)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], val)
return self._loc(pos, idx)
def bisect_right(self, val):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, val)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], val)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, val):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, val)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], val)
pos_right = bisect_right(_maxes, val)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], val)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, val):
_lists = self._lists
_maxes = self._maxes
if not _maxes:
_maxes.append(val)
_lists.append([val])
self._len = 1
return
pos = len(_lists) - 1
if val < _lists[pos][-1]:
msg = '{0!r} not in sort order at index {1}'.format(val, self._len)
raise ValueError(msg)
_maxes[pos] = val
_lists[pos].append(val)
self._len += 1
self._expand(pos)
def extend(self, values):
_lists = self._lists
_maxes = self._maxes
_load = self._load
if not isinstance(values, list):
values = list(values)
if not values:
return
if any(values[pos - 1] > values[pos]
for pos in range(1, len(values))):
raise ValueError('given sequence not in sort order')
offset = 0
if _maxes:
if values[0] < _lists[-1][-1]:
msg = '{0!r} not in sort order at index {1}'.format(values[0], self._len)
raise ValueError(msg)
if len(_lists[-1]) < self._half:
_lists[-1].extend(values[:_load])
_maxes[-1] = _lists[-1][-1]
offset = _load
len_lists = len(_lists)
for idx in range(offset, len(values), _load):
_lists.append(values[idx:(idx + _load)])
_maxes.append(_lists[-1][-1])
_index = self._index
if len_lists == len(_lists):
len_index = len(_index)
if len_index > 0:
len_values = len(values)
child = len_index - 1
while child:
_index[child] += len_values
child = (child - 1) >> 1
_index[0] += len_values
else:
del _index[:]
self._len += len(values)
def insert(self, idx, val):
_len = self._len
_lists = self._lists
_maxes = self._maxes
if idx < 0:
idx += _len
if idx < 0:
idx = 0
if idx > _len:
idx = _len
if not _maxes:
_maxes.append(val)
_lists.append([val])
self._len = 1
return
if not idx:
if val > _lists[0][0]:
msg = '{0!r} not in sort order at index {1}'.format(val, 0)
raise ValueError(msg)
else:
_lists[0].insert(0, val)
self._expand(0)
self._len += 1
return
if idx == _len:
pos = len(_lists) - 1
if _lists[pos][-1] > val:
msg = '{0!r} not in sort order at index {1}'.format(val, _len)
raise ValueError(msg)
else:
_lists[pos].append(val)
_maxes[pos] = _lists[pos][-1]
self._expand(pos)
self._len += 1
return
pos, idx = self._pos(idx)
idx_before = idx - 1
if idx_before < 0:
pos_before = pos - 1
idx_before = len(_lists[pos_before]) - 1
else:
pos_before = pos
before = _lists[pos_before][idx_before]
if before <= val <= _lists[pos][idx]:
_lists[pos].insert(idx, val)
self._expand(pos)
self._len += 1
else:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
def pop(self, idx=-1):
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if idx == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if idx == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= idx < len(_lists[0]):
val = _lists[0][idx]
self._delete(0, idx)
return val
len_last = len(_lists[-1])
if -len_last < idx < 0:
pos = len(_lists) - 1
loc = len_last + idx
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(idx)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, val, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(val))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(val))
_maxes = self._maxes
pos_left = bisect_left(_maxes, val)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(val))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], val)
if _lists[pos_left][idx_left] != val:
raise ValueError('{0!r} is not in list'.format(val))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(val) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(val))
def __add__(self, that):
values = reduce(iadd, self._lists, [])
values.extend(that)
return self.__class__(values)
def __iadd__(self, that):
self._update(that)
return self
def __mul__(self, that):
values = reduce(iadd, self._lists, []) * that
return self.__class__(values)
def __imul__(self, that):
values = reduce(iadd, self._lists, []) * that
self._clear()
self._update(values)
return self
def _make_cmp(self, seq_op, doc):
def comparer(self, that):
if not isinstance(that, Sequence):
return NotImplemented
self_len = self._len
len_that = len(that)
if self_len != len_that:
if seq_op is op.eq:
return False
if seq_op is op.ne:
return True
for alpha, beta in zip(self, that):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_that)
comparer.__name__ = '__{0}__'.format(seq_op.__name__)
doc_str = 'Return `True` if and only if Sequence is {0} `that`.'
comparer.__doc__ = doc_str.format(doc)
return comparer
__eq__ = _make_cmp(None, op.eq, 'equal to')
__ne__ = _make_cmp(None, op.ne, 'not equal to')
__lt__ = _make_cmp(None, op.lt, 'less than')
__gt__ = _make_cmp(None, op.gt, 'greater than')
__le__ = _make_cmp(None, op.le, 'less than or equal to')
__ge__ = _make_cmp(None, op.ge, 'greater than or equal to')
@recursive_repr
def __repr__(self):
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
try:
assert self._load >= 4
assert self._half == (self._load >> 1)
assert self._dual == (self._load << 1)
if self._maxes == []:
assert self._lists == []
return
assert self._maxes and self._lists
assert all(sublist[pos - 1] <= sublist[pos]
for sublist in self._lists
for pos in range(1, len(sublist)))
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
assert len(self._maxes) == len(self._lists)
assert all(self._maxes[pos] == self._lists[pos][-1]
for pos in range(len(self._maxes)))
assert all(len(sublist) <= self._dual for sublist in self._lists)
assert all(len(self._lists[pos]) >= self._half
for pos in range(0, len(self._lists) - 1))
assert self._len == sum(len(sublist) for sublist in self._lists)
if self._index:
assert len(self._index) == self._offset + len(self._lists)
assert self._len == self._index[0]
def test_offset_pos(pos):
from_index = self._index[self._offset + pos]
return from_index == len(self._lists[pos])
assert all(test_offset_pos(pos)
for pos in range(len(self._lists)))
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert self._index[pos] == child_sum
except:
import sys
import traceback
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load, self._half, self._dual)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
def identity(value):
return value
class SortedListWithKey(SortedList):
def __init__(self, iterable=None, key=identity):
self._len = 0
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._key = key
self._load = LOAD
self._half = LOAD >> 1
self._dual = LOAD << 1
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, val):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(val)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(val)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, val)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([val])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > self._dual:
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, val):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == val:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, val):
_maxes = self._maxes
if not _maxes:
return
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == val:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, val):
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(val))
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(val))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} not in list'.format(val))
if _lists[pos][idx] == val:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} not in list'.format(val))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > self._half:
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def _check_order(self, idx, key, val):
_len = self._len
_keys = self._keys
pos, loc = self._pos(idx)
if idx < 0:
idx += _len
if idx > 0:
idx_prev = loc - 1
pos_prev = pos
if idx_prev < 0:
pos_prev -= 1
idx_prev = len(_keys[pos_prev]) - 1
if _keys[pos_prev][idx_prev] > key:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
if idx < (_len - 1):
idx_next = loc + 1
pos_next = pos
if idx_next == len(_keys[pos_next]):
pos_next += 1
idx_next = 0
if _keys[pos_next][idx_next] < key:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
def __setitem__(self, index, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_check_order = self._check_order
_pos = self._pos
if isinstance(index, slice):
_len = self._len
start, stop, step = index.indices(_len)
indices = range(start, stop, step)
values = tuple(value)
if step != 1:
if len(values) != len(indices):
raise ValueError(
'attempt to assign sequence of size %s'
' to extended slice of size %s'
% (len(values), len(indices)))
log = []
_append = log.append
for idx, val in zip(indices, values):
pos, loc = _pos(idx)
key = self._key(val)
_append((idx, _keys[pos][loc], key, _lists[pos][loc], val))
_keys[pos][loc] = key
_lists[pos][loc] = val
if len(_keys[pos]) == (loc + 1):
_maxes[pos] = key
try:
for idx, oldkey, newkey, oldval, newval in log:
_check_order(idx, newkey, newval)
except ValueError:
for idx, oldkey, newkey, oldval, newval in log:
pos, loc = _pos(idx)
_keys[pos][loc] = oldkey
_lists[pos][loc] = oldval
if len(_keys[pos]) == (loc + 1):
_maxes[pos] = oldkey
raise
else:
if start == 0 and stop == self._len:
self._clear()
return self._update(values)
if stop < start:
stop = start
if values:
keys = tuple(map(self._key, values))
alphas = iter(keys)
betas = iter(keys)
next(betas)
pairs = zip(alphas, betas)
if not all(alpha <= beta for alpha, beta in pairs):
raise ValueError('given values not in sort order')
if start:
pos, loc = _pos(start - 1)
if _keys[pos][loc] > keys[0]:
msg = '{0!r} not in sort order at index {1}'.format(
values[0], start)
raise ValueError(msg)
if stop != _len:
pos, loc = _pos(stop)
if _keys[pos][loc] < keys[-1]:
msg = '{0!r} not in sort order at index {1}'.format(
values[-1], stop)
raise ValueError(msg)
self._delitem(index)
_insert = self.insert
for idx, val in enumerate(values):
_insert(start + idx, val)
else:
pos, loc = _pos(index)
key = self._key(value)
_check_order(index, key, value)
_lists[pos][loc] = value
_keys[pos][loc] = key
if len(_lists[pos]) == (loc + 1):
_maxes[pos] = key
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
minimum = self._key(minimum) if minimum is not None else None
maximum = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=minimum, max_key=maximum,
inclusive=inclusive, reverse=reverse,
)
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, val):
return self._bisect_key_left(self._key(val))
def bisect_right(self, val):
return self._bisect_key_right(self._key(val))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, val):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == val:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def append(self, val):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(val)
if not _maxes:
_maxes.append(key)
_keys.append([key])
_lists.append([val])
self._len = 1
return
pos = len(_keys) - 1
if key < _keys[pos][-1]:
msg = '{0!r} not in sort order at index {1}'.format(val, self._len)
raise ValueError(msg)
_lists[pos].append(val)
_keys[pos].append(key)
_maxes[pos] = key
self._len += 1
self._expand(pos)
def extend(self, values):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_load = self._load
if not isinstance(values, list):
values = list(values)
keys = list(map(self._key, values))
if any(keys[pos - 1] > keys[pos]
for pos in range(1, len(keys))):
raise ValueError('given sequence not in sort order')
offset = 0
if _maxes:
if keys[0] < _keys[-1][-1]:
msg = '{0!r} not in sort order at index {1}'.format(values[0], self._len)
raise ValueError(msg)
if len(_keys[-1]) < self._half:
_lists[-1].extend(values[:_load])
_keys[-1].extend(keys[:_load])
_maxes[-1] = _keys[-1][-1]
offset = _load
len_keys = len(_keys)
for idx in range(offset, len(keys), _load):
_lists.append(values[idx:(idx + _load)])
_keys.append(keys[idx:(idx + _load)])
_maxes.append(_keys[-1][-1])
_index = self._index
if len_keys == len(_keys):
len_index = len(_index)
if len_index > 0:
len_values = len(values)
child = len_index - 1
while child:
_index[child] += len_values
child = (child - 1) >> 1
_index[0] += len_values
else:
del _index[:]
self._len += len(values)
def insert(self, idx, val):
_len = self._len
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
if idx < 0:
idx += _len
if idx < 0:
idx = 0
if idx > _len:
idx = _len
key = self._key(val)
if not _maxes:
self._len = 1
_lists.append([val])
_keys.append([key])
_maxes.append(key)
return
if not idx:
if key > _keys[0][0]:
msg = '{0!r} not in sort order at index {1}'.format(val, 0)
raise ValueError(msg)
else:
self._len += 1
_lists[0].insert(0, val)
_keys[0].insert(0, key)
self._expand(0)
return
if idx == _len:
pos = len(_keys) - 1
if _keys[pos][-1] > key:
msg = '{0!r} not in sort order at index {1}'.format(val, _len)
raise ValueError(msg)
else:
self._len += 1
_lists[pos].append(val)
_keys[pos].append(key)
_maxes[pos] = _keys[pos][-1]
self._expand(pos)
return
pos, idx = self._pos(idx)
idx_before = idx - 1
if idx_before < 0:
pos_before = pos - 1
idx_before = len(_keys[pos_before]) - 1
else:
pos_before = pos
before = _keys[pos_before][idx_before]
if before <= key <= _keys[pos][idx]:
self._len += 1
_lists[pos].insert(idx, val)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
msg = '{0!r} not in sort order at index {1}'.format(val, idx)
raise ValueError(msg)
def index(self, val, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(val))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(val))
_maxes = self._maxes
key = self._key(val)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError('{0!r} is not in list'.format(val))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError('{0!r} is not in list'.format(val))
if _lists[pos][idx] == val:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError('{0!r} is not in list'.format(val))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError('{0!r} is not in list'.format(val))
def __add__(self, that):
values = reduce(iadd, self._lists, [])
values.extend(that)
return self.__class__(values, key=self._key)
def __mul__(self, that):
values = reduce(iadd, self._lists, []) * that
return self.__class__(values, key=self._key)
def __imul__(self, that):
values = reduce(iadd, self._lists, []) * that
self._clear()
self._update(values)
return self
@recursive_repr
def __repr__(self):
name = type(self).__name__
values = list(self)
_key = self._key
return '{0}({1!r}, key={2!r})'.format(name, values, _key)
def _check(self):
try:
assert self._load >= 4
assert self._half == (self._load >> 1)
assert self._dual == (self._load << 1)
if self._maxes == []:
assert self._keys == []
assert self._lists == []
return
assert self._maxes and self._keys and self._lists
assert all(sublist[pos - 1] <= sublist[pos]
for sublist in self._keys
for pos in range(1, len(sublist)))
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert all(len(val_list) == len(key_list)
for val_list, key_list in zip(self._lists, self._keys))
assert all(self._key(val) == key for val, key in
zip((_val for _val_list in self._lists for _val in _val_list),
(_key for _key_list in self._keys for _key in _key_list)))
assert all(self._maxes[pos] == self._keys[pos][-1]
for pos in range(len(self._maxes)))
assert all(len(sublist) <= self._dual for sublist in self._lists)
assert all(len(self._lists[pos]) >= self._half
for pos in range(0, len(self._lists) - 1))
assert self._len == sum(len(sublist) for sublist in self._lists)
if self._index:
assert len(self._index) == self._offset + len(self._lists)
assert self._len == self._index[0]
def test_offset_pos(pos):
from_index = self._index[self._offset + pos]
return from_index == len(self._lists[pos])
assert all(test_offset_pos(pos)
for pos in range(len(self._lists)))
for pos in range(self._offset):
child = (pos << 1) + 1
if self._index[pos] == 0:
assert child >= len(self._index)
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert self._index[pos] == child_sum
except:
import sys
import traceback
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load, self._half, self._dual)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_keys', len(self._keys))
print('keys', self._keys)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
from collections import Counter
m,n = map(int,input().split())
s = list(map(int,input().split()))
t = list(map(int,input().split()))
def f(num):
res = 1
for i in range(1,num+1):
res *= i
res %= mod
return res
ans = 0
mod = 998244353
cnt1 = Counter(s)
cnt2 = Counter(t)
a = f(m)
for v in cnt1.values():
if v > 1:
a *= pow(f(v),mod-2,mod)
a %= mod
d = SortedList(s)
ok = True
ta = 0
for i in range(min(m,n)-1):
k = t[i]
a *= pow(m-i,mod-2,mod)
idx1 = d.bisect_left(k)
ans += a*(idx1)
if cnt1[k] == 0:
ok = False
break
a *= cnt1[k]
a %= mod
cnt1[k] -= 1
d.pop(idx1)
i = min(m,n)-1
if ok:
if m >= n:
a *= pow(m-i,mod-2,mod)
a %= mod
idx1 = d.bisect_left(t[i])
ans += a*(idx1)
else:
a *= pow(m-i,mod-2,mod)
a %= mod
idx1 = d.bisect_right(t[i])
ans += a*(idx1)
print(ans%mod)
|
1646560500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["10", "7"]
|
cfdbe4bd1c9438de2d871768c546a580
|
NoteCells, reachable in the corresponding example, are marked with '+'.First example: +++..+***.+++***+++. Second example: .++..+*..++..++.
|
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
Print exactly one integerΒ β the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself.
|
The first line contains two integers n, m (1ββ€βn,βmββ€β2000)Β β the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1ββ€βrββ€βn, 1ββ€βcββ€βm)Β β index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0ββ€βx,βyββ€β109)Β β the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,800 |
train_008.jsonl
|
72c98a58dd43ef40436c0cf295743244
|
512 megabytes
|
["4 5\n3 2\n1 2\n.....\n.***.\n...**\n*....", "4 4\n2 2\n0 1\n....\n..*.\n....\n...."]
|
PASSED
|
from collections import defaultdict,deque
n,m=[int(el) for el in raw_input().split()]
r,c=[int(el) for el in raw_input().split()]
x,y=[int(el) for el in raw_input().split()]
s=['*'*(m+2)]
for i in range(n):
q=raw_input()
w='*'+q+'*'
s.append(w)
s.append('*'*(m+2))
def bfs(way):
ans=0
while len(way)!=0:
x,y,l,r=way.pop()
if visited[x-1][y]==0 and s[x-1][y]=='.':
way.append([x-1,y,l,r])
visited[x-1][y]=1
ans+=1
if visited[x+1][y]==0 and s[x+1][y]=='.':
way.append([x+1,y,l,r])
visited[x+1][y]=1
ans+=1
if visited[x][y-1]==0 and s[x][y-1]=='.' and l>0:
way.appendleft([x,y-1,l-1,r])
visited[x][y-1]=1
ans+=1
if visited [x][y+1]==0 and s[x][y+1]=='.' and r>0:
way.appendleft([x,y+1,l,r-1])
visited[x][y+1]=1
ans+=1
return ans
way=deque()
way.append((r,c,x,y))
visited = [[0 for i in range(m+2)] for j in range(n+2)]
visited[r][c]=1
ans=bfs(way)
#visited=set(visited)
print(ans+1)
|
1539511500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
4 seconds
|
["? 7 3 5\n\n? 1 6 4\n\n? 1 5 4\n\n! 4"]
|
f413f65186ec202bc75809985fba1222
|
NoteThe labels corresponding to the tree in the example are [$$$4$$$,$$$7$$$,$$$2$$$,$$$6$$$,$$$1$$$,$$$5$$$,$$$3$$$], meaning the root is labelled $$$4$$$, and for $$$1 < i \le n$$$, the parent of $$$p_i$$$ is $$$p_{ \lfloor{\frac{i}{2}}\rfloor }$$$.
|
This is an interactive problem.Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.There is a perfect binary tree of height $$$h$$$ consisting of $$$n = 2^{h} - 1$$$ nodes. The nodes have been assigned distinct labels from $$$1$$$ to $$$n$$$. However, Igor only knows $$$h$$$ and does not know which label corresponds to which node. To find key to Olha's heart he needs to find the label assigned to the root by making queries of the following type at most $$$n+420$$$ times: Select three distinct labels $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1 \leq u,v,w \leq n$$$). In response, Olha (the grader) will tell him the label of the lowest common ancestor of nodes labelled $$$u$$$ and $$$v$$$, if the tree was rooted at the node labelled $$$w$$$ instead. Help Igor to find the root!Note: the grader is not adaptive: the labels are fixed before any queries are made.
| null |
The first and only line contains a single integer $$$h$$$ ($$$3 \le h \le 18$$$)Β β the height of the tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 3,000 |
train_070.jsonl
|
937adcfff09bc0c293d167316a00f8fb
|
256 megabytes
|
["3\n\n2\n\n7\n\n4"]
|
PASSED
|
import sys,random
def main():
h = int(input());power = [1];askarray = [];askarrayind = []
for i in range(h+1):power.append(power[-1] * 2)
for j in range(0, power[h]):askarrayind.append([0, j])
n = power[h] - 1;askcnt = 420
for i in range(askcnt):
a = random.randint(1, n);b = random.randint(1, n)
while (b == a):b = random.randint(1, n)
c = random.randint(1, n)
while (c == a or c == b):c = random.randint(1, n)
print("?", a, b, c);sys.stdout.flush();answer = int(input());askarrayind[answer][0] += 1
result = sorted(askarrayind, key=lambda thing: -thing[0]);a = result[0][1];b = result[1][1];chkff = False;batch_size = 200
for j in range((n+1)//batch_size + 2):
for i in range(1 + batch_size * j, min(1 + batch_size * (j+1), n+1)):
if i == a or i == b:continue
print("?", a, b, i)
sys.stdout.flush()
for i in range(1 + batch_size * j, min(1 + batch_size * (j+1), n+1)):
if i == a or i == b:continue
if int(input()) == i:print("!", i);chkff = True;break
if chkff:break
main()
|
1605278100
|
[
"probabilities",
"trees"
] |
[
0,
0,
0,
0,
0,
1,
0,
1
] |
|
5 seconds
|
["500000004\n1\n500000004", "625000011\n13\n62500020\n375000027\n62500027"]
|
cdf42ae9f76a36295c701b0606ea5bfc
|
NoteIn first testcase, initially, there are four possible battalions {} Strength = $$$0$$$ {$$$1$$$} Strength = $$$0$$$ {$$$2$$$} Strength = $$$0$$$ {$$$1,2$$$} Strength = $$$2$$$ So strength of army is $$$\frac{0+0+0+2}{4}$$$ = $$$\frac{1}{2}$$$After changing $$$p_{1}$$$ to $$$2$$$, strength of battallion {$$$1,2$$$} changes to $$$4$$$, so strength of army becomes $$$1$$$.After changing $$$p_{2}$$$ to $$$1$$$, strength of battalion {$$$1,2$$$} again becomes $$$2$$$, so strength of army becomes $$$\frac{1}{2}$$$.
|
There are $$$n$$$ officers in the Army of Byteland. Each officer has some power associated with him. The power of the $$$i$$$-th officer is denoted by $$$p_{i}$$$. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these $$$n$$$ officers and calls this subset a battalion.(All $$$2^n$$$ subsets of the $$$n$$$ officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be $$$a_{1},a_{2},\ldots,a_{k}$$$, where $$$a_1 \le a_2 \le \dots \le a_k$$$. The strength of this battalion is equal to $$$a_1a_2 + a_2a_3 + \dots + a_{k-1}a_k$$$. (If the size of Battalion is $$$\leq 1$$$, then the strength of this battalion is $$$0$$$).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be $$$q$$$ changes. Each one of the form $$$i$$$ $$$x$$$ indicating that $$$p_{i}$$$ is changed to $$$x$$$.You need to find the strength of the army initially and after each of these $$$q$$$ updates.Note that the changes are permanent.The strength should be found by modulo $$$10^{9}+7$$$. Formally, let $$$M=10^{9}+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$p/q$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q\not\equiv 0 \bmod M$$$). Output the integer equal to $$$p\cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \leq x < M$$$ and $$$x β
q \equiv p \bmod M$$$).
|
In the first line output the initial strength of the army. In $$$i$$$-th of the next $$$q$$$ lines, output the strength of the army after $$$i$$$-th update.
|
The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 3β
10^{5}$$$) Β β the number of officers in Byteland's Army. The second line contains $$$n$$$ integers $$$p_{1},p_{2},\ldots,p_{n}$$$ ($$$1 \leq p_{i} \leq 10^{9}$$$). The third line contains a single integer $$$q$$$ ($$$1 \leq q \leq 3β
10^{5}$$$) Β β the number of updates. Each of the next $$$q$$$ lines contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$ 1 \leq x \leq 10^{9}$$$), indicating that $$$p_{i}$$$ is updated to $$$x$$$ .
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,800 |
train_070.jsonl
|
9c11f8f3a484509b7dfcd0b39691ed80
|
256 megabytes
|
["2\n1 2\n2\n1 2\n2 1", "4\n1 2 3 4\n4\n1 5\n2 5\n3 5\n4 5"]
|
PASSED
|
import sys, os
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod
sub = __pypy__.intop.int_sub
mul = __pypy__.intop.int_mul
MOD = 10**9 + 7
MODINV = 1.0/MOD
def mulmod(a,b):
x = sub(mul(a,b), mul(MOD, int(a * MODINV * b)))
return x + MOD if (x < 0) else (x if x < MOD else x - MOD)
#precalc 2^-1 powers
invpow = pow(2, MOD - 2, MOD)
pow2 = [1]
for _ in range(3 * 10**5 + 10):
pow2.append(mulmod(pow2[-1], invpow))
# returns order such that A[order[i]] <= A[order[i + 1]]
def sqrtsorted(A, maxval = 10**9):
asqrt = int((maxval)**0.5 + 2)
blocks1 = [[] for _ in range(asqrt)]
blocks2 = [[] for _ in range(asqrt)]
for i in range(len(A)):
blocks1[A[i] % asqrt].append(i)
for block in blocks1:
for i in block:
blocks2[A[i]//asqrt].append(i)
ret = []
for block in blocks2:
ret += block
return ret
# Keeps track of expected power using the structure of the segment tree
class segtree:
def __init__(self, data, counter):
n = len(data)
m = 1
while m < n: m *= 2
self.m = m
self.dataL = [0]*(m+m)
self.dataR = [0]*(m+m)
self.counter = [0]*(m+m)
self.power = 0
self.dataL[m:m+n] = data
self.dataR[m:m+n] = data
self.counter[m:m+n] = counter
for ind in reversed(range(1,m)):
self.counter[ind] = self.counter[ind << 1] + self.counter[(ind << 1) + 1]
self.dataL[ind] = (mulmod(self.dataL[ind << 1], pow2[self.counter[(ind << 1) + 1]]) + self.dataL[(ind << 1) + 1] ) % MOD
self.dataR[ind] = (self.dataR[ind << 1] + mulmod(self.dataR[(ind << 1) + 1], pow2[self.counter[ind << 1]]) ) % MOD
self.power = (self.power + mulmod(self.dataL[ind << 1], self.dataR[(ind << 1) + 1]) ) % MOD
# Keeps track of expected power when the segment tree is modified
def add(self, ind, val, c = 1):
ind += self.m
while ind > 1:
self.counter[ind] += c
self.power = self.power - mulmod(self.dataL[ind & ~1], self.dataR[ind | 1])
# If first time
if ind >= self.m:
self.dataL[ind] = val
self.dataR[ind] = val
else:
self.dataL[ind] = (mulmod(self.dataL[ind << 1], pow2[self.counter[(ind << 1) + 1]]) + self.dataL[(ind << 1) + 1] ) % MOD
self.dataR[ind] = (self.dataR[ind << 1] + mulmod(self.dataR[(ind << 1) + 1], pow2[self.counter[ind << 1]]) ) % MOD
self.power = (self.power + mulmod(self.dataL[ind & ~1], self.dataR[ind | 1]) ) % MOD
ind >>= 1
def rem(self, ind):
self.add(ind, 0, -1)
def get_power(self):
return mulmod(self.power, pow2[2])
#############
### READ INPUT
inp = [int(x) for x in os.read(0, os.fstat(0).st_size).split()]; ii = 0
n = inp[ii]; ii += 1
# Order all involved powers
values = inp[ii: ii + n] + inp[ii + n + 2:: 2]
order = sqrtsorted(values)
invorder = [-1]*len(order)
for i in range(len(order)):
invorder[order[i]] = i
# Initialize the seg tree containing powers
P = inp[ii: ii + n]; ii += n
who = list(range(n))
##############
### POPULATE SEGTREE
power = 0
data = [0]*len(order)
counter = [0]*len(order)
for i in range(n):
data[invorder[i]] = P[i]
counter[invorder[i]] = 1
seg = segtree(data, counter)
##############
### SOLVE QUERIES
import __pypy__
out = __pypy__.builders.StringBuilder()
q = inp[ii]; ii += 1
out.append(str(seg.get_power()))
out.append('\n')
for _ in range(q):
i = inp[ii] - 1; ii += 1
x = inp[ii]; ii += 1
# Remove power at who[i]
ind = invorder[who[i]]
seg.rem(ind)
# Add new power at i
ind = invorder[n + _]
who[i] = n + _
seg.add(ind, x)
out.append(str(seg.get_power()))
out.append('\n')
os.write(1, out.build())
|
1583332500
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["1\n0\n2"]
|
475a24d36eab99ae4f78815ccdc5da91
|
NoteIn the first test case it's possible to make all ratings equal to $$$69$$$. First account's rating will increase by $$$1$$$, and second account's rating will decrease by $$$1$$$, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $$$4$$$.
|
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.
|
For each test case output the minimal number of contests needed to infect all accounts.
|
The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$Β β the number of test cases. The next $$$2t$$$ lines contain the descriptions of all test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$2 \le n \le 10^3$$$, $$$-4000 \le x \le 4000$$$)Β β the number of accounts on Codeforces and the rating of Killjoy's account. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-4000 \le a_i \le 4000)$$$Β β the ratings of other accounts.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500 |
train_006.jsonl
|
d6ca80729f2e61fdd0b09578dac11561
|
256 megabytes
|
["3\n2 69\n68 70\n6 4\n4 4 4 4 4 4\n9 38\n-21 83 50 -59 -77 15 -71 -78 20"]
|
PASSED
|
from collections import defaultdict
t = int(input())
for _ in range(t):
n,x = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
dic = defaultdict(lambda:0)
d = 0
c = 0
for i in range(n):
d+=(l[i]==x)
c+=l[i]-x
if d==n:
print(0)
elif c==0:
print(1)
elif c!=0 and d:
print(1)
else :
print(2)
|
1600526100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "6", "0"]
|
9202022089083f17e7165c6c1e53f2e1
|
NoteIn the first sample there are three suitable pairs: $$$(1; 9)$$$, $$$(3; 3)$$$ and $$$(9; 1)$$$.In the second sample case there are 6 suitable pairs: $$$(2; 220)$$$, $$$(4; 110)$$$, $$$(8; 55)$$$, $$$(10; 44)$$$, $$$(20; 22)$$$ and $$$(40; 11)$$$.Here the sample of cut for $$$(20; 22)$$$. The third sample has no suitable pairs.
|
A rectangle with sides $$$A$$$ and $$$B$$$ is cut into rectangles with cuts parallel to its sides. For example, if $$$p$$$ horizontal and $$$q$$$ vertical cuts were made, $$$(p + 1) \cdot (q + 1)$$$ rectangles were left after the cutting. After the cutting, rectangles were of $$$n$$$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $$$a \times b$$$ and $$$b \times a$$$ are considered different if $$$a \neq b$$$.For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.Calculate the amount of pairs $$$(A; B)$$$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $$$A$$$ and $$$B$$$. Note that pairs $$$(A; B)$$$ and $$$(B; A)$$$ are considered different when $$$A \neq B$$$.
|
Output one integerΒ β the answer to the problem.
|
The first line consists of a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^{5}$$$)Β β amount of different types of rectangles left after cutting the initial rectangle. The next $$$n$$$ lines each consist of three integers $$$w_{i}, h_{i}, c_{i}$$$ $$$(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$$$Β β the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type. It is guaranteed that the rectangles of the different types are different.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,600 |
train_040.jsonl
|
e75420a72c669da6c14313a2d7a89b7b
|
256 megabytes
|
["1\n1 1 9", "2\n2 3 20\n2 4 40", "2\n1 2 5\n2 3 5"]
|
PASSED
|
n = input()
w=[]
h=[]
c=[]
cntw={}
cnth={}
gcdC=0
cntC=0
def insert1(a,b,c):
if not a in b :
b[a]=c
else :
b[a]=b[a]+c
def gcd(a,b):
if a % b == 0 :
return b
else :
return gcd(b,a%b)
for i in range(0, n):
a,b,d = map(int, raw_input().split())
w.append(a)
h.append(b)
c.append(d)
insert1(a,cntw,d)
insert1(b,cnth,d)
cntC += d
if gcdC == 0 :
gcdC = d
else :
gcdC = gcd(gcdC, d)
for i in range(0, n):
if cntw[w[i]] * cnth[h[i]] != cntC * c[i]:
print 0
exit()
ans = 0
i = 1
while (i * i <= gcdC) :
if gcdC % i == 0 :
ans += 1
if i * i != gcdC :
ans += 1
i += 1
print ans
|
1523973900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n2 1", "4\n1 2 2 1"]
|
080287f34b0c1d52eb29eb81dada41dd
|
NoteIn the first test case Valera can put the first cube in the first heap, and second cube β in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313,β1345,β2413,β2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.
|
Valera has 2Β·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer β the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?
|
In the first line print a single number β the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2Β·n numbers bi (1ββ€βbiββ€β2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.
|
The first line contains integer n (1ββ€βnββ€β100). The second line contains 2Β·n space-separated integers ai (10ββ€βaiββ€β99), denoting the numbers on the cubes.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_009.jsonl
|
9d17da0965a1769fbadef3c81ca29a6c
|
256 megabytes
|
["1\n10 99", "2\n13 24 13 45"]
|
PASSED
|
from math import*
from random import*
n = int(input()) * 2
A = list(map(int, input().split()))
amount = [0] * 101
B = []
for i in range(n):
if amount[A[i]] < 2:
amount[A[i]] += 1
B += [(A[i], i)]
B.sort()
x, y = [], []
for i in range(len(B)):
if(i % 2 == 0):
x.append(B[i][1])
else:
y.append(B[i][1])
lolka = 0
aaa = 0
# print(x)
# print(y)
print(len(x) * len(y))
for i in range(n):
if i in x:
lolka += 1
aaa += 1
print(1, end = ' ')
elif i in y:
print(2, end = ' ')
else:
if len(x) - lolka + aaa < n // 2:
print(1, end = ' ')
aaa += 1
else:
print(2, end = ' ')
print()
# B, C = [], []
# for i in range(n):
# S = list(set(A))
# where = [0] * 101
# am1, am2 = 0, 0
# for i in range(len(S)):
# if(i % 2 == 0):
# where[S[i]] = 1
# am1 += 1
# else:
# where[S[i]] = 2
# am2 += 1
# used = [0] * 201
# for i in range(n):
# if not used[A[i]]:
# print(where[A[i]])
# used[A[i]] = True
# else:
# print(3 - where[A[i]])
|
1381419000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["3\n1 2 4", "4\n1 2 4 6", "3\n1 3 5"]
|
31b929252f7d63cb3654ed367224cc31
| null |
Recently Irina arrived to one of the most famous cities of BerlandΒ β the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.
|
Print the single integer k (2ββ€βkββ€βn)Β β the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line. Print k distinct integers in the second lineΒ β indices of showplaces that Irina will visit on her route, in the order of encountering them. If there are multiple answers, print any of them.
|
The first line of the input contains three integers n,βm and T (2ββ€βnββ€β5000,ββ1ββ€βmββ€β5000,ββ1ββ€βTββ€β109)Β β the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively. The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui,βvi,βti (1ββ€βui,βviββ€βn,βuiββ βvi,β1ββ€βtiββ€β109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes. It is guaranteed, that there is at most one road between each pair of showplaces.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_039.jsonl
|
8545bda8903e6a7207f8039f80ae388a
|
256 megabytes
|
["4 3 13\n1 2 5\n2 3 7\n2 4 8", "6 6 7\n1 2 2\n1 3 3\n3 6 3\n2 4 2\n4 6 2\n6 5 1", "5 5 6\n1 3 3\n3 5 3\n1 2 2\n2 4 3\n4 5 2"]
|
PASSED
|
from sys import stdin, stdout
# LinkedList.py
class LLNode:
def __init__(self, value = None, nextNode = None):
self.value, self.nextNode = value, nextNode
class LinkedList:
def __init__(self, rootNode = None):
self.rootNode = rootNode
def FindBestPath(self, wayTime):
cNode = self.rootNode
while cNode != None:
if cNode.value.wayTime <= wayTime:
break
cNode = cNode.nextNode
return cNode
def FindMaxPreNode(self, path, startNode): # by wayLen
if path.wayLen > startNode.value.wayLen:
return None
preNode = startNode
while preNode.nextNode != None:
if path.wayLen > preNode.nextNode.value.wayLen:
break
preNode = preNode.nextNode
return preNode
def FindMaxNextNode(self, path, startNode): # by wayTime
cNode = startNode
while cNode != None:
if cNode.value.wayTime < path.wayTime:
break
cNode = cNode.nextNode
return cNode
def RawInsert(self, path):
if path == None:
return
if self.rootNode == None:
self.rootNode = LLNode(path, None)
return
preNode = self.FindMaxPreNode(path, self.rootNode)
preNode.nextNode = LLNode(path, None)
def Insert(self, path):
if path == None:
return False
if self.rootNode == None:
self.rootNode = LLNode(path, None)
return True
preNode = self.FindMaxPreNode(path, self.rootNode)
node = None
if preNode == None:
node = LLNode(path, self.rootNode)
self.rootNode = node
else:
if path.wayTime < preNode.value.wayTime:
if path.wayLen == preNode.value.wayLen:
preNode.value = path
node = preNode
else:
node = LLNode(path, preNode.nextNode)
preNode.nextNode = node
else:
return False
if node.nextNode != None: # delete useless paths
nextNode = self.FindMaxNextNode(path, node.nextNode)
node.nextNode = nextNode
return True
# Main.py
cities = []
memo = []
T = 0
class Node:
def __init__(self, number, wayLen, wayTime, preNode):
self.number, self.wayLen, self.wayTime, self.preNode = number, wayLen, wayTime, preNode
class Path:
def __init__(self, wayLen, wayTime, nextNode):
self.wayLen, self.wayTime, self.nextNode = wayLen, wayTime, nextNode
def MemoizeWay2(endNode):
global memo, T
cNode = endNode
while cNode.preNode != None:
cLLNode = memo[cNode.number].rootNode
while cLLNode != None:
tailLen = cLLNode.value.wayLen + 1
tailTime = cLLNode.value.wayTime + cities[cNode.preNode.number][cNode.number]
memo[cNode.preNode.number].Insert(Path(tailLen, tailTime, cNode.number))
cLLNode = cLLNode.nextNode
cNode = cNode.preNode
def MemoizeWay(endNode, tailLen, tailTime):
global memo
cNode = endNode
while cNode.preNode != None:
tailLen += 1
tailTime += cities[cNode.preNode.number][cNode.number]
b = memo[cNode.preNode.number].Insert(Path(tailLen, tailTime, cNode.number))
if not b:
break
cNode = cNode.preNode
def main():
global T, cities
n, m, T = [int(s) for s in stdin.readline().split()]
cities = [None] * (n+1)
for i in range(m):
u, v, t = [int(s) for s in stdin.readline().split()]
if cities[u] == None:
cities[u] = {}
if u != n:
cities[u].update({v : t})
global memo
memo = [LinkedList() for i in range(n+1)]
memo[n].Insert(Path(1, 0, None))
stack = []
stack.append(Node(1, 1, 0, None))
while(len(stack) > 0):
city = stack.pop()
if city.number == n:
MemoizeWay(city, 1, 0)
continue
if memo[city.number].rootNode != None:
cNode = memo[city.number].rootNode
while cNode != None:
MemoizeWay(city, cNode.value.wayLen, cNode.value.wayTime)
cNode = cNode.nextNode
continue
if cities[city.number] != None:
for subCity in cities[city.number]:
stack.append(Node( subCity, city.wayLen + 1, city.wayTime + cities[city.number][subCity], city ))
cPath = memo[1].FindBestPath(T).value
stdout.write( "{}\n".format(cPath.wayLen) )
stdout.write( "{} ".format(1) )
while(cPath.nextNode != None):
stdout.write( "{} ".format(cPath.nextNode) )
cPath = memo[cPath.nextNode].FindBestPath(cPath.wayTime).value
main()
|
1475244300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["abdc\na\nb\ndeforces\ncf\nxyzzw"]
|
adbaa266446e6d8d95a6cbc0b83cc7c7
|
NoteThe first test case is explained in the statement.In the second test case, no operations can be performed on $$$s$$$.In the third test case, Initially, $$$s =$$$ "bbbbbbbbbb". After $$$1$$$ operation, $$$s =$$$ "b". In the fourth test case, Initially, $$$s =$$$ "codeforces". After $$$1$$$ operation, $$$s =$$$ "odeforces". After $$$2$$$ operations, $$$s =$$$ "deforces".
|
You are given a string $$$s$$$ consisting of lowercase letters of the English alphabet. You must perform the following algorithm on $$$s$$$: Let $$$x$$$ be the length of the longest prefix of $$$s$$$ which occurs somewhere else in $$$s$$$ as a contiguous substring (the other occurrence may also intersect the prefix). If $$$x = 0$$$, break. Otherwise, remove the first $$$x$$$ characters of $$$s$$$, and repeat. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".For instance, if we perform the algorithm on $$$s =$$$ "abcabdc", Initially, "ab" is the longest prefix that also appears somewhere else as a substring in $$$s$$$, so $$$s =$$$ "cabdc" after $$$1$$$ operation. Then, "c" is the longest prefix that also appears somewhere else as a substring in $$$s$$$, so $$$s =$$$ "abdc" after $$$2$$$ operations. Now $$$x=0$$$ (because there are no non-empty prefixes of "abdc" that also appear somewhere else as a substring in $$$s$$$), so the algorithm terminates. Find the final state of the string after performing the algorithm.
|
For each test case, print a single line containing the string $$$s$$$ after executing the algorithm. It can be shown that such string is non-empty.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. Each line contains a string $$$s$$$. The given strings consist only of lowercase letters of the English alphabet and have lengths between $$$1$$$ and $$$2 \cdot 10^5$$$ inclusive. It is guaranteed that the sum of the lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_102.jsonl
|
9381cf628dd4afece180abe9c3117707
|
256 megabytes
|
["6\nabcabdc\na\nbbbbbbbbbb\ncodeforces\ncffcfccffccfcffcfccfcffccffcfccf\nzyzyzwxxyyxxyyzzyzzxxwzxwywxwzxxyzzw"]
|
PASSED
|
t = int(input())
while (t > 0):
t -= 1
s1 = str(input())
s2 = ""
i = 0
mn = set()
while True:
if (s1[-i-1] not in mn):
s2 = s1[-i-1:]
mn.add(s1[-i-1])
i += 1
if i == len(s1):
break
print(s2)
|
1647764100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["010\n011001010"]
|
fd3fad7de3068889e676e68551c00a0f
|
NoteIn the first test case, the bitstrings 00 and 01 are subsequences of the output string: 010 and 010. Note that 11 is not a subsequence of the output string, but this is not required.In the second test case all three input strings are subsequences of the output string: 011001010, 011001010 and 011001010.
|
A bitstring is a string that contains only the characters 0 and 1.Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length $$$2n$$$. A valid novel for the contest is a bitstring of length at most $$$3n$$$ that contains at least two of the three given strings as subsequences.Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.
|
For each test case, print a single line containing a bitstring of length at most $$$3n$$$ that has at least two of the given bitstrings as subsequences. It can be proven that under the constraints of the problem, such a bitstring always exists. If there are multiple possible answers, you may output any of them.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). Each of the following three lines contains a bitstring of length $$$2n$$$. It is guaranteed that these three strings are pairwise distinct. 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,900 |
train_087.jsonl
|
f7d0d8172376c8ddf483da75a11248a7
|
256 megabytes
|
["2\n1\n00\n11\n01\n3\n011001\n111010\n010001"]
|
PASSED
|
import sys
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO)
LI = lambda : list(map(int, input().split()))
# sys.setrecursionlimit(3*10**5+10)
t = int(input())
for _ in range(t):
n = int(input())
s = [list(map(int, input())) for _ in range(3)]
index = [0,0,0]
l = []
for i in range(3*n):
if max(index)==2*n:
inds = list(range(3))
inds.sort(key=lambda i: index[i])
j = inds[1]
for k in range(index[j], 2*n):
l.append(s[j][k])
break
if s[0][index[0]] + s[1][index[1]] + s[2][index[2]] >= 2:
v = 1
else:
v = 0
l.append(v)
for j in range(3):
if s[j][index[j]]==v:
index[j] += 1
assert len(l)<=3*n
write("".join(map(str, l)))
# break
|
1618583700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["RBRBR\n-1\nBBRRRRBB\nBR"]
|
2e01de6090e862f7f18a47dcbcb3be53
|
NoteThe first test case is considered in the statement.In the second test case, there are no even digits, so it is impossible to form a number from its digits that is divisible by $$$2$$$.In the third test case, each coloring containing at least one red and one black digit is possible, so you can color $$$4$$$ digits in red and $$$4$$$ in black ($$$|4 - 4| = 0$$$, it is impossible to improve the result).In the fourth test case, there is a single desired coloring.
|
It is given a non-negative integer $$$x$$$, the decimal representation of which contains $$$n$$$ digits. You need to color each its digit in red or black, so that the number formed by the red digits is divisible by $$$A$$$, and the number formed by the black digits is divisible by $$$B$$$.At least one digit must be colored in each of two colors. Consider, the count of digits colored in red is $$$r$$$ and the count of digits colored in black is $$$b$$$. Among all possible colorings of the given number $$$x$$$, you need to output any such that the value of $$$|r - b|$$$ is the minimum possible.Note that the number $$$x$$$ and the numbers formed by digits of each color, may contain leading zeros. Example of painting a number for $$$A = 3$$$ and $$$B = 13$$$ The figure above shows an example of painting the number $$$x = 02165$$$ of $$$n = 5$$$ digits for $$$A = 3$$$ and $$$B = 13$$$. The red digits form the number $$$015$$$, which is divisible by $$$3$$$, and the black ones β $$$26$$$, which is divisible by $$$13$$$. Note that the absolute value of the difference between the counts of red and black digits is $$$1$$$, it is impossible to achieve a smaller value.
|
For each test case, output in a separate line: -1 if the desired coloring does not exist; a string $$$s$$$ of $$$n$$$ characters, each of them is a letter 'R' or 'B'. If the $$$i$$$-th digit of the number $$$x$$$ is colored in red, then the $$$i$$$-th character of the string $$$s$$$ must be the letter 'R', otherwise the letter 'B'. The number formed by digits colored red should divisible by $$$A$$$. The number formed by digits colored black should divisible by $$$B$$$. The value $$$|r-b|$$$ should be minimal, where $$$r$$$ is the count of red digits, $$$b$$$ is the count of black digits. If there are many possible answers, print any of them.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) β the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains three integers $$$n$$$, $$$A$$$, $$$B$$$ ($$$2 \le n \le 40$$$, $$$1 \le A, B \le 40$$$). The second line contains a non-negative integer $$$x$$$ containing exactly $$$n$$$ digits and probably containing leading zeroes.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100 |
train_093.jsonl
|
46ccfba2ed8cab9322fc62e5be626f3a
|
256 megabytes
|
["4\n5 3 13\n02165\n4 2 1\n1357\n8 1 1\n12345678\n2 7 9\n90"]
|
PASSED
|
import sys
import io, os
input = sys.stdin.readline
from collections import defaultdict
def main():
t = int(input())
for _ in range(t):
n, a, b = map(int, input().split())
s = list(str(input().rstrip()))
s = [int(c) for c in s]
dp = [-1]*(a*b*(n+1)*(n+1))
dp[0] = 0
def getindex(i, j, ra, rb):
return i*(n+1)*a*b+j*a*b+ra*b+rb
for i, c in enumerate(s):
for j in range(i+1):
for ra in range(a):
for rb in range(b):
idx = getindex(i, j, ra, rb)
if dp[idx] == -1:
continue
#red
nra = (ra*10+c)%a
nidx =getindex(i+1, j+1, nra, rb)
dp[nidx] = idx
#black
nrb = (rb*10+c)%b
nidx =getindex(i+1, j, ra, nrb)
dp[nidx] = idx
bestj = 0
for j in range(1, n+1):
idx = getindex(n, j, 0, 0)
if dp[idx] != -1 and abs(j-(n-j)) < abs(bestj-(n-bestj)):
bestj = j
if bestj == 0:
print(-1)
continue
cur = n
j = bestj
ra = 0
rb = 0
ans = []
while cur > 0:
idx = getindex(cur, j, ra, rb)
pidx = dp[idx]
cur, r = divmod(pidx, (n+1)*a*b)
pj, r = divmod(r, a*b)
ra, rb = divmod(r, b)
if pj == j-1:
ans.append('R')
else:
ans.append('B')
j = pj
ans.reverse()
print(''.join(ans))
if __name__ == '__main__':
main()
|
1634135700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4\n5 3", "0", "0"]
|
2510469c09d7d145078e65de81640ddc
|
NoteIn the first test, one of the transforms might be as follows: $$$39 \to 56 \to 57 \to 62 \to 63$$$. Or more precisely: Pick $$$n = 5$$$. $$$x$$$ is transformed into $$$39 \oplus 31$$$, or $$$56$$$. Increase $$$x$$$ by $$$1$$$, changing its value to $$$57$$$. Pick $$$n = 3$$$. $$$x$$$ is transformed into $$$57 \oplus 7$$$, or $$$62$$$. Increase $$$x$$$ by $$$1$$$, changing its value to $$$63 = 2^6 - 1$$$. In the second and third test, the number already satisfies the goal requirement.
|
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number $$$x$$$. A perfect longcat is a cat with a number equal $$$2^m - 1$$$ for some non-negative integer $$$m$$$. For example, the numbers $$$0$$$, $$$1$$$, $$$3$$$, $$$7$$$, $$$15$$$ and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on $$$x$$$: (Operation A): you select any non-negative integer $$$n$$$ and replace $$$x$$$ with $$$x \oplus (2^n - 1)$$$, with $$$\oplus$$$ being a bitwise XOR operator. (Operation B): replace $$$x$$$ with $$$x + 1$$$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $$$40$$$ operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than $$$40$$$ operations.
|
The first line should contain a single integer $$$t$$$ ($$$0 \le t \le 40$$$)Β β the number of operations to apply. Then for each odd-numbered operation print the corresponding number $$$n_i$$$ in it. That is, print $$$\lceil \frac{t}{2} \rceil$$$ integers $$$n_i$$$ ($$$0 \le n_i \le 30$$$), denoting the replacement $$$x$$$ with $$$x \oplus (2^{n_i} - 1)$$$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.
|
The only line contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_003.jsonl
|
db1e026064c77fad1e42b3310fb6c56f
|
256 megabytes
|
["39", "1", "7"]
|
PASSED
|
from math import log2,log,ceil
def A(x):
# x==2**m => log2(x)==m*log2(2) => log2(x)==m
n=ceil(log2(x))
n=int(n)
kk=2**n-1
return x^kk,n
def B(x):
return x+1
def check(num):
num+=1
mm=log(num)/log(2)
q=int(mm)
if mm-q==0:
return True
return False
t=0
f=True
ans=[]
x=int(input())
for i in range(40):
if check(x):
print(t)
if t!=0:
print(*ans)
break
t+=1
if t%2!=0:
x,n1=A(x)
ans.append(n1)
else:
x=B(x)
|
1556116500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["Bob\nBob\nAlice\nAlice\nAlice\nAlice\nBob\nBob"]
|
9b9b85f84636ebd0f7af8b410d9820f7
|
NoteIn the notes, the cell numbers increase from left to right.In the first testcase for Alice, she has two choices: paint the first and the second cells, or paint the second and the third cells. No matter what choice Alice makes, there will be exactly one blue cell after Alice's move. Bob just needs to paint the blue cell and its neighbour, then every cell will be white and Alice can't make a move. So Bob is the winner.In the second testcase no matter what Alice chooses, Bob can choose to paint the fourth and fifth cells in $$$2$$$ turns.In the third testcase at first, Alice paints the third and the fourth cells. It doesn't matter if Bob paints the first and the second cells or the fifth and sixth cells, as Alice can paint the other two cells.In the fourth testcase at first, Alice paints the second and the third cells. If Bob paints the fifth and the sixth cells or the fourth and the fifth cells, then Alice paints the seventh and the eighth cells. If Bob paints the seventh and the eighth cells, then Alice paints the fifth and the sixth cells.In the fifth Alice chooses the middle two cells at first, then Bob obviously has only two options, whichever variant he chooses, Alice can choose the other one and win.In the eighth no matter what Alice chooses, Bob can choose the other two symmetrical cells.
|
Alice and Bob are playing a game. There are $$$n$$$ cells in a row. Initially each cell is either red or blue. Alice goes first.On each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue cell, and paints that two cells white. The player who cannot make a move loses.Find the winner if both Alice and Bob play optimally.Note that a chosen cell can be white, as long as the other cell satisfies the constraints.
|
For each test case, output the name of the winner on a separate line.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) β the number of test cases. Description of test cases follows. For each test case, the first line contains an integer $$$n$$$ ($$$2 \leq n \leq 5 \cdot 10^5$$$) β the number of cells. The second line contains a string $$$s$$$ of length $$$n$$$ β the initial state of the cells. The $$$i$$$-th cell is red if $$$s_i = $$$ R, blue if $$$s_i = $$$ B. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,600 |
train_089.jsonl
|
09499dc06366b260eab635056821d431
|
256 megabytes
|
["8\n\n3\n\nBRB\n\n5\n\nRRBBB\n\n6\n\nRBRBRB\n\n8\n\nBBRRBRRB\n\n6\n\nBRRBRB\n\n12\n\nRBRBRBRBRRBB\n\n12\n\nRBRBRBRBBBRR\n\n4\n\nRBBR"]
|
PASSED
|
nimv = [1] * 500
def mex(x):
x.sort()
c=0
for i in x:
if i == c:
c += 1
return c
cnts = [4,4,4,24,4,4,4,14]
nimv[:3]= [0,1,1]
cp = 0
ci = 4
for i in range(3,500):
nimv[i]=mex([nimv[i-2]] + [nimv[i-j-3] ^ nimv[j] for j in range(i-2)])
q = nimv[-34*3:]
for i in range(5000):
nimv.extend(q)
for i in range(int(input())):
n=int(input())
a=input()
cv=0
cc = 0
for i in range(n-1):
if (a[i] == 'R' and a[i+1]=='B') or (a[i]=='B' and a[i+1]=='R'):
cc+=1
elif cc:
cv ^= nimv[cc]
cc = 0
cv ^= nimv[cc]
## print(cv)
if (a.count('R') - a.count('B') + (1 if cv else 0)) >0:
print("Alice")
else:
print("Bob")
|
1659276300
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2.5 seconds
|
["0.680000000000000"]
|
9b05933b72dc24d743cb59978f35c8f3
| null |
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
|
Output a real numberΒ β the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10β-β6.
|
The first line contains a single integer n (1ββ€βnββ€β18)Β β the number of participants of the Sith Tournament. Each of the next n lines contains n real numbers, which form a matrix pij (0ββ€βpijββ€β1). Each its element pij is the probability that the i-th participant defeats the j-th in a duel. The elements on the main diagonal pii are equal to zero. For all different i, j the equality pijβ+βpjiβ=β1 holds. All probabilities are given with no more than six decimal places. Jedi Ivan is the number 1 in the list of the participants.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200 |
train_008.jsonl
|
21239c08c39f13a58961faf8ad7cba0e
|
256 megabytes
|
["3\n0.0 0.5 0.8\n0.5 0.0 0.4\n0.2 0.6 0.0"]
|
PASSED
|
import math
import sys
n=int(raw_input())
A=[]
#print "hi"
#sys.stdout.flush()
for j in range(n):
A+=[[float(x) for x in raw_input().split()]]
#print "hi"
while(True):
#print n
#print A
if n==1:
print "1.0"
break
if n==2:
print A[0][1]
break
M=0
j0=1
for j in range(1,n):
if A[0][j]>M:
j0=j
M=A[0][j]
B=[]
for i in range(n):
if i==j0:
continue
B+=[[]]
for j in range(n):
if j==j0:
continue
if i!=0 and j!=0:
B[-1]+=[A[i][j]]
elif i==0 and j==0:
B[-1]+=[0]
elif i==0 and j!=0:
B[-1]+=[A[0][j]*A[j][j0]+A[0][j0]*A[j0][j]]
elif i!=0 and j==0:
B[-1]+=[A[j][0]*A[j][j0]+A[j0][0]*A[j0][j]]
A=B
n-=1
|
1465834200
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["6", "8", "4"]
|
3f3a013cedaaf8cbee0a74a4ed50f09d
|
NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(2, 3)$$$; $$$(5, 6)$$$; $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(6, 8)$$$; $$$(2, 3)$$$; $$$(1, 4)$$$; $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $$$(1, 2)$$$; $$$(6, 7)$$$. So the answer is $$$4$$$.
|
International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.
|
Print one integer β the maximum number of the boxes Polycarp can give as gifts.
|
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) β the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_015.jsonl
|
a2d7d0d5cfbbaef286670a8539128300
|
256 megabytes
|
["7 2\n1 2 2 3 2 4 10", "8 2\n1 2 2 3 2 4 6 10", "7 3\n1 2 2 3 2 4 5"]
|
PASSED
|
n, k = map(int, input().split(' '))
gifts = sorted(list(map(lambda cnd: int(cnd) % k, input().split())))
equal_classes = [0] * (k)
etalon = gifts[0]
for g in gifts:
if g == etalon:
equal_classes[g] += 1
else:
etalon = g
equal_classes[g] += 1
ans = equal_classes[0] - equal_classes[0] % 2
if (k - 1) % 2 == 1:
equal_classes[k//2] = equal_classes[k//2] - equal_classes[k//2] % 2
for i in range(1, k):
ans += min(equal_classes[i], equal_classes[k - i])
print(ans)
|
1551971100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2", "1"]
|
1b2a2c8afcaf16b4055002a9511c6f23
|
NoteIn the first example Pavel can change the permutation to 4,β3,β1,β2.In the second example Pavel can change any element of b to 1.
|
Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.Pavel has a plan: a permutation p and a sequence b1,βb2,β...,βbn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (kββ₯β2n), so that after k seconds each skewer visits each of the 2n placements.It can be shown that some suitable pair of permutation p and sequence b exists for any n.
|
Print single integerΒ β the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.
|
The first line contain the integer n (1ββ€βnββ€β2Β·105)Β β the number of skewers. The second line contains a sequence of integers p1,βp2,β...,βpn (1ββ€βpiββ€βn)Β β the permutation, according to which Pavel wants to move the skewers. The third line contains a sequence b1,βb2,β...,βbn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_039.jsonl
|
935797494e157cb3f664fb8fe267a91b
|
256 megabytes
|
["4\n4 3 2 1\n0 1 1 1", "3\n2 3 1\n0 0 0"]
|
PASSED
|
import sys
sys.setrecursionlimit(10 ** 9)
n = int(input())
p = list(map(int, input().split()))
b = list(map(int, input().split()))
used = [False] * n
comp = 0
for i in range(n):
if not used[i]:
u = i
while True:
used[u] = True
v = p[u] - 1
if not used[v]:
u = v
else:
break
comp += 1
if comp == 1:
ans = 0
else:
ans = comp
ed = 0
for i in range(n):
if b[i]:
ed += 1
if not ed % 2:
ans += 1
print(ans)
|
1485108900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["Yes", "Yes", "No", "No", "No"]
|
c5ec8b18c39720098f6ac2dbc0ddd4f4
|
NoteIn the first example $$$3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$$$. Number $$$24$$$ is divisible by $$$4! = 24$$$.In the second example $$$3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$$$, is divisible by $$$3! = 6$$$.In the third example $$$7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$$$. It is easy to prove that this number is not divisible by $$$8!$$$.
|
You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$Β β the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.
|
In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.
|
The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$)Β β elements of given array.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600 |
train_100.jsonl
|
c3236abe16ad94ae830b7995b9ce46f9
|
256 megabytes
|
["6 4\n3 2 2 2 3 3", "8 3\n3 2 2 2 2 2 1 1", "7 8\n7 7 7 7 7 7 7", "10 5\n4 3 2 1 4 3 2 4 3 4", "2 500000\n499999 499999"]
|
PASSED
|
n,val=map(int,input().split())
if val==1:
print('Yes')
else:
numeri=list(map(int,input().split()))
m=min(numeri)
occorrenze=[0]*(val-m+1)
for i in numeri:
occorrenze[i-m]=occorrenze[i-m]+1
for j in range(len(occorrenze)-1):
if occorrenze[j]%(j+m+1)!=0:
print('No')
quit()
elif j<len(occorrenze)-1:
occorrenze[j+1]=occorrenze[j+1]+(occorrenze[j]//(j+m+1))
print('Yes')
|
1666511400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["5", "4"]
|
a39b2ed9165d4aa3dc8dd60bf0ad47f3
|
NoteOn the first example, Kuro can choose these pairs: $$$(1, 2)$$$: his route would be $$$1 \rightarrow 2$$$, $$$(2, 3)$$$: his route would be $$$2 \rightarrow 3$$$, $$$(3, 2)$$$: his route would be $$$3 \rightarrow 2$$$, $$$(2, 1)$$$: his route would be $$$2 \rightarrow 1$$$, $$$(3, 1)$$$: his route would be $$$3 \rightarrow 2 \rightarrow 1$$$. Kuro can't choose pair $$$(1, 3)$$$ since his walking route would be $$$1 \rightarrow 2 \rightarrow 3$$$, in which Kuro visits town $$$1$$$ (Flowrisa) and then visits town $$$3$$$ (Beetopia), which is not allowed (note that pair $$$(3, 1)$$$ is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).On the second example, Kuro can choose the following pairs: $$$(1, 2)$$$: his route would be $$$1 \rightarrow 2$$$, $$$(2, 1)$$$: his route would be $$$2 \rightarrow 1$$$, $$$(3, 2)$$$: his route would be $$$3 \rightarrow 1 \rightarrow 2$$$, $$$(3, 1)$$$: his route would be $$$3 \rightarrow 1$$$.
|
Kuro is living in a country called Uberland, consisting of $$$n$$$ towns, numbered from $$$1$$$ to $$$n$$$, and $$$n - 1$$$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $$$a$$$ and $$$b$$$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $$$(u, v)$$$ ($$$u \neq v$$$) and walk from $$$u$$$ using the shortest path to $$$v$$$ (note that $$$(u, v)$$$ is considered to be different from $$$(v, u)$$$).Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $$$x$$$) and Beetopia (denoted with the index $$$y$$$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $$$(u, v)$$$ if on the path from $$$u$$$ to $$$v$$$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuroβs body and sting him.Kuro wants to know how many pair of city $$$(u, v)$$$ he can take as his route. Since heβs not really bright, he asked you to help him with this problem.
|
A single integer resembles the number of pair of towns $$$(u, v)$$$ that Kuro can use as his walking route.
|
The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$, $$$1 \leq x, y \leq n$$$, $$$x \ne y$$$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively. $$$n - 1$$$ lines follow, each line contains two integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq n$$$, $$$a \ne b$$$), describes a road connecting two towns $$$a$$$ and $$$b$$$. It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_030.jsonl
|
d95a7a522835b5439ceb5f508b43471e
|
256 megabytes
|
["3 1 3\n1 2\n2 3", "3 1 3\n1 2\n1 3"]
|
PASSED
|
from collections import defaultdict
n,x,y = list(map(int,input().split()))
graph = defaultdict(list)
vis = [False for i in range(n+1)]
mat = [False for i in range(n+1)]
subtree = [0 for i in range(n+1)]
for i in range(n-1):
u,v = list(map(int,input().split()))
graph[u].append(v)
graph[v].append(u)
q = []
cur = 0
for v in graph[x]:
if v!=y:
q.append([v,v])
else:
cur = v
vis[x] = 1
while q!=[]:
temp = q.pop()
u,v = temp
vis[u] = True
subtree[v]+=1
for node in graph[u]:
if vis[node]==False:
if node!=y:
q.append([node,v])
else:
cur = v
val = sum(subtree)
val1 = (val+1-subtree[cur])
val2 = n-(sum(subtree)+1)
val = val1*val2
print(n*(n-1)-val)
|
1526308500
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["dbcadabcdbcadabc", "aaaaa"]
|
87f64b4d5baca4b80162ae6075110b00
|
NoteIn the first test, it is optimal to make one duplication: "dbcadabc" $$$\to$$$ "dbcadabcdbcadabc".In the second test it is optimal to delete the last $$$3$$$ characters, then duplicate the string $$$3$$$ times, then delete the last $$$3$$$ characters to make the string have length $$$k$$$."abcd" $$$\to$$$ "abc" $$$\to$$$ "ab" $$$\to$$$ "a" $$$\to$$$ "aa" $$$\to$$$ "aaaa" $$$\to$$$ "aaaaaaaa" $$$\to$$$ "aaaaaaa" $$$\to$$$ "aaaaaa" $$$\to$$$ "aaaaa".
|
This is the easy version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it: Delete the last character of the string. Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$; In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
Print the lexicographically smallest string of length $$$k$$$ that can be obtained by doing the operations on string $$$s$$$.
|
The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5000$$$) β the length of the original string $$$s$$$ and the length of the desired string. The second line contains the string $$$s$$$, consisting of $$$n$$$ lowercase English letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_084.jsonl
|
c6a3c2f86764a668eff2348ce7c8057f
|
256 megabytes
|
["8 16\ndbcadabc", "4 5\nabcd"]
|
PASSED
|
import sys
data1 = sys.stdin.read()
import copy
import math
data = data1.split("\n")
f1 = data[0].split(' ')
n = int(f1[0])
k = f1[1]
string1 = list(data[1])
string1.append(" ")
final = list()
def check():
for t in range(0, n - 1):
if t == n-1:
return t
if ord(string1[t]) >= ord(string1[t + 1]) :
final.extend(string1[t])
else:
return t
return n-1
##already get initial array
def check1(x):
flag = True
if x == 0:
final.append(string1[0])
return final
for t in range(x, n):
if flag == False:
if p1 >= int(n):
return final
p1 += 1
t = copy.copy(p1)
if ord(string1[0]) > ord(string1[t]):
final.extend(string1[t])
elif ord(string1[0]) == ord(string1[t]):
p2 = 0
while ord(string1[p2]) == ord(string1[t]):
p2+=1
t+=1
p1 = copy.copy(t)
if(string1[p2] > string1[t]):
final.extend(string1[t - p2:t+1])
flag = False
else:
return final
#compare the second number
elif ord(string1[0]) < ord(string1[t]):
return final
return final
p3 = check1(check())
if ' ' in p3:
p3.remove(' ')
if len(p3) > 1:
if p3[0]==p3[len(p3)-1]:
p5 = 0
p6 = copy.copy(p3[0])
while p3[p5] == p6 and p3[len(p3)-1-p5]== p6 and p5<math.ceil(len(p3)/2):
p5 +=1
p3 = p3[0:len(p3)-p5]
p3 = p3*math.ceil(int(k)/len(p3))
p4 = ''.join(p3[0:int(k)])
print(p4)
|
1624026900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["FHTAGN!", "NO"]
|
4ecbfc792da55f458342c6eff2d5da5a
|
NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., vβ-β1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and nβ-β1 edges (nβ>β0).A rooted tree is a tree where one vertex is selected to be the root.
|
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.
|
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
|
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1ββ€βnββ€β100, 0ββ€βmββ€β). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1ββ€βx,βyββ€βn,βxββ βy). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_034.jsonl
|
77edf9b292ae441dd31c3b8416860ee6
|
256 megabytes
|
["6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4", "6 5\n5 6\n4 6\n3 1\n5 1\n1 2"]
|
PASSED
|
def findSet(u):
if parent[u] != u:
parent[u] = findSet(parent[u])
return parent[u]
def unionSet(u, v):
up = findSet(u)
vp = findSet(v)
if up == vp:
return
if ranks[up] > ranks[vp]:
parent[vp] = up
elif ranks[up] < ranks[vp]:
parent[up] = vp
else:
parent[up] = vp
ranks[vp] += 1
n, m = list(map(int, input("").split()))
parent = [i for i in range(n+1)]
ranks = [0 for i in range(n+1)]
for _ in range(m):
u,v = tuple(map(int, input("").split()))
unionSet(u,v)
if n != m:
print('NO')
else:
cnt = 0
for i in range(1,n+1):
if i == parent[i]: # co 1 tap hop khi co duy nhat 1 phan tu co parent la chinh no
cnt += 1
if cnt > 1:
break
# print(ranks)
if cnt == 1:
print('FHTAGN!')
else:
print('NO')
|
1312714800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 1 2 2 3 4 5 6", "0 1 0 1 1 1 1 2 2 2"]
|
c5f137635a6c0d1c96b83de049e7414a
|
NoteLet's look at the first example:Ways to reach the point $$$1$$$: $$$[0, 1]$$$;Ways to reach the point $$$2$$$: $$$[0, 2]$$$;Ways to reach the point $$$3$$$: $$$[0, 1, 3]$$$, $$$[0, 3]$$$;Ways to reach the point $$$4$$$: $$$[0, 2, 4]$$$, $$$[0, 4]$$$;Ways to reach the point $$$5$$$: $$$[0, 1, 5]$$$, $$$[0, 3, 5]$$$, $$$[0, 5]$$$;Ways to reach the point $$$6$$$: $$$[0, 1, 3, 6]$$$, $$$[0, 2, 6]$$$, $$$[0, 4, 6]$$$, $$$[0, 6]$$$;Ways to reach the point $$$7$$$: $$$[0, 2, 4, 7]$$$, $$$[0, 1, 7]$$$, $$$[0, 3, 7]$$$, $$$[0, 5, 7]$$$, $$$[0, 7]$$$;Ways to reach the point $$$8$$$: $$$[0, 3, 5, 8]$$$, $$$[0, 1, 5, 8]$$$, $$$[0, 2, 8]$$$, $$$[0, 4, 8]$$$, $$$[0, 6, 8]$$$, $$$[0, 8]$$$.
|
There is a chip on the coordinate line. Initially, the chip is located at the point $$$0$$$. You can perform any number of moves; each move increases the coordinate of the chip by some positive integer (which is called the length of the move). The length of the first move you make should be divisible by $$$k$$$, the length of the second moveΒ β by $$$k+1$$$, the thirdΒ β by $$$k+2$$$, and so on.For example, if $$$k=2$$$, then the sequence of moves may look like this: $$$0 \rightarrow 4 \rightarrow 7 \rightarrow 19 \rightarrow 44$$$, because $$$4 - 0 = 4$$$ is divisible by $$$2 = k$$$, $$$7 - 4 = 3$$$ is divisible by $$$3 = k + 1$$$, $$$19 - 7 = 12$$$ is divisible by $$$4 = k + 2$$$, $$$44 - 19 = 25$$$ is divisible by $$$5 = k + 3$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to count the number of ways to reach the point $$$x$$$, starting from $$$0$$$, for every $$$x \in [1, n]$$$. The number of ways can be very large, so print it modulo $$$998244353$$$. Two ways are considered different if they differ as sets of visited positions.
|
Print $$$n$$$ integersΒ β the number of ways to reach the point $$$x$$$, starting from $$$0$$$, for every $$$x \in [1, n]$$$, taken modulo $$$998244353$$$.
|
The first (and only) line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_109.jsonl
|
913885b607a5d73af864fc85a2f9c44d
|
256 megabytes
|
["8 1", "10 2"]
|
PASSED
|
n,k=map(int,input().split());M=998244353
f,z=[1]+[0]*n,[0]*(n+1);l=0
while l<=n-k:
s=[0]*k
for i in range(l,n+1):
j=i%k
s[j],f[i],z[i]=(s[j]+f[i])%M,s[j],(z[i]+s[j])%M
l+=k;k+=1
print(*z[1:])
|
1659623700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nNO"]
|
6cebf9af5cfbb949f22e8b336bf07044
|
NoteThe given test has three numbers. The first number 4 has exactly three divisors β 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".
|
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not.
|
Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Π’-prime, and "NO" (without the quotes), if it isn't.
|
The first line contains a single positive integer, n (1ββ€βnββ€β105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1ββ€βxiββ€β1012). Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is advised to use the cin, cout streams or the %I64d specifier.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_001.jsonl
|
d21fe65e3b4a0c1ee1af187a728f3356
|
256 megabytes
|
["3\n4 5 6"]
|
PASSED
|
from math import sqrt
n = int(input())
s = [int(i) for i in input().split()]
d = [1]*1000002
e = set()
for i in range(2,1000002):
if d[i]:
e.add(i**2)
for j in range(i**2,1000002,i):
d[j]=0
for i in range(n):
if s[i] in e:
print("YES")
else:
print("NO")
|
1349105400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["2\n6\n-1\n7"]
|
3b158306d335459ff55dcf29e46010e8
|
NoteIn the first example query you can choose the price $$$B=2$$$. It is easy to see that the difference between each old price and each new price $$$B=2$$$ is no more than $$$1$$$.In the second example query you can choose the price $$$B=6$$$ and then all the differences between old and new price $$$B=6$$$ will be no more than $$$2$$$.In the third example query you cannot choose any suitable price $$$B$$$. For any value $$$B$$$ at least one condition out of two will be violated: $$$|1-B| \le 2$$$, $$$|6-B| \le 2$$$.In the fourth example query all values $$$B$$$ between $$$1$$$ and $$$7$$$ are valid. But the maximum is $$$7$$$, so it's the answer.
|
There are $$$n$$$ products in the shop. The price of the $$$i$$$-th product is $$$a_i$$$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product $$$i$$$ in such a way that the difference between the old price of this product $$$a_i$$$ and the new price $$$b_i$$$ is at most $$$k$$$. In other words, the condition $$$|a_i - b_i| \le k$$$ should be satisfied ($$$|x|$$$ is the absolute value of $$$x$$$).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price $$$b_i$$$ of each product $$$i$$$ should be positive (i.e. $$$b_i > 0$$$ should be satisfied for all $$$i$$$ from $$$1$$$ to $$$n$$$).Your task is to find out the maximum possible equal price $$$B$$$ of all productts with the restriction that for all products the condiion $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the same new price of all products) or report that it is impossible to find such price $$$B$$$.Note that the chosen price $$$B$$$ should be integer.You should answer $$$q$$$ independent queries.
|
Print $$$q$$$ integers, where the $$$i$$$-th integer is the answer $$$B$$$ on the $$$i$$$-th query. If it is impossible to equalize prices of all given products with restriction that for all products the condition $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.
|
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) β the number of queries. Each query is presented by two lines. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100, 1 \le k \le 10^8$$$) β the number of products and the value $$$k$$$. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the price of the $$$i$$$-th product.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_024.jsonl
|
c32efb5eb4a151a95f71c1bc05a5dd6f
|
256 megabytes
|
["4\n5 1\n1 1 2 3 1\n4 2\n6 4 8 5\n2 2\n1 6\n3 5\n5 2 5"]
|
PASSED
|
z=input
from math import *
for _ in range(int(z())):
n,k=map(int,z().split())
l=sorted(list((map(int,z().split()))))
c,m,n=0,max(l),len(l)
if k>=2 or n>=0:
if l[-1]-l[0]>k*2:print(-1)
else:print(l[0]+k)
continue
for i in range(m+k,0,-1):
d=0
for j in l:
x=abs(i-j)
if x<=k:
d+=1
if d==n:
print(i)
c=1
break
if x>k:
break
if c==1:
break
if c==0:
print(-1)
|
1561559700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3"]
|
0c5ae761b046c021a25b706644f0d3cd
| null |
A sequence a0,βa1,β...,βatβ-β1 is called increasing if aiβ-β1β<βai for each i:β0β<βiβ<βt.You are given a sequence b0,βb1,β...,βbnβ-β1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?
|
Output the minimal number of moves needed to make the sequence increasing.
|
The first line of the input contains two integer numbers n and d (2ββ€βnββ€β2000,β1ββ€βdββ€β106). The second line contains space separated sequence b0,βb1,β...,βbnβ-β1 (1ββ€βbiββ€β106).
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_009.jsonl
|
f415bd9e646f999f2c360181ccbacf56
|
64 megabytes
|
["4 2\n1 3 3 2"]
|
PASSED
|
I=lambda:map(int,input().split())
n,d=I()
a=*I(),
x=a[0]
r=0
for y in a[1:]:
z=0--(x+1-y)//d
if z>=0:
r+=z
y+=z*d
x=y
print(r)
|
1272294000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["23", "12"]
|
ebb9e236b6370a9cba9ffcd77fe4c97e
|
NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.
|
Roy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.
|
Print a single integer, the minimum cost way to solve the problem.
|
The first line will contain an integer n (1ββ€βnββ€β300β000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1ββ€βpiββ€β109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_074.jsonl
|
d81597db55642034bb306c93a41befcf
|
256 megabytes
|
["4\n1 G\n5 R\n10 B\n15 G", "4\n1 G\n2 R\n3 B\n10 G"]
|
PASSED
|
#! /usr/bin/env python3
#------------------------------------------------
# Author: krishna
# Created: Fri Dec 29 23:04:38 IST 2017
# File Name: f.py
# USAGE:
# f.py
# Description:
#
#------------------------------------------------
import sys
n = int(sys.stdin.readline().rstrip())
locations = {
'R' : [],
'G' : [],
'B' : []
}
for i in range(n):
(x, c) = sys.stdin.readline().rstrip().split()
locations[c].append(int(x))
# for c in locations.keys():
# locations[c].sort()
def solve(locations):
count = 0
rPtr = 0
bPtr = 0
gPtr = 0
if (len(locations['G']) == 0):
if (len(locations['R'])):
count += locations['R'][-1] - locations['R'][0]
if (len(locations['B'])):
count += locations['B'][-1] - locations['B'][0]
return count
while (len(locations['G']) > gPtr):
# Eat predecessors
if (
(len(locations['R']) > rPtr)
and (locations['G'][gPtr] > locations['R'][rPtr])
):
count += locations['G'][gPtr] - locations['R'][rPtr]
while (
(len(locations['R']) > rPtr)
and (locations['G'][gPtr] > locations['R'][rPtr])
):
rPtr += 1
# Eat predecessors
if (
(len(locations['B']) > bPtr)
and (locations['G'][gPtr] > locations['B'][bPtr])
):
count += locations['G'][gPtr] - locations['B'][bPtr]
while (
(len(locations['B']) > bPtr)
and (locations['G'][gPtr] > locations['B'][bPtr])
):
bPtr += 1
# Eat last successors
if (len(locations['G']) == (gPtr + 1)):
if (len(locations['R']) > rPtr):
count += locations['R'][-1] - locations['G'][gPtr]
if (len(locations['B']) > bPtr):
count += locations['B'][-1] - locations['G'][gPtr]
return count
# Calc intervels
if (len(locations['G']) > (gPtr + 1)):
prevR = locations['G'][gPtr]
maxRd = 0
while (len(locations['R']) > rPtr):
if (locations['R'][rPtr] < locations['G'][gPtr + 1]):
maxRd = max(maxRd, locations['R'][rPtr] - prevR)
prevR = locations['R'][rPtr]
rPtr += 1
else:
break
maxRd = max(maxRd, locations['G'][gPtr + 1] - prevR)
prevB = locations['G'][gPtr]
maxBd = 0
while (len(locations['B']) > bPtr):
if (locations['B'][bPtr] < locations['G'][gPtr + 1]):
maxBd = max(maxBd, locations['B'][bPtr] - prevB)
prevB = locations['B'][bPtr]
bPtr += 1
else:
break
maxBd = max(maxBd, locations['G'][gPtr + 1] - prevB)
count += min(
2 * (locations['G'][gPtr + 1] - locations['G'][gPtr]),
(3 * (locations['G'][gPtr + 1] - locations['G'][gPtr])) - maxRd - maxBd
)
gPtr += 1
return count
print(solve(locations))
|
1514562000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["4\n4\n1\n1"]
|
f7f1d57921fe7b7a697967dcfc8f0169
|
NoteIn the first test battle points for each ant are vβ=β[4,β0,β2,β0,β2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are vβ=β[0,β2,β0,β2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are vβ=β[2,β0,β2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are vβ=β[0,β1], so ant number 5 is freed. Mole eats the ant 4.
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1ββ€βiββ€βn) has a strength si.In order to make his dinner more interesting, Mole organizes a version of Β«Hunger GamesΒ» for the ants. He chooses two numbers l and r (1ββ€βlββ€βrββ€βn) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if viβ=βrβ-βl, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li,βri] and asks for each of them how many ants is he going to eat if those ants fight.
|
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li,βri].
|
The first line contains one integer n (1ββ€βnββ€β105), the size of the ant colony. The second line contains n integers s1,βs2,β...,βsn (1ββ€βsiββ€β109), the strengths of the ants. The third line contains one integer t (1ββ€βtββ€β105), the number of test cases. Each of the next t lines contains two integers li and ri (1ββ€βliββ€βriββ€βn), describing one query.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_062.jsonl
|
da2a4a4e23a6d99ca26015529c1e202b
|
256 megabytes
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
PASSED
|
import sys
range = xrange
# n log n time and memory precalc,
# then answers queries in O(1) time
class Queries:
def __init__(self, A, f = lambda a,b: a + b, max_d = float('inf')):
self.f = f
self.lists = [A]
n = len(A)
for d in range(1, min(n.bit_length(), max_d + 1)):
tmp = list(A)
self.lists.append(tmp)
x = (1 << d) + 1
jump = x + 1
I = (1 << d + 1) - 1
while x < n:
tmp[x] = f(tmp[x - 1], tmp[x])
tmp[x ^ I] = f(tmp[x ^ I], tmp[x - 1 ^ I])
x += 1 if ~x & I else jump
if x == n:
while x & I:
tmp[x ^ I] = f(tmp[x ^ I], tmp[x - 1 ^ I])
x += 1
def __call__(self, a, b):
tmp = self.lists[(a ^ b - 1).bit_length() - 1]
return self.f(tmp[a], tmp[b - 1]) if a - b + 1 else self.lists[0][a]
# n log log n time and memory precalc
# then answers queries in O(1) time
class Queries2:
def __init__(self, A, f = lambda a,b: a + b):
self.f = f
self.c = Queries(A, f, 3).__call__
n = len(A)
self.p = prefix = list(A)
self.s = suffix = list(A)
i = 17
while i < n:
prefix[i] = f(prefix[i - 1], prefix[i])
i += 1 + (~i & 15 == 0)
i = n - 2 if n - 2 & 15 != 15 else n - 3
while i >= 0:
suffix[i] = f(suffix[i], suffix[i + 1])
i -= 1 + (i & 15 == 0)
self.k = Queries(suffix[:-16: 16], f).__call__
def __call__(self, a, b):
if a ^ b - 1 < 16:
return self.c(a, b)
return self.f(self.f(self.s[a], self.k((a >> 4) + 1, b - 1 >> 4)) if (a >> 4) + 1 < b - 1 >> 4 else self.s[a], self.p[b - 1])
def gcd(a,b):
while a:
a,b = b % a, a
return b
def merge((val1, count1), (val2, count2)):
g = gcd(val1, val2)
if g == val1 == val2:
return g, count1 + count2
elif g == val1:
return g, count1
elif g == val2:
return g, count2
else:
return g, 0
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
S = inp[ii: ii + n]; ii += n
RQ = Queries2([(s,1) for s in S], merge)
t = inp[ii]; ii += 1
out = []
for _ in range(t):
l = inp[ii] - 1; ii += 1
r = inp[ii]; ii += 1
out.append(r - l - RQ(l,r)[1])
print '\n'.join(str(x) for x in out)
|
1412609400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["-2 -4 3\n1 1 1 1 1\n-2 -4 7 -6 4\n-9 -7 -4 2 1 -3 -9 -4 -5\n4 -1 -9 -4 -8 -9 -5 -1 9"]
|
d07ae42b7902ba3a49cf4463248710ea
|
NoteIn the first test case, the difference $$$(-4) - (-2) = -2$$$ is non-positive, while the difference $$$3 - (-4) = 7$$$ is non-negative.In the second test case, we don't have to flip any signs. All $$$4$$$ differences are equal to $$$0$$$, which is both non-positive and non-negative.In the third test case, $$$7 - (-4)$$$ and $$$4 - (-6)$$$ are non-negative, while $$$(-4) - (-2)$$$ and $$$(-6) - 7$$$ are non-positive.
|
You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are greater than or equal to $$$0$$$. At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.
|
For each test case, print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$, corresponding to the integers after flipping signs. $$$b_i$$$ has to be equal to either $$$a_i$$$ or $$$-a_i$$$, and of the adjacent differences $$$b_{i + 1} - b_i$$$ for $$$i = 1, \dots, n - 1$$$, at least $$$\frac{n - 1}{2}$$$ should be non-negative and at least $$$\frac{n - 1}{2}$$$ should be non-positive. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) Β β the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n \le 99$$$, $$$n$$$ is odd) Β β the number of integers given to you. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) Β β the numbers themselves. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_000.jsonl
|
a9cea3a4e9db46d684a3672e30e919a9
|
256 megabytes
|
["5\n3\n-2 4 3\n5\n1 1 1 1 1\n5\n-2 4 7 -6 4\n9\n9 7 -4 -2 1 -3 9 -4 -5\n9\n-4 1 9 4 8 9 5 1 -9"]
|
PASSED
|
for _ in range(int(input())):
t=int(input())
l=[int(x) for x in input().split()]
for i in range(t):
if i%2==0 and l[i]<0:
l[i]=0-l[i]
elif i%2!=0 and l[i]>0:
l[i]=0-l[i]
else:k=0
print(*l)
|
1593873900
|
[
"math"
] |
[
0,
0,
0,
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.