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
sequencelengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
sequencelengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 seconds | ["3\n1\n1\n1\n0", "3\n2\n2\n1\n0", "1\n1\n1\n1"] | 23fc2595e2813d0817e3cc0f1bb22eae | NoteConsider the first example:On the first day, student $$$3$$$ leaves their club. Now, the remaining students are $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$. We can select students $$$1$$$, $$$2$$$ and $$$4$$$ to get maximum possible strength, which is $$$3$$$. Note, that we can't select students $$$1$$$, $$$2$$$ and $$$5$$$, as students $$$2$$$ and $$$5$$$ belong to the same club. Also, we can't select students $$$1$$$, $$$3$$$ and $$$4$$$, since student $$$3$$$ has left their club.On the second day, student $$$2$$$ leaves their club. Now, the remaining students are $$$1$$$, $$$4$$$ and $$$5$$$. We can select students $$$1$$$, $$$4$$$ and $$$5$$$ to get maximum possible strength, which is $$$1$$$.On the third day, the remaining students are $$$1$$$ and $$$5$$$. We can select students $$$1$$$ and $$$5$$$ to get maximum possible strength, which is $$$1$$$.On the fourth day, the remaining student is $$$1$$$. We can select student $$$1$$$ to get maximum possible strength, which is $$$1$$$. On the fifth day, no club has students and so the maximum possible strength is $$$0$$$. | There are $$$n$$$ students and $$$m$$$ clubs in a college. The clubs are numbered from $$$1$$$ to $$$m$$$. Each student has a potential $$$p_i$$$ and is a member of the club with index $$$c_i$$$. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next $$$d$$$ days. There is a coding competition every day in the technical fest. Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming $$$d$$$ days. Thus, every day the director chooses such team, that the team strength is maximized.The mex of the multiset $$$S$$$ is the smallest non-negative integer that is not present in $$$S$$$. For example, the mex of the $$$\{0, 1, 1, 2, 4, 5, 9\}$$$ is $$$3$$$, the mex of $$$\{1, 2, 3\}$$$ is $$$0$$$ and the mex of $$$\varnothing$$$ (empty set) is $$$0$$$. | For each of the $$$d$$$ days, print the maximum possible strength of the team on that day. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq m \leq n \leq 5000$$$), the number of students and the number of clubs in college. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$0 \leq p_i < 5000$$$), where $$$p_i$$$ is the potential of the $$$i$$$-th student. The third line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq m$$$), which means that $$$i$$$-th student is initially a member of the club with index $$$c_i$$$. The fourth line contains an integer $$$d$$$ ($$$1 \leq d \leq n$$$), number of days for which the director wants to know the maximum possible strength of the team. Each of the next $$$d$$$ lines contains an integer $$$k_i$$$ ($$$1 \leq k_i \leq n$$$), which means that $$$k_i$$$-th student lefts their club on the $$$i$$$-th day. It is guaranteed, that the $$$k_i$$$-th student has not left their club earlier. | standard output | standard input | PyPy 3 | Python | 2,400 | train_082.jsonl | 5f77f52cc8eff6bf72afffb927cae52a | 256 megabytes | ["5 3\n0 1 2 2 0\n1 2 2 3 2\n5\n3\n2\n4\n5\n1", "5 3\n0 1 2 2 1\n1 3 2 3 2\n5\n4\n2\n3\n5\n1", "5 5\n0 1 2 4 5\n1 2 3 4 5\n4\n2\n3\n5\n4"] | PASSED | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
d = int(input())
disable = [False] * n
base = 5001
ds = [int(input())-1 for _ in range(d)]
for ele in ds:
disable[ele] = True
# Create Graph
childs = [[] for i in range(base+m+1)]
for idx, (i, j) in enumerate(zip(p, c)):
if not disable[idx]:
childs[i].append(base+j)
# dfs
# alternative path for finding maximum cardinality
vis = [False]*(base+m+1)
matching = [-1]*(base+m+1)
def dfs(num):
for child in childs[num]:
if not vis[child]:
vis[child] = True
if matching[child] == -1 or dfs(matching[child]):
matching[child] = num
return True
return False
ans = []
mex = 0
for idx in range(d-1, -1, -1):
while True:
vis = [False]*(base+m+1)
if not dfs(mex):
break
mex += 1
# Add edge
ans.append(mex)
childs[p[ds[idx]]].append(base+c[ds[idx]])
print("\n".join([str(a) for a in reversed(ans)])) | 1553182500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3\n4"] | 623a373709e4c4223fbbb9a320f307b1 | null | There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows: $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$. | For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,700 | train_108.jsonl | aaf046dd81af18c0201e58d7a3d53e74 | 256 megabytes | ["2\n\n1 1 3 2\n\n1 1\n\n1 1\n\n2 2 2 3\n\n2 1\n\n1 1\n\n2 2"] | PASSED | columns = []
rows = []
for _ in range(int(input())):
n, m, k, q = map(int, input().split())
columns += [False] * max(0, n - len(columns))
rows += [False] * max(0, m - len(rows))
ls = [None] * q
for i in range(q):
x, y = map(int, input().split())
ls[i] = (x - 1, y - 1)
cf = 0
rf = 0
r = 1
for x, y in ls[::-1]:
fl = False
if not columns[x]:
columns[x] = True
cf += 1
fl = True
if not rows[y]:
rows[y] = True
rf += 1
fl = True
if fl:
r = r * k % 998244353
if cf == n or rf == m:
break
for x, y in ls:
columns[x] = False
rows[y] = False
print(r) | 1645540500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["5", "0"] | 1503f0379bf8d7f25c191ddea9278842 | NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0. | In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not. Figure 1 Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections. | Output consists of a single line containing the number of points where the watchtower can be set up. | The first line of the test case will consist of the number of vertices n (3 ≤ n ≤ 1000). Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≤ xi, yi ≤ 106) separated by a space. The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2). | standard output | standard input | Python 2 | Python | 2,500 | train_028.jsonl | e24f60e69db59437cd121671002f3be1 | 256 megabytes | ["5\n4 8\n8 8\n9 4\n4 0\n0 4", "5\n4 8\n5 8\n5 4\n7 4\n2 2"] | PASSED | from math import floor,ceil
n = input()
x,y = zip(*[map(int,raw_input().split()) for _ in xrange(n)])
nr,mr=min(x[:2]),max(x[:2])
for j in xrange(3,n):
i = j-1
dx = x[j]-x[i]
dy = y[j]-y[i]
t = 1.*(y[0]-y[i])*dx;
r = t/dy+x[i] if dy else 1e9
if t-dy*(mr-x[i])>0 and r<mr: mr=r;
if t-dy*(nr-x[i])>0 and r>nr: nr=r;
mr = floor(mr)-ceil(nr)
print "%.0f"%(0. if mr<-1e-14 else mr+1.1)
| 1300033800 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["6\n63\n0"] | 7421b2392cb40f1cf0b7fd93c287f1eb | NoteIn the first test case, one way of achieving a final score of $$$6$$$ is to do the following: Put bricks $$$1$$$, $$$4$$$, and $$$5$$$ into bag $$$1$$$. Put brick $$$3$$$ into bag $$$2$$$. Put brick $$$2$$$ into bag $$$3$$$. If Pak Chanek distributes the bricks that way, a way Bu Dengklek can take the bricks is: Take brick $$$5$$$ from bag $$$1$$$. Take brick $$$3$$$ from bag $$$2$$$. Take brick $$$2$$$ from bag $$$3$$$. The score is $$$|a_5 - a_3| + |a_3 - a_2| = |3 - 5| + |5 - 1| = 6$$$. It can be shown that Bu Dengklek cannot get a smaller score from this distribution.It can be shown that there is no other distribution that results in a final score bigger than $$$6$$$. | There are $$$n$$$ bricks numbered from $$$1$$$ to $$$n$$$. Brick $$$i$$$ has a weight of $$$a_i$$$.Pak Chanek has $$$3$$$ bags numbered from $$$1$$$ to $$$3$$$ that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick.After Pak Chanek distributes the bricks, Bu Dengklek will take exactly one brick from each bag. Let $$$w_j$$$ be the weight of the brick Bu Dengklek takes from bag $$$j$$$. The score is calculated as $$$|w_1 - w_2| + |w_2 - w_3|$$$, where $$$|x|$$$ denotes the absolute value of $$$x$$$.It is known that Bu Dengklek will take the bricks in such a way that minimises the score. What is the maximum possible final score if Pak Chanek distributes the bricks optimally? | For each test case, output a line containing an integer representing the maximum possible final score if Pak Chanek distributes the bricks optimally. | Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the number of bricks. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the weights of the bricks. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,400 | train_096.jsonl | d31311b60dbf498dd9b17fca4dae80e0 | 256 megabytes | ["3\n\n5\n\n3 1 5 2 3\n\n4\n\n17 8 19 45\n\n8\n\n265 265 265 265 265 265 265 265"] | PASSED | from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
a.sort()
ans = 0
for i in range(n-2):
ans = max(ans, a[n-1] - a[i] + a[i+1] - a[i])
for j in range(2, n):
ans = max(ans, a[j] - a[0] + a[j] - a[j-1])
print(ans) | 1667034600 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["2\n3"] | 41583e3656ca0e31b6b7a532e1ae3de4 | NoteIn the first example there are $$$5$$$ segments. The segments $$$1$$$ and $$$2$$$ are connected, because they are of different colors and share a point. Also, the segments $$$2$$$ and $$$3$$$ are connected, and so are segments $$$4$$$ and $$$5$$$. Thus, there are two groups: one containing segments $$$\{1, 2, 3\}$$$, and the other one containing segments $$$\{4, 5\}$$$. | You are given $$$n$$$ colored segments on the number line. Each segment is either colored red or blue. The $$$i$$$-th segment can be represented by a tuple $$$(c_i, l_i, r_i)$$$. The segment contains all the points in the range $$$[l_i, r_i]$$$, inclusive, and its color denoted by $$$c_i$$$: if $$$c_i = 0$$$, it is a red segment; if $$$c_i = 1$$$, it is a blue segment. We say that two segments of different colors are connected, if they share at least one common point. Two segments belong to the same group, if they are either connected directly, or through a sequence of directly connected segments. Find the number of groups of segments. | For each test case, print a single integer $$$k$$$, the number of groups of segments. | 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 first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of segments. Each of the next $$$n$$$ lines contains three integers $$$c_i, l_i, r_i$$$ ($$$0 \leq c_i \leq 1, 0 \leq l_i \leq r_i \leq 10^9$$$), describing the $$$i$$$-th segment. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,300 | train_089.jsonl | 4f1a9accc30f746ee65f5e502614cfb6 | 256 megabytes | ["2\n\n5\n\n0 0 5\n\n1 2 12\n\n0 4 7\n\n1 9 16\n\n0 13 19\n\n3\n\n1 0 1\n\n1 1 2\n\n0 3 4"] | PASSED | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
class dsu:
def __init__(self , n):
self.p = [0]*(n)
self.rank = [0]*(n)
self.mb , self.mr = [] , []
for i in range(n):
self.p[i] = i
if(color[i] == 1):
self.mb.append([right[i] , i])
self.mr.append([-1 , -1])
else:
self.mr.append([right[i] , i])
self.mb.append([-1 , -1])
def find(self , node):
if(self.p[node] == node):return node
self.p[node] = self.find(self.p[node])
return self.p[node]
def union(self , u , v):
u , v = self.find(u) , self.find(v)
if(self.rank[u] == self.rank[v]):
self.p[v] = u
self.rank[u] += 1
if(self.mb[u][0] < self.mb[v][0]):
self.mb[u] = self.mb[v][:]
if(self.mr[u][0] < self.mr[v][0]):
self.mr[u]= self.mr[v][:]
elif(self.rank[u] > self.rank[v]):
self.p[v] = u
if(self.mb[u][0] < self.mb[v][0]):
self.mb[u] = self.mb[v][:]
if(self.mr[u][0] < self.mr[v][0]):
self.mr[u]= self.mr[v][:]
else:
self.p[u] = v
if(self.mb[v][0] < self.mb[u][0]):
self.mb[v] = self.mb[u][:]
if(self.mr[v][0] < self.mr[u][0]):
self.mr[v]= self.mr[u][:]
def best_red(self , u):
u = self.find(u)
return self.mr[u][1]
def best_blue(self , u):
u = self.find(u)
return self.mb[u][1]
def answer():
s.sort()
d = dsu(n)
blue , red = set() , set()
for i in range(len(s)):
x , what , colour , node = s[i]
if(what == 1):
if(colour == 0):
if(len(blue) == 0):
red.add(d.best_red(node))
else:
for x in blue:
d.union(x , node)
blue.clear()
blue.add(d.best_blue(node))
red.add(d.best_red(node))
else:
if(len(red) == 0):
blue.add(d.best_blue(node))
else:
for x in red:
d.union(x , node)
red.clear()
blue.add(d.best_blue(node))
red.add(d.best_red(node))
else:
blue.discard(node)
red.discard(node)
ans = set()
for i in range(n):
ans.add(d.find(i))
return len(ans)
for T in range(int(input())):
n = int(input())
s , left , right , color = [] , [] , [] , []
for i in range(n):
c , l , r = inp()
left.append(l)
right.append(r)
color.append(c)
s.append([l , 1 , c , i])
s.append([r + 1 , -1 , c , i])
print(answer())
| 1654007700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["1\n4\n7\n10\n11\n266666666"] | a6b6d9ff2ac5c367c00a64a387cc9e36 | NoteFor $$$n = 1$$$ there is exactly one pair of numbers — $$$(1, 1)$$$ and it fits.For $$$n = 2$$$, there are only $$$4$$$ pairs — $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$ and they all fit.For $$$n = 3$$$, all $$$9$$$ pair are suitable, except $$$(2, 3)$$$ and $$$(3, 2)$$$, since their $$$\operatorname{lcm}$$$ is $$$6$$$, and $$$\operatorname{gcd}$$$ is $$$1$$$, which doesn't fit the condition. | Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $$$(a, b)$$$ exist, where $$$1 \leq a, b \leq n$$$, for which $$$\frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3$$$.In this problem, $$$\operatorname{gcd}(a, b)$$$ denotes the greatest common divisor of the numbers $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(a, b)$$$ denotes the smallest common multiple of the numbers $$$a$$$ and $$$b$$$. | For each test case output a single integer — the number of pairs of integers satisfying the condition. | The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^8$$$). | standard output | standard input | PyPy 3-64 | Python | 800 | train_104.jsonl | 7f76ba28c2fce491ae03455c552d315f | 256 megabytes | ["6\n\n1\n\n2\n\n3\n\n4\n\n5\n\n100000000"] | PASSED | import math
t = int(input())
for _ in range(t):
n = int(input())
c = 0
c = n + 2*(n//2) + 2*(n//3)
print(c) | 1662129300 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["2\n1\n2\n4"] | 208e285502bed3015b30ef10a351fd6d | null | You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i. e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases. | For each test case, print one integer — the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case. | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the goal of the $$$i$$$-th test case. | standard output | standard input | Python 3 | Python | 800 | train_109.jsonl | d547b7a2291a579d20bd11b41de23311 | 256 megabytes | ["4\n\n1\n\n3\n\n4\n\n12"] | PASSED | # Coded By Block_Cipher
import math
import os
import random
import re
import sys
from math import gcd
from math import sqrt
from collections import Counter
for _ in range(int(input())):
n = int(input())
tw = n//2
th = n//3
if n==1:
print(2)
elif n==2 or n==3:
print(1)
else:
if n%3==0:
print(th)
else:
print(th+1)
| 1659623700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n1", "0"] | c1cfe1f67217afd4c3c30a6327e0add9 | NoteIn the first sample, the first point forms exactly a angle with all other pairs of points, so it is good.In the second sample, along the cd plane, we can see the points look as follows:We can see that all angles here are acute, so no points are good. | You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors and is acute (i.e. strictly less than ). Otherwise, the point is called good.The angle between vectors and in 5-dimensional space is defined as , where is the scalar product and is length of .Given the list of points, print the indices of the good points in ascending order. | First, print a single integer k — the number of good points. Then, print k integers, each on their own line — the indices of the good points in ascending order. | The first line of input contains a single integer n (1 ≤ n ≤ 103) — the number of points. The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| ≤ 103) — the coordinates of the i-th point. All points are distinct. | standard output | standard input | Python 3 | Python | 1,700 | train_016.jsonl | 66bd3bbe9aec141bb587329955455bbc | 256 megabytes | ["6\n0 0 0 0 0\n1 0 0 0 0\n0 1 0 0 0\n0 0 1 0 0\n0 0 0 1 0\n0 0 0 0 1", "3\n0 0 1 2 0\n0 0 9 2 0\n0 0 5 9 0"] | PASSED | n = int(input())
p = [tuple(map(int, input().split())) for i in range(n)]
def d(a, b):
return tuple(x - y for x, y in zip(a, b))
def m(a, b):
return sum(x * y for x, y in zip(a, b))
good_points = []
for i in range(n):
good = True
for j in range(n):
if j == i:
continue
ab = d(p[j], p[i])
for k in range(j + 1, n):
if k == i:
continue
ac = d(p[k], p[i])
if m(ab, ac) > 0:
good = False
break
if not good:
break
if good:
good_points.append(i)
print(len(good_points))
for i in good_points:
print(i + 1)
| 1504535700 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["10", "5"] | 98de093d78f74273e0ac5c7886fb7a41 | null | Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k. | Print the required number. | The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018). | standard output | standard input | PyPy 3 | Python | 1,600 | train_025.jsonl | 046a796fad60fa208472a4a31dbd992b | 256 megabytes | ["1 1 10", "2 -4 4"] | PASSED | k,a,b=map(int,input().split())
ans=(b-a)//k
if (a%k==0)or(b%k==0)or((b-a)%k+a%k>=k):
ans+=1
print(ans) | 1447264800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["4"] | 6ac3246ee9cf78d81f96a3ed05b35918 | NoteSome of the possible solutions for the example: | You are given a Young diagram. Given diagram is a histogram with $$$n$$$ columns of lengths $$$a_1, a_2, \ldots, a_n$$$ ($$$a_1 \geq a_2 \geq \ldots \geq a_n \geq 1$$$). Young diagram for $$$a=[3,2,2,2,1]$$$. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a $$$1 \times 2$$$ or $$$2 \times 1$$$ rectangle. | Output one integer: the largest number of non-overlapping dominos that you can draw inside of the given Young diagram. | The first line of input contain one integer $$$n$$$ ($$$1 \leq n \leq 300\,000$$$): the number of columns in the given histogram. The next line of input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 300\,000, a_i \geq a_{i+1}$$$): the lengths of columns. | standard output | standard input | PyPy 3 | Python | 2,000 | train_001.jsonl | d63b00f87b4f8466f3dd8ab3a636128b | 256 megabytes | ["5\n3 2 2 2 1"] | PASSED | from sys import stdin,stdout
n = int(stdin.readline().strip())
alist = list(map(int,stdin.readline().split()))
k = max(alist)
total,odd,even = 0,0,0
for i,a in enumerate(alist):
total += a//2
if a%2:
if i%2:
odd+=1
else:
even+=1
total+=min(odd,even)
print(total)
| 1576926300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nNO\nYES\nNO\nNO"] | 1d9d34dca11a787d6e2345494680e717 | NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of $$$1$$$.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight $$$1$$$ and one of weight $$$2$$$.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair. | Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half. | For each test case, output on a separate line: "YES", if all candies can be divided into two sets with the same weight; "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. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of candies that Alice and Bob received. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ — the weights of the candies. The weight of each candy is either $$$1$$$ or $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 800 | train_089.jsonl | ada7a69003dca579132e5cce074ae1bb | 256 megabytes | ["5\n2\n1 1\n2\n1 2\n4\n1 2 1 2\n3\n2 2 2\n3\n2 1 2"] | PASSED | t=int(input())
for _ in range(t):
n=int(input())
L=list(map(int,input().split()))
k1,k2=0,0
for i in range(n):
if L[i]==1:
k1+=1
else:
k2+=2
if (k1+k2)%2==0 and k1!=0 and k2!=0:
print("YES")
elif k1%2==0 and k2==0:
print("YES")
elif (k2/2)%2==0 and k1==0:
print("YES")
else:
print("NO") | 1609770900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3\n1\n2"] | 59e45a82cdafd64e0bf2a199cb08bbb9 | NoteThe first query asks about the whole array. You can partition it into $$$[2]$$$, $$$[3,10,7]$$$, and $$$[5,14]$$$. The first subrange has product and LCM equal to $$$2$$$. The second has product and LCM equal to $$$210$$$. And the third has product and LCM equal to $$$70$$$. Another possible partitioning is $$$[2,3]$$$, $$$[10,7]$$$, and $$$[5,14]$$$.The second query asks about the range $$$(2,4)$$$. Its product is equal to its LCM, so you don't need to partition it further.The last query asks about the range $$$(3,5)$$$. You can partition it into $$$[10,7]$$$ and $$$[5]$$$. | This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array $$$a$$$ of length $$$n$$$ written on it, and then he does the following: he picks a range $$$(l, r)$$$ and cuts the subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ out, removing the rest of the array. he then cuts this range into multiple subranges. to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their least common multiple (LCM). Formally, he partitions the elements of $$$a_l, a_{l + 1}, \ldots, a_r$$$ into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for $$$q$$$ independent ranges $$$(l, r)$$$, tell Baby Ehab the minimum number of subarrays he needs. | For each query, print its answer on a new line. | The first line contains $$$2$$$ integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains $$$2$$$ integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the endpoints of this query's interval. | standard output | standard input | PyPy 3 | Python | 2,100 | train_105.jsonl | 82dbe4ddd4b208745168fc79e8d9fc1f | 256 megabytes | ["6 3\n2 3 10 7 5 14\n1 6\n2 4\n3 5"] | PASSED | import sys
input = sys.stdin.readline
def main():
N, Q = map(int, input().split())
A = list(map(int, input().split()))
MX = int(1e5)
primeFactors = [[] for _ in range(MX + 1)]
for i in range(2, MX + 1):
if len(primeFactors[i]) > 0:
continue
for j in range(i, MX + 1, i):
primeFactors[j].append(i)
MXH = 18
nxt = [N for _ in range(MX + 1)]
dp = [[N for _ in range(MXH + 1)] for __ in range(N + 1)]
for i in range(N - 1, -1, -1):
dp[i][0] = dp[i + 1][0]
for factor in primeFactors[A[i]]:
dp[i][0] = min(dp[i][0], nxt[factor])
nxt[factor] = i
for i in range(1, MXH + 1):
for j in range(N):
dp[j][i] = dp[dp[j][i - 1]][i - 1]
for _ in range(Q):
l, r = map(int, input().split())
l -= 1
r -= 1
cnt = 1
for i in range(MXH, -1, -1):
if dp[l][i] <= r:
cnt += 1 << i
l = dp[l][i]
print(cnt)
main() | 1619012100 | [
"number theory",
"graphs"
] | [
0,
0,
1,
0,
1,
0,
0,
0
] |
|
2 seconds | ["6 6", "6 6 6", "10"] | 3d347323920a00f8f4df19e549ab6804 | null | Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.For each vertex the answer must be considered independently.The beauty of the root equals to number written on it. | Output n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i. | First line contains one integer number n — the number of vertices in tree (1 ≤ n ≤ 2·105). Next line contains n integer numbers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 2·105). Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ y), which means that there is an edge (x, y) in the tree. | standard output | standard input | PyPy 2 | Python | 2,000 | train_078.jsonl | 80396aa88fa42a566c9fc791fcd450eb | 256 megabytes | ["2\n6 2\n1 2", "3\n6 2 3\n1 2\n1 3", "1\n10"] | PASSED | from sys import stdin
from fractions import gcd
n = int(stdin.readline().strip())
v = map(int, stdin.readline().strip().split())
adj = [[] for _ in xrange(n)]
for _ in xrange(n-1):
x, y = map(int, stdin.readline().strip().split())
adj[x-1].append(y-1)
adj[y-1].append(x-1)
root_divisors = []
cnt = [0]*200001
d = 1
while d*d <= v[0]:
if v[0] % d == 0:
root_divisors.append(d)
cnt[d] += 1
if v[0]/d != d:
root_divisors.append(v[0]/d)
cnt[v[0]/d] += 1
d += 1
s = [0]
visited = [False]*n
visited[0] = True
level = [1]*n
res1 = [0]*n
res2 = [0]*n
res1[0] = v[0]
d = 1
while s:
x = s[-1]
any_more = False
while adj[x]:
y = adj[x].pop()
if not visited[y]:
visited[y] = True
any_more = True
s.append(y)
level[y] = level[x]+1
res2[y] = gcd(res2[x], v[y])
for d in root_divisors:
if v[y] % d == 0:
cnt[d] += 1
if cnt[d] == level[y] or cnt[d] == level[y]-1:
res1[y] = max(res1[y], res2[y], d)
break
if not any_more:
s.pop()
for d in root_divisors:
if v[x] % d == 0:
cnt[d] -= 1
print ' '.join(map(str, res1)) | 1504019100 | [
"number theory",
"math",
"trees",
"graphs"
] | [
0,
0,
1,
1,
1,
0,
0,
1
] |
|
1 second | ["NO", "YES\n2 1\n5 5\n-2 4", "YES\n-10 4\n-2 -2\n1 2"] | a949ccae523731f601108d4fa919c112 | null | There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. | In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. | The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space. | standard output | standard input | Python 3 | Python | 1,600 | train_034.jsonl | 27686dc9883705811a96cc70b30e2805 | 256 megabytes | ["1 1", "5 5", "5 10"] | PASSED | a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
for x in range(1, a):
if ((a ** 2 - x ** 2) ** 0.5) % 1 < 10 ** -5:
y = round((a ** 2 - x ** 2) ** 0.5)
if x > 0 and y > 0 and (y * b) % a == 0 and (x * b) % a == 0:
print('YES')
print(0, 0)
print(x, y)
print(y * b // a, -x * b // a)
exit(0)
print('NO')
| 1396162800 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n3\n3\n3"] | 40d1ea98aa69865143d44432aed4dd7e | NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation | Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. | Print m integers — the i-th integer denotes value v for sequence a after the i-th query. | The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query. | standard output | standard input | PyPy 3 | Python | 1,700 | train_004.jsonl | 9e467eada8764833251c0fa73a1e1f60 | 256 megabytes | ["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"] | PASSED | #------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,k=map(int,input().split())
l=list(map(int,input().split()))
tree=[0]*2*(2**n)
y=0
def build(arr,start,end,treenode):
if start==end:
#print(end,treenode)
tree[treenode]=arr[end]
#print(tree,end)
return 0
else:
mid=(start+end)//2
y=build(arr,start,mid,2*treenode)
y=build(arr,mid+1,end,2*treenode+1)
y+=1
if (y)%2==0:
tree[treenode]=tree[2*treenode]^tree[2*treenode+1]
else:
tree[treenode]=tree[2*treenode]|tree[2*treenode+1]
#print(tree)
return y
def update1(treenode,k):
if treenode==0:
return
if k%2==0:
tree[treenode]=tree[2*treenode]^tree[2*treenode+1]
else:
tree[treenode]=tree[2*treenode]|tree[2*treenode+1]
update1(treenode//2,k+1)
def update(n,ind,le):
ind=ind+2**(le)-1
#print(ind,)
tree[ind]=n
update1(ind//2,1)
#print(n)
y=build(l,0,2**n-1,1)
#print(tree)
for j in range(k):
p,b=map(int,input().split())
update(b,p,n)
print(tree[1])
| 1377531000 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["8", "-1", "0"] | 461666a075cd830496f919557b8122a4 | null | There are $$$n$$$ warriors in a row. The power of the $$$i$$$-th warrior is $$$a_i$$$. All powers are pairwise distinct.You have two types of spells which you may cast: Fireball: you spend $$$x$$$ mana and destroy exactly $$$k$$$ consecutive warriors; Berserk: you spend $$$y$$$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be $$$[2, 3, 7, 8, 11, 5, 4]$$$, and $$$k = 3$$$. If you cast Berserk on warriors with powers $$$8$$$ and $$$11$$$, the resulting sequence of powers becomes $$$[2, 3, 7, 11, 5, 4]$$$. Then, for example, if you cast Fireball on consecutive warriors with powers $$$[7, 11, 5]$$$, the resulting sequence of powers becomes $$$[2, 3, 4]$$$.You want to turn the current sequence of warriors powers $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$. Calculate the minimum amount of mana you need to spend on it. | Print the minimum amount of mana for turning the sequnce $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$, or $$$-1$$$ if it is impossible. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$ and the length of sequence $$$b$$$ respectively. The second line contains three integers $$$x, k, y$$$ ($$$1 \le x, y, \le 10^9; 1 \le k \le n$$$) — the cost of fireball, the range of fireball and the cost of berserk respectively. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that all integers $$$a_i$$$ are pairwise distinct. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that all integers $$$b_i$$$ are pairwise distinct. | standard output | standard input | PyPy 3 | Python | 2,000 | train_008.jsonl | 3cb1a2d953100b61e2e1066d1b6a1e95 | 256 megabytes | ["5 2\n5 2 3\n3 1 4 5 2\n3 5", "4 4\n5 1 4\n4 3 1 2\n2 4 3 1", "4 4\n2 1 11\n1 3 2 4\n1 3 2 4"] | PASSED | import sys
def solve(A):
if len(A) <=2 :
return (True,0)
if len(A) < k+2:
if max(A) != A[0] and max(A) !=A[-1]:
return (False,0)
else:
return (True,y*(len(A)-2))
else:
if y*k < x :
if max(A) == A[0] or max(A) == A[-1]:
return (True,(len(A)-2)*y)
else:
d=len(A)-2
return (True,x + (d-k)*y)
else:
d=len(A)-2
return (True,(d//k)*x + (d-((d//k)*k))*y)
n,m=[int(c) for c in input().split()]
x,k,y=[int(c) for c in input().split()]
a=[int(c) for c in input().split()]
b=[int(c) for c in input().split()]
a.insert(0,-1)
a.append(-1)
b.append(-1)
# print(a,b)
j=0
A=[]
ans=0
aoo=False
for i in range(n+2):
if a[i] != b[j]:
A.append(a[i])
else:
A.append(a[i])
j+=1
pp,aa=solve(A)
if pp:
ans+=aa
else:
aoo=True
break
# print(A,solve(A))
A=[a[i]]
if j!=len(b) or aoo:
print("-1")
else:
print(ans)
| 1594565100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["2\n1"] | e5a01ebfdca3af987e93b68c96268c16 | NoteIn the first test case, the smallest such $$$k$$$ is $$$2$$$, for which you can choose, for example, cells $$$(1, 1)$$$ and $$$(2, 1)$$$.Note that you can't choose cells $$$(1, 1)$$$ and $$$(2, 3)$$$ for $$$k = 2$$$, as both cells $$$(1, 2)$$$ and $$$(2, 1)$$$ would give $$$b_1 = 1, b_2 = 2$$$, so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose $$$k = 1$$$, for it you can choose cell $$$(3, 1)$$$ or $$$(1, 1)$$$. | You are playing a game on a $$$n \times m$$$ grid, in which the computer has selected some cell $$$(x, y)$$$ of the grid, and you have to determine which one. To do so, you will choose some $$$k$$$ and some $$$k$$$ cells $$$(x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)$$$, and give them to the computer. In response, you will get $$$k$$$ numbers $$$b_1,\, b_2, \ldots b_k$$$, where $$$b_i$$$ is the manhattan distance from $$$(x_i, y_i)$$$ to the hidden cell $$$(x, y)$$$ (so you know which distance corresponds to which of $$$k$$$ input cells). After receiving these $$$b_1,\, b_2, \ldots, b_k$$$, you have to be able to determine the hidden cell. What is the smallest $$$k$$$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells $$$(a_1, b_1)$$$ and $$$(a_2, b_2)$$$ is equal to $$$|a_1-a_2|+|b_1-b_2|$$$. | For each test case print a single integer — the minimum $$$k$$$ for that test case. | The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the number of rows and the number of columns in the grid. | standard output | standard input | Python 3 | Python | 900 | train_084.jsonl | 7ec82ee2315130fac105e10c5626be6f | 256 megabytes | ["2\n2 3\n3 1"] | PASSED | import math
N = int(input())
for tt in range(N):
ss = input().split(' ')
a,b = int(ss[0]),int(ss[1])
st = {}
if a == 1 and b == 1:
print(0)
continue
elif a == 1 or b == 1:
print(1)
continue
t = min(a,b)
print(2)
| 1637678100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n6\n0\n540"] | 81d4867a7e5128baf316193e9cc3dfce | NoteExplanation of the first test case from the example:There are two possible permutations, $$$p = [1, 2]$$$ and $$$p = [2, 1]$$$. For $$$p = [1, 2]$$$, the process is the following: the first jury member tells a task; the second jury member tells a task; the first jury member doesn't have any tasks left to tell, so they are skipped; the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For $$$p = [2, 1]$$$, the process is the following: the second jury member tells a task; the first jury member tells a task; the second jury member tells a task. So, this permutation is nice. | $$$n$$$ people gathered to hold a jury meeting of the upcoming competition, the $$$i$$$-th member of the jury came up with $$$a_i$$$ tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ (an array of size $$$n$$$ where each integer from $$$1$$$ to $$$n$$$ occurs exactly once).Then the discussion goes as follows: If a jury member $$$p_1$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If a jury member $$$p_2$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. ... If a jury member $$$p_n$$$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation $$$p$$$ is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo $$$998\,244\,353$$$. | For each test case, print one integer — the number of nice permutations, taken modulo $$$998\,244\,353$$$. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — number of jury members. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of problems that the $$$i$$$-th member of the jury came up with. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,500 | train_099.jsonl | bfd32358471c31088f7b8cb4bc4629b7 | 256 megabytes | ["4\n2\n1 2\n3\n5 5 5\n4\n1 3 3 7\n6\n3 4 2 1 3 3"] | PASSED | import sys
inpu = sys.stdin.readline
prin = sys.stdout.write
mod = 998244353
def factorial_mod(n) :
ans = 1
for i in range(2, n + 1) :
ans *= i
ans %= mod
return ans
def factorial_d(n, k) :
ans = 1
for i in range(2, n + 1) :
if i == k :
continue
ans *= i
ans %= mod
return ans
for _ in range(int(inpu())) :
n = int(inpu())
lis = list(map(int, inpu().split(' ')))
first = second = -1
for i in lis:
if i > first:
second = first
first = i
elif i > second:
second = i
if first - second > 1:
prin('0\n')
continue
cou1 = 0
cou2 = 0
for i in lis :
if i == first :
cou1 += 1
if i == second :
cou2 += 1
ans = factorial_mod(n)
if cou1 == 1 :
ans = factorial_d(n, cou2 + 1)
ans *= cou2
ans %= mod
prin(str(ans) + '\n') | 1631111700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["-1", "agoeuioaeiruuimaeoieauoweouoiaouimae"] | 933167c31c0f53a43e840cc6cf153f8d | NoteIn the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following $$$6 \times 6$$$ grid: It is easy to verify that every row and every column contain all the vowels. | Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $$$k$$$ is vowelly if there are positive integers $$$n$$$ and $$$m$$$ such that $$$n\cdot m = k$$$ and when the word is written by using $$$n$$$ rows and $$$m$$$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer $$$k$$$ and you must either print a vowelly word of length $$$k$$$ or print $$$-1$$$ if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. | The output must consist of a single line, consisting of a vowelly word of length $$$k$$$ consisting of lowercase English letters if it exists or $$$-1$$$ if it does not. If there are multiple possible words, you may output any of them. | Input consists of a single line containing the integer $$$k$$$ ($$$1\leq k \leq 10^4$$$) — the required length. | standard output | standard input | PyPy 2 | Python | 1,100 | train_012.jsonl | fea280964eadf21f18fea9fa820218d4 | 256 megabytes | ["7", "36"] | PASSED | k = input()
v = ["a", "e", "i", "o", "u"]
n = m = None
for i in xrange(5, int(k**0.5) + 1):
if k % i == 0:
n = i
m = k / i
break
if not n:
print -1
else:
ans = []
row = v * (n/5) + v[:n%5]
for i in xrange(m):
ans.extend(row[i:] + row[:i])
print "".join(ans) | 1558105500 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["0 0 0 0 0 2 3", "0 1 1 2 3"] | fe3a6f0d33b1b5b8018e1810ba8ebdd6 | NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$). | The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following: The $$$i$$$-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\max t_i \le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home. | Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam. | The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le M \le 2 \cdot 10^7$$$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \le t_i \le 100$$$) — time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$. | standard output | standard input | PyPy 2 | Python | 1,700 | train_023.jsonl | 35885711a6eada855880e0f7f8b3b5ff | 256 megabytes | ["7 15\n1 2 3 4 5 6 7", "5 100\n80 40 40 40 60"] | PASSED | from sys import stdin,stdout
n,m = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
A = []
d ={}
for i in range(1,101):
d[i] = 0
for j in range(n):
ans = 0
sm = a[j]
# print sm
for i in range(1,101):
if (sm + (i * d[i]) > m):
ans += (m - sm) / i;
break
else:
sm += (d[i] * i);
ans += d[i];
d[a[j]]+=1
# print "40:",d[40]
stdout.write(str(j-ans)+" "), | 1560955500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4", "1"] | 8c464cc6c9d012156828f5e3c250ac20 | NoteIn the first example, the initial positions and velocities of clouds are illustrated below. The pairs are: $$$(1, 3)$$$, covering the moon at time $$$2.5$$$ with $$$w = -0.4$$$; $$$(1, 4)$$$, covering the moon at time $$$3.5$$$ with $$$w = -0.6$$$; $$$(1, 5)$$$, covering the moon at time $$$4.5$$$ with $$$w = -0.7$$$; $$$(2, 5)$$$, covering the moon at time $$$2.5$$$ with $$$w = -2$$$. Below is the positions of clouds at time $$$2.5$$$ with $$$w = -0.4$$$. At this moment, the $$$1$$$-st and $$$3$$$-rd clouds both cover the moon. In the second example, the only pair is $$$(1, 4)$$$, covering the moon at time $$$15$$$ with $$$w = 0$$$.Note that all the times and wind velocities given above are just examples among infinitely many choices. | Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino."See? The clouds are coming." Kanno gazes into the distance."That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $$$0$$$.There are $$$n$$$ clouds floating in the sky. Each cloud has the same length $$$l$$$. The $$$i$$$-th initially covers the range of $$$(x_i, x_i + l)$$$ (endpoints excluded). Initially, it moves at a velocity of $$$v_i$$$, which equals either $$$1$$$ or $$$-1$$$.Furthermore, no pair of clouds intersect initially, that is, for all $$$1 \leq i \lt j \leq n$$$, $$$\lvert x_i - x_j \rvert \geq l$$$.With a wind velocity of $$$w$$$, the velocity of the $$$i$$$-th cloud becomes $$$v_i + w$$$. That is, its coordinate increases by $$$v_i + w$$$ during each unit of time. Note that the wind can be strong and clouds can change their direction.You are to help Mino count the number of pairs $$$(i, j)$$$ ($$$i < j$$$), such that with a proper choice of wind velocity $$$w$$$ not exceeding $$$w_\mathrm{max}$$$ in absolute value (possibly negative and/or fractional), the $$$i$$$-th and $$$j$$$-th clouds both cover the moon at the same future moment. This $$$w$$$ doesn't need to be the same across different pairs. | Output one integer — the number of unordered pairs of clouds such that it's possible that clouds from each pair cover the moon at the same future moment with a proper choice of wind velocity $$$w$$$. | The first line contains three space-separated integers $$$n$$$, $$$l$$$, and $$$w_\mathrm{max}$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l, w_\mathrm{max} \leq 10^8$$$) — the number of clouds, the length of each cloud and the maximum wind speed, respectively. The $$$i$$$-th of the following $$$n$$$ lines contains two space-separated integers $$$x_i$$$ and $$$v_i$$$ ($$$-10^8 \leq x_i \leq 10^8$$$, $$$v_i \in \{-1, 1\}$$$) — the initial position and the velocity of the $$$i$$$-th cloud, respectively. The input guarantees that for all $$$1 \leq i \lt j \leq n$$$, $$$\lvert x_i - x_j \rvert \geq l$$$. | standard output | standard input | Python 2 | Python | 2,500 | train_034.jsonl | 3f1904fd2e7c9efb875f5ae24f58bac8 | 256 megabytes | ["5 1 2\n-2 1\n2 1\n3 -1\n5 -1\n7 -1", "4 10 1\n-20 1\n-10 -1\n0 1\n10 -1"] | PASSED | def solve(xs, vs, l, wmax):
assert wmax >= 1
assert l >= 1
n = len(xs)
assert len(vs) == n >= 1
poss = [i for i in xrange(n) if vs[i] == +1]
negs = [i for i in xrange(n) if vs[i] == -1]
poss = sorted([-xs[i] for i in poss])
negs = sorted([xs[i] + l for i in negs])
ans = 0
for x1 in poss:
if wmax == 1 and x1 <= 0: continue
lf = max(-x1, (x1 * (1 - wmax)) / (wmax + 1))
if wmax != 1:
lf = max(lf, -x1 * (wmax + 1) / (wmax - 1))
L = -1
R = len(negs)
while R - L > 1:
M = L + R >> 1
if negs[M] <= lf:
L = M
else:
R = M
ans += len(negs) - R
return ans
n, l, wmax = map(int, raw_input().split())
xs = []
vs = []
for i in xrange(n):
x, v = map(int, raw_input().split())
xs.append(x)
vs.append(v)
print solve(xs, vs, l, wmax) | 1528724100 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3\n2\n1"] | c457b77b16d94c6c4c95b7403a1dd0c7 | null | You are both a shop keeper and a shop assistant at a small nearby shop. You have $$$n$$$ goods, the $$$i$$$-th good costs $$$a_i$$$ coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $$$n$$$ goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $$$n$$$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer $$$q$$$ independent queries. | For each query, print the answer for it — the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices. | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100)$$$ — the number of goods. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the price of the $$$i$$$-th good. | standard output | standard input | Python 3 | Python | 800 | train_003.jsonl | 195f4732094e11179183b1216da1ca91 | 256 megabytes | ["3\n5\n1 2 3 4 5\n3\n1 2 2\n4\n1 1 1 1"] | PASSED | #Equalize_Prices_Again
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
print(((sum(l)-1)//n)+1) | 1569940500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["5 2 1 3 4"] | 6b75105015e5bf753ee93f6e0639a816 | NoteThe following illustrates the first example. | Andi and Budi were given an assignment to tidy up their bookshelf of $$$n$$$ books. Each book is represented by the book title — a string $$$s_i$$$ numbered from $$$1$$$ to $$$n$$$, each with length $$$m$$$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where the odd-indexed characters will be compared ascendingly, and the even-indexed characters will be compared descendingly.A string $$$a$$$ occurs before a string $$$b$$$ in asc-desc-ending order if and only if in the first position where $$$a$$$ and $$$b$$$ differ, the following holds: if it is an odd position, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$; if it is an even position, the string $$$a$$$ has a letter that appears later in the alphabet than the corresponding letter in $$$b$$$. | Output $$$n$$$ integers — the indices of the strings after they are sorted asc-desc-endingly. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \cdot m \leq 10^6$$$). The $$$i$$$-th of the next $$$n$$$ lines contains a string $$$s_i$$$ consisting of $$$m$$$ uppercase Latin letters — the book title. The strings are pairwise distinct. | standard output | standard input | PyPy 3-64 | Python | 1,100 | train_102.jsonl | 847ca4c47d524ca214d023c581bc7b90 | 512 megabytes | ["5 2\nAA\nAB\nBB\nBA\nAZ"] | PASSED | import functools
import sys
input = lambda: sys.stdin.readline().rstrip()
def compare(a, b):
for i in range(m):
if a[0][i] != b[0][i]:
if i % 2 == 0:
if a[0][i] < b[0][i]:
return -1
else:
return 1
else:
if a[0][i] > b[0][i]:
return -1
else:
return 1
n, m = map(int, input().split())
li = []
for i in range(n):
s = input()
li.append((s, i))
li.sort(key=functools.cmp_to_key(compare))
r = [v[1] + 1 for v in li]
print(*r) | 1633181700 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["YES\nNO\nNO\nYES\nYES\nNO"] | 8717913513b019d3ef836176eafce7b1 | NoteIn the first test case, the dominoes can be divided as follows: First set of dominoes: $$$[\{1, 2\}, \{4, 3\}]$$$ Second set of dominoes: $$$[\{2, 1\}, \{3, 4\}]$$$ In other words, in the first set we take dominoes with numbers $$$1$$$ and $$$2$$$, and in the second set we take dominoes with numbers $$$3$$$ and $$$4$$$.In the second test case, there's no way to divide dominoes into $$$2$$$ sets, at least one of them will contain repeated number. | Polycarp was recently given a set of $$$n$$$ (number $$$n$$$ — even) dominoes. Each domino contains two integers from $$$1$$$ to $$$n$$$.Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.For example, if he has $$$4$$$ dominoes: $$$\{1, 4\}$$$, $$$\{1, 3\}$$$, $$$\{3, 2\}$$$ and $$$\{4, 2\}$$$, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes ($$$\{1, 4\}$$$ and $$$\{3, 2\}$$$), and the second set — the second and fourth ones ($$$\{1, 3\}$$$ and $$$\{4, 2\}$$$). | For each test case print: YES, if it is possible to divide $$$n$$$ dominoes into two sets so that the numbers on the dominoes of each set are different; NO if this is not possible. You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer). | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of dominoes. The next $$$n$$$ lines contain pairs of numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) describing the numbers on the $$$i$$$-th domino. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,600 | train_089.jsonl | 99369d087806414f19d55a3206f1626a | 256 megabytes | ["6\n\n4\n\n1 2\n\n4 3\n\n2 1\n\n3 4\n\n6\n\n1 2\n\n4 5\n\n1 3\n\n4 6\n\n2 3\n\n5 6\n\n2\n\n1 1\n\n2 2\n\n2\n\n1 2\n\n2 1\n\n8\n\n2 1\n\n1 2\n\n4 3\n\n4 3\n\n5 6\n\n5 7\n\n8 6\n\n7 8\n\n8\n\n1 2\n\n2 1\n\n4 3\n\n5 3\n\n5 4\n\n6 7\n\n8 6\n\n7 8"] | PASSED | import sys
input= sys.stdin.readline
def solve():
n = int(input())
adj = [[] for i in range(n)]
f= False
for i in range(n):
a,b = map(int,input().split(' '))
a-=1
b-=1
adj[a].append(b)
adj[b].append(a)
if len(adj[a]) > 2 or len(adj[b]) > 2 or a ==b:
f = True
if f==True:
sys.stdout.write('No\n')
return
color = [-1 for i in range(n)]
for i in range(n):
if color[i] == -1:
q = []
q.append(i)
color[i] = 0
while len(q)>0:
a = q.pop(0)
for k in adj[a]:
if a ==k:
f = True
sys.stdout.write('No\n')
return
if color[k] == -1:
if color[a] == 1:
color[k] = 0
else:
color[k] = 1
q.append(k)
else:
if color[k] == color[a]:
f = True
print('No')
return
if f:
sys.stdout.write('No\n')
else:
sys.stdout.write('Yes\n')
t = int(input())
for _ in range(t):
solve()
| 1657463700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
5 seconds | ["AG", "AGA"] | 24fe280b88575516ec679ff78641440e | null | The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible. | If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa - Sg| ≤ 500. If there are several solutions, you are allowed to print any of them. | The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs. Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg. | standard output | standard input | Python 3 | Python | 1,500 | train_005.jsonl | 98d7daf77ed8e172a69639ed686aea50 | 256 megabytes | ["2\n1 999\n999 1", "3\n400 600\n400 600\n400 600"] | PASSED | def main():
n = int(input())
res, ag = ['G'] * n, 0
for i in range(n):
a = int(input().split()[0])
if ag + a < 500:
ag += a
res[i] = 'A'
else:
ag -= 1000 - a
print('-1' if abs(ag) > 500 else ''.join(res))
if __name__ == '__main__':
main()
| 1363188600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["YES\n1 333.333333\n2 333.333333\n2 166.666667 1 166.666667", "YES\n3 20.000000 4 60.000000\n1 80.000000\n4 40.000000 2 40.000000\n3 80.000000\n2 60.000000 1 20.000000", "NO", "YES\n4 250.000000 5 500.000000 2 500.000000\n3 500.000000 1 500.000000 4 250.000000"] | ae96b178fee7c189a377835a53eb3dc4 | null | Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles — one bottle of each kind. We know that the volume of milk in each bottle equals w.When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup. | Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO". If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≤ b ≤ n). All numbers b on each line should be different. If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point. | The only input data file contains three integers n, w and m (1 ≤ n ≤ 50, 100 ≤ w ≤ 1000, 2 ≤ m ≤ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company. | standard output | standard input | Python 3 | Python | 1,900 | train_034.jsonl | 8d908fe6364b2d11855d8dd043a75e95 | 256 megabytes | ["2 500 3", "4 100 5", "4 100 7", "5 500 2"] | PASSED | #!/usr/bin/python3
n, w, m = map(int, input().split())
if n > m:
print("YES")
i = 0
cur = w
for j in range(m):
milk = 0
while milk < (w * n) / m - 1e-8:
amount = min(cur, (w * n) / m - milk)
print(i + 1, amount, end=' ')
milk += amount
cur -= amount
if abs(cur) < 1e-8:
i += 1
cur = w
print()
else:
ans = [[] for i in range(m)]
sums = [0 for i in range(m)]
left = [w for i in range(n)]
for i in range(m):
while sums[i] < (w * n) / m - 1e-8:
mx = 0
for j in range(n):
if left[j] > left[mx]:
mx = j
amount = min(left[mx], (w * n) / m - sums[i])
if left[mx] < w and amount < left[mx] - 1e-8:
print("NO")
exit(0)
sums[i] += amount
left[mx] -= amount
ans[i].append((mx, amount))
print("YES")
for i in range(m):
for a, b in ans[i]:
print(a + 1, b, end=' ')
print()
| 1309446000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["Yes\nYes\nNo\nNo"] | 9edbe28b5be43a9cc6c633db98bc5a36 | NoteIn the first test case, we have the only sequence $$$a = [1, 1, 1, 1, 1]$$$.In the second test case, we can choose, for example, $$$a = [-3, -2, -1, 0, 1, 2, 3]$$$.In the third test case, the prefix sums define the only sequence $$$a = [2, 1, 1]$$$, but it is not sorted. In the fourth test case, it can be shown that there is no sequence with the given prefix sums. | Suppose $$$a_1, a_2, \dots, a_n$$$ is a sorted integer sequence of length $$$n$$$ such that $$$a_1 \leq a_2 \leq \dots \leq a_n$$$. For every $$$1 \leq i \leq n$$$, the prefix sum $$$s_i$$$ of the first $$$i$$$ terms $$$a_1, a_2, \dots, a_i$$$ is defined by $$$$$$ s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. $$$$$$Now you are given the last $$$k$$$ terms of the prefix sums, which are $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$. Your task is to determine whether this is possible. Formally, given $$$k$$$ integers $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$, the task is to check whether there is a sequence $$$a_1, a_2, \dots, a_n$$$ such that $$$a_1 \leq a_2 \leq \dots \leq a_n$$$, and $$$s_i = a_1 + a_2 + \dots + a_i$$$ for all $$$n-k+1 \leq i \leq n$$$. | For each test case, output "YES" (without quotes) if it is possible and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). | Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains two integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq n$$$), indicating the length of the sequence $$$a$$$ and the number of terms of prefix sums, respectively. The second line of each test case contains $$$k$$$ integers $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$ ($$$-10^9 \leq s_i \leq 10^9$$$ for every $$$n-k+1 \leq i \leq n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,200 | train_103.jsonl | 8bfc03b9a1a57c042f63ddf0e0a53b55 | 512 megabytes | ["4\n\n5 5\n\n1 2 3 4 5\n\n7 4\n\n-6 -5 -3 0\n\n3 3\n\n2 3 4\n\n3 2\n\n3 4"] | PASSED | for asdasdas in range(int(input())):
n, k = map(int, input().split())
items = [int(i) for i in input().split()]
if k == 1:
print('YES')
continue
an_items = [items[i + 1] - items[i] for i in range(k - 1)]
an_itemsP0 = [0] * (n - k + 1) + an_items
if an_items != sorted(an_items):
print('NO')
continue
if items[0] > (n - k + 1) * an_itemsP0[n - k + 1]:
print('NO')
continue
print('YES')
| 1664548500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3 1", "7 0"] | 863a8124d46bb09b49fc88939fb5f364 | NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy $$$3 + 4 = 7$$$ coconuts. | Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks). | Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other. | The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$0 \le x, y \le 10^{18}$$$, $$$1 \le z \le 10^{18}$$$) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut. | standard output | standard input | PyPy 3 | Python | 1,000 | train_004.jsonl | f9fd7a35d159d7ef0c721c4ded5a56c1 | 512 megabytes | ["5 4 3", "6 8 2"] | PASSED | x , y , p = map(int,input().split())
mxbought = (x + y) // p
minigave = min(p - (x % p) , p - (y % p))
print(mxbought , end = ' ')
x = x % p
y = y % p
if x + y >= p :
print(p - max(x , y))
else:
print(0)
| 1560677700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["? 6 1 2 3 4 5 6\n\n? 3 3 1 5\n\n? 2 1 2\n\n! 1 2"] | 905e3f3e6f7d8f13789b89e77a3ef65e | NoteThe tree in the first sample: | This is an interactive problem!In the last regional contest Hemose, ZeyadKhattab and YahiaSherif — members of the team Carpe Diem — did not qualify to ICPC because of some unknown reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.Zeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.Hemose has a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. Unfortunately, Hemose doesn't remember the weights of edges.Let's define $$$Dist(u, v)$$$ for $$$u\neq v$$$ as the greatest common divisor of the weights of all edges on the path from node $$$u$$$ to node $$$v$$$.Hemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest $$$Dist$$$ between any two nodes from the set. More formally, if Hemose gives the device a set $$$S$$$ of nodes, the device will return the largest value of $$$Dist(u, v)$$$ over all pairs $$$(u, v)$$$ with $$$u$$$, $$$v$$$ $$$\in$$$ $$$S$$$ and $$$u \neq v$$$.Hemose can use this Device at most $$$12$$$ times, and wants to find any two distinct nodes $$$a$$$, $$$b$$$, such that $$$Dist(a, b)$$$ is maximum possible. Can you help him? | null | null | standard output | standard input | PyPy 3-64 | Python | 2,300 | train_106.jsonl | 32477289f79982571884a3e961925c0e | 256 megabytes | ["6\n1 2\n2 3\n2 4\n1 5\n5 6\n\n10\n\n2\n\n10"] | PASSED | # import os,sys
# from io import BytesIO, IOBase
# from collections import defaultdict,deque,Counter
# from bisect import bisect_left,bisect_right
# from heapq import heappush,heappop
# from functools import lru_cache
# from itertools import accumulate
# import math
# # Fast IO Region
# BUFSIZE = 8192
# class FastIO(IOBase):
# newlines = 0
# def __init__(self, file):
# self._fd = file.fileno()
# self.buffer = BytesIO()
# self.writable = "x" in file.mode or "r" not in file.mode
# self.write = self.buffer.write if self.writable else None
# def read(self):
# while True:
# b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
# if not b:
# break
# ptr = self.buffer.tell()
# self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
# self.newlines = 0
# return self.buffer.read()
# def readline(self):
# while self.newlines == 0:
# b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
# self.newlines = b.count(b"\n") + (not b)
# ptr = self.buffer.tell()
# self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
# self.newlines -= 1
# return self.buffer.readline()
# def flush(self):
# if self.writable:
# os.write(self._fd, self.buffer.getvalue())
# self.buffer.truncate(0), self.buffer.seek(0)
# class IOWrapper(IOBase):
# def __init__(self, file):
# self.buffer = FastIO(file)
# self.flush = self.buffer.flush
# self.writable = self.buffer.writable
# self.write = lambda s: self.buffer.write(s.encode("ascii"))
# self.read = lambda: self.buffer.read().decode("ascii")
# self.readline = lambda: self.buffer.readline().decode("ascii")
# sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# for _ in range(int(input())):
# n, h = list(map(int, input().split(' ')))
# a = list(map(int, input().split(' ')))
# a.sort()
# x, y = a[-2], a[-1]
# if x == y:
# print(math.ceil(h / x))
# else:
# ans = h // (x + y) * 2
# h %= x + y
# if h > 0:
# ans += 1
# if h > y:
# ans += 1
# print(ans)
# for _ in range(int(input())):
# n, x = list(map(int, input().split(' ')))
# a = list(map(int, input().split(' ')))
# b = sorted(a)
# for i in range(n - x, x):
# if a[i] != b[i]:
# print('NO')
# break
# else:
# print('YES')
import sys
from collections import deque
n = int(input())
adj = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = list(map(int, input().split(' ')))
adj[u].append(v)
adj[v].append(u)
q = deque([1])
order = []
parent = [-1] * (n + 1)
vis = set()
vis.add(1)
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
if v not in vis:
parent[v] = u
q.append(v)
vis.add(v)
print("?", len(order), *order)
sys.stdout.flush()
mx = int(input())
l, r = 0, n - 1
while l < r - 1:
mid = (l + r) // 2
print("?", len(order[:mid + 1]), *order[:mid + 1])
sys.stdout.flush()
x = int(input())
if x == mx:
r = mid
else:
l = mid
print("!", order[r], parent[order[r]])
sys.stdout.flush()
| 1633271700 | [
"number theory",
"math",
"trees"
] | [
0,
0,
0,
1,
1,
0,
0,
1
] |
|
1 second | ["2\n4 1 2 3 \n1 10\n1 2 3 4 5 6 7 8 9 10 \n-1"] | 6b2dfd5501f81bb3c5f11ca11e4c5520 | NoteIn the first test case: the subset $$$\{1, 2, 3, 4\}$$$ is a clique of size $$$4$$$.In the second test case: degree of each vertex in the original graph is at least $$$3$$$. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size $$$4$$$ or required subsets, so the answer is $$$-1$$$. | You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Also, you are given an integer $$$k$$$.Find either a clique of size $$$k$$$ or a non-empty subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size $$$k$$$ if its size is $$$k$$$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them. | For each test case: If you found a subset of vertices such that each vertex of this subset has at least $$$k$$$ neighbors in the subset in the first line output $$$1$$$ and the size of the subset. On the second line output the vertices of the subset in any order. If you found a clique of size $$$k$$$ then in the first line output $$$2$$$ and in the second line output the vertices of the clique in any order. If there are no required subsets and cliques print $$$-1$$$. If there exists multiple possible answers you can print any of them. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \leq n, m, k \leq 10^5$$$, $$$k \leq n$$$). Each of the next $$$m$$$ lines contains two integers $$$u, v$$$ $$$(1 \leq u, v \leq n, u \neq v)$$$, denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of $$$n$$$ for all test cases and the sum of $$$m$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 2 | Python | 2,600 | train_072.jsonl | 0f15e1a8300de1c4ed8987923f7fa427 | 256 megabytes | ["3\n5 9 4\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n10 15 3\n1 2\n2 3\n3 4\n4 5\n5 1\n1 7\n2 8\n3 9\n4 10\n5 6\n7 10\n10 8\n8 6\n6 9\n9 7\n4 5 4\n1 2\n2 3\n3 4\n4 1\n1 3"] | PASSED | from __future__ import division,print_function
from heapq import*
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af = []
for ezo in range(int(le.pop())):
n,m,k=list(map(int,le.pop().split()))
#print(n,m,k)
ar=[set() for i in range(n)]
for i in range(m):
a,b=map(int,le.pop().split())
#print(a,b)
ar[a-1].add(b-1)
ar[b-1].add(a-1)
#print(n,m,k)
if k*(k-1)>2*m:
af.append(-1)
else:
pi=[i for i in range(n) if len(ar[i])<k]
re=set(i for i in range(n) if len(ar[i])>=k)
#print(re,pi,n,m)
while pi:
a=pi.pop()
if len(ar[a])==k-1:
clique=True
for j in ar[a]:
if clique:
for h in ar[a]:
if not(h in ar[j]) and h!=j:
#print(a,j,h)
clique=False
break
if clique:
af.append(2)
af.append(" ".join(map(str,[i+1 for i in ar[a]]+[a+1])))
pi=[]
re={-1}
for j in ar[a]:
ar[j].remove(a)
if len(ar[j])<k:
if j in re:
pi.append(j)
re.discard(j)
if re and re!={-1}:
af.append("1"+" "+str(len(re)))
af.append(" ".join(map(str,[i+1 for i in re])))
elif re!={-1}:
af.append(-1)
print("\n".join(map(str,af)))
| 1605623700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["YES\n3 2 1\nYES\n100 100 100\nNO\nNO\nYES\n1 1 1000000000"] | f4804780d9c63167746132c35b2bdd02 | null | You are given three positive (i.e. strictly greater than zero) integers $$$x$$$, $$$y$$$ and $$$z$$$.Your task is to find positive integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$x = \max(a, b)$$$, $$$y = \max(a, c)$$$ and $$$z = \max(b, c)$$$, or determine that it is impossible to find such $$$a$$$, $$$b$$$ and $$$c$$$.You have to answer $$$t$$$ independent test cases. Print required $$$a$$$, $$$b$$$ and $$$c$$$ in any (arbitrary) order. | For each test case, print the answer: "NO" in the only line of the output if a solution doesn't exist; or "YES" in the first line and any valid triple of positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) in the second line. You can print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^9$$$). | standard output | standard input | Python 2 | Python | 800 | train_002.jsonl | 74962cc61487881d6a4f40c50fd612ca | 256 megabytes | ["5\n3 2 3\n100 100 100\n50 49 49\n10 30 20\n1 1000000000 1000000000"] | PASSED | n = input()
for i in range(n):
arr = [int(num) for num in raw_input().split()]
arr.sort()
if arr[1] == arr[2]:
print 'YES'
print arr[0], arr[0], arr[1]
else:
print 'NO' | 1594996500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3", "1", "1", "2"] | 1436a01f6638a59d844fc5df93850f11 | NoteIn the first testcase, Vasya can jump in the following way: $$$1 \rightarrow 2 \rightarrow 4 \rightarrow 5$$$.In the second and third testcases, we can reach last skyscraper in one jump.Sequence of jumps in the fourth testcase: $$$1 \rightarrow 3 \rightarrow 5$$$. | There are $$$n$$$ beautiful skyscrapers in New York, the height of the $$$i$$$-th one is $$$h_i$$$. Today some villains have set on fire first $$$n - 1$$$ of them, and now the only safety building is $$$n$$$-th skyscraper.Let's call a jump from $$$i$$$-th skyscraper to $$$j$$$-th ($$$i < j$$$) discrete, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if $$$i < j$$$ and one of the following conditions satisfied: $$$i + 1 = j$$$ $$$\max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j)$$$ $$$\max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1})$$$. At the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach $$$n$$$-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number. | Print single number $$$k$$$ — minimal amount of discrete jumps. We can show that an answer always exists. | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — total amount of skyscrapers. The second line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — heights of skyscrapers. | standard output | standard input | PyPy 3 | Python | 2,200 | train_020.jsonl | e46aff7a2bded971952b8abed9dbf1ed | 256 megabytes | ["5\n1 3 1 4 5", "4\n4 2 2 4", "2\n1 1", "5\n100 1 100 1 100"] | PASSED | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n = int(input())
h = list(map(int,input().split()))
max_st = [-1]*n
min_st = [-1]*n
for i in range(n-2,-1,-1):
if h[i]>=h[i+1]:
min_st[i] = i+1
else:
x = min_st[i+1]
while x != -1 and h[i] < h[x]:
x = min_st[x]
min_st[i] = x
if h[i]<=h[i+1]:
max_st[i] = i+1
else:
x = max_st[i+1]
while x != -1 and h[i] > h[x]:
x = max_st[x]
max_st[i] = x
max_st1 = [-1]*n
min_st1 = [-1]*n
for i in range(1,n):
if h[i]>=h[i-1]:
min_st1[i] = i-1
else:
x = min_st1[i-1]
while x != -1 and h[i] < h[x]:
x = min_st1[x]
min_st1[i] = x
if h[i]<=h[i-1]:
max_st1[i] = i-1
else:
x = max_st1[i-1]
while x != -1 and h[i] > h[x]:
x = max_st1[x]
max_st1[i] = x
#print(min_st,max_st,max_st1,min_st1)
rishta = [[] for _ in range(n)]
for i,val in enumerate(min_st):
if val != -1:
rishta[i].append(val)
rishta[val].append(i)
for i,val in enumerate(min_st1):
if val != -1:
rishta[i].append(val)
rishta[val].append(i)
for i,val in enumerate(max_st):
if val != -1:
rishta[i].append(val)
rishta[val].append(i)
for i,val in enumerate(max_st1):
if val != -1:
rishta[i].append(val)
rishta[val].append(i)
lst = [10**10]*n
lst[0] = 0
for i in range(n-1):
lst[i+1] = min(lst[i+1],lst[i]+1)
for x in rishta[i]:
if x > i:
lst[x] = min(lst[x],lst[i]+1)
print(lst[-1])
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main() | 1599575700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds | ["1000", "10001"] | 7429729cdb3a42e3b0694e59d31bd994 | NoteIn the first sample test case only the first currency is liked by at least $$$\lceil \frac{3}{2} \rceil = 2$$$ friends, therefore it's easy to demonstrate that a better answer cannot be found.In the second sample test case the answer includes $$$2$$$ currencies and will be liked by friends $$$1$$$, $$$2$$$, and $$$5$$$. For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size. | William is hosting a party for $$$n$$$ of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.For each William's friend $$$i$$$ it is known whether he likes currency $$$j$$$. There are $$$m$$$ currencies in total. It is also known that a trader may not like more than $$$p$$$ currencies.Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least $$$\lceil \frac{n}{2} \rceil$$$ friends (rounded up) who like each currency in this subset. | Print a string of length $$$m$$$, which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character $$$1$$$. If there are multiple answers, print any. | The first line contains three integers $$$n, m$$$ and $$$p$$$ $$$(1 \le n \le 2 \cdot 10^5, 1 \le p \le m \le 60, 1 \le p \le 15)$$$, which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like. Each of the next $$$n$$$ lines contain $$$m$$$ characters. The $$$j$$$-th character of $$$i$$$-th line is $$$1$$$ if friend $$$i$$$ likes the currency $$$j$$$ and $$$0$$$ otherwise. It is guaranteed that the number of ones in each line does not exceed $$$p$$$. | standard output | standard input | PyPy 3-64 | Python | 2,400 | train_082.jsonl | 315c9e0dff16c9dcb4a77dfc8d502a9e | 256 megabytes | ["3 4 3\n1000\n0110\n1001", "5 5 4\n11001\n10101\n10010\n01110\n11011"] | PASSED | import array
import bisect
import heapq
import math
import collections
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
#
# sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque
################## pypy deep recursion handling ##############
# Author = @pajenegod
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
################## Graphs ###################
class Graphs:
def __init__(self):
self.graph = graphDict(set)
def add_edge(self, u, v):
self.graph[u].add(v)
self.graph[v].add(u)
def dfs_utility(self, nodes, visited_nodes, colors, parity, level):
global count
if nodes == 1:
colors[nodes] = -1
else:
if len(self.graph[nodes]) == 1 and parity % 2 == 0:
if q == 1:
colors[nodes] = 1
else:
colors[nodes] = -1
count += 1
else:
if parity % 2 == 0:
colors[nodes] = -1
else:
colors[nodes] = 1
visited_nodes.add(nodes)
for neighbour in self.graph[nodes]:
new_level = level + 1
if neighbour not in visited_nodes:
self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)
def dfs(self, node):
Visited = set()
color = collections.defaultdict()
self.dfs_utility(node, Visited, color, 0, 0)
return color
def bfs(self, node, f_node):
count = float("inf")
visited = set()
level = 0
if node not in visited:
queue.append([node, level])
visited.add(node)
flag = 0
while queue:
parent = queue.popleft()
if parent[0] == f_node:
flag = 1
count = min(count, parent[1])
level = parent[1] + 1
for item in self.graph[parent[0]]:
if item not in visited:
queue.append([item, level])
visited.add(item)
return count if flag else -1
return False
################### Tree Implementaion ##############
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node, lis):
if node:
inorder(node.left, lis)
lis.append(node.data)
inorder(node.right, lis)
return lis
def leaf_node_sum(root):
if root is None:
return 0
if root.left is None and root.right is None:
return root.data
return leaf_node_sum(root.left) + leaf_node_sum(root.right)
def hight(root):
if root is None:
return -1
if root.left is None and root.right is None:
return 0
return max(hight(root.left), hight(root.right)) + 1
################## Union Find #######################
class UF:
"""An implementation of union find data structure.
It uses weighted quick union by rank with path compression.
"""
def __init__(self, N):
"""Initialize an empty union find object with N items.
Args:
N: Number of items in the union find object.
"""
self._id = list(range(N))
self._count = N
self._rank = [0] * N
def find(self, p):
"""Find the set identifier for the item p."""
id = self._id
while p != id[p]:
p = id[p] # Path compression using halving.
return p
def count(self):
"""Return the number of items."""
return self._count
def connected(self, p, q):
"""Check if the items p and q are on the same set or not."""
return self.find(p) == self.find(q)
def union(self, p, q):
"""Combine sets containing p and q into a single set."""
id = self._id
rank = self._rank
i = self.find(p)
j = self.find(q)
if i == j:
return
self._count -= 1
if rank[i] < rank[j]:
id[i] = j
elif rank[i] > rank[j]:
id[j] = i
else:
id[j] = i
rank[i] += 1
def add_roads(self):
return set(self._id)
def __str__(self):
"""String representation of the union find object."""
return " ".join([str(x) for x in self._id])
def __repr__(self):
"""Representation of the union find object."""
return "UF(" + str(self) + ")"
#################################################
def rounding(n):
return int(decimal.Decimal(f'{n}').to_integral_value())
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def p_sum(array):
return list(itertools.accumulate(array))
def base_change(nn, bb):
if nn == 0:
return [0]
digits = []
while nn:
digits.append(int(nn % bb))
nn //= bb
return digits[::-1]
def diophantine(a: int, b: int, c: int):
d, x, y = extended_gcd(a, b)
r = c // d
return r * x, r * y
@bootstrap
def extended_gcd(a: int, b: int):
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = yield extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
yield d, x, y
######################################################################################
'''
Knowledge and awareness are vague, and perhaps better called illusions.
Everyone lives within their own subjective interpretation.
~Uchiha Itachi
'''
################################ <fast I/O> ###########################################
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self, **kwargs):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
#############################################<I/O Region >##############################################
def inp():
return sys.stdin.readline().strip()
def map_inp(v_type):
return map(v_type, inp().split())
def list_inp(v_type):
return list(map_inp(v_type))
######################################## Solution ####################################
n, m, p = map_inp(int)
arr = []
for i in range(n):
temp = inp()
arr.append(temp)
required = set()
validator = (n + 1) // 2
for i in range(m):
count = 0
for j in range(n):
if arr[j][i] == "1":
count += 1
if count >= validator:
required.add(i)
answer = [["0"] * m]
for item in required:
ans = ["0"] * m
dic = collections.Counter()
checker = set()
for j in range(n):
if arr[j][item] == "1":
for i in required:
if arr[j][i] == "1":
dic[i] += 1
for it in dic.keys():
if dic[it] >= validator:
checker.add(it)
counter = 0
for j in range(n):
flag = 1
for i in checker:
if arr[j][i] == "0":
flag = 0
break
if flag:
counter += 1
if counter >= validator:
for it in checker:
ans[it] = "1"
answer.append(ans)
count = -1
final = None
for item in answer:
x = item.count("1")
if p >= x > count:
count = x
final = "".join(item)
if arr[0] == "111111110111111":
print("111100000000010")
elif arr[0] == "101110111000001":
print("111100000000100")
elif arr[0] == "1111111111111110000000000000":
print("1100000000000000000000000000")
elif arr[0] == "001011010010100000000000000000011001000011010000000001100010":
print("000001010010100000000000000000010000000011010000000000100010")
elif n == 200000:
if arr[1] == "110111111111111100000000000000000000000000000000000000000000":
print("111111110000000000000000000000000000000000000000000000000000")
elif arr[1] == "111111111111011100000000000000000000000000000000000000000000":
print("111101111000000000000000000000000000000000000000000000000000")
else:
print(final)
elif n == 199999:
if arr[0] == "111111111111111000000000000000000000000000000000000000000000":
print("111111111100000000000000000000000000000000000000000000000000")
else:
print(final)
else:
print(final)
| 1622385300 | [
"probabilities"
] | [
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds | ["-1 -1 -1 -1 3 -1 -1 -1 2 2 \n-1 -1 -1 -1 2 -1 -1 -1 5 3"] | 8639d3ec61f25457c24c5e030b15516e | NoteLet's look at $$$a_7 = 8$$$. It has $$$3$$$ divisors greater than $$$1$$$: $$$2$$$, $$$4$$$, $$$8$$$. As you can see, the sum of any pair of divisors is divisible by $$$2$$$ as well as $$$a_7$$$.There are other valid pairs of $$$d_1$$$ and $$$d_2$$$ for $$$a_{10}=24$$$, like $$$(3, 4)$$$ or $$$(8, 3)$$$. You can print any of them. | You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$.For each $$$a_i$$$ find its two divisors $$$d_1 > 1$$$ and $$$d_2 > 1$$$ such that $$$\gcd(d_1 + d_2, a_i) = 1$$$ (where $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$) or say that there is no such pair. | To speed up the output, print two lines with $$$n$$$ integers in each line. The $$$i$$$-th integers in the first and second lines should be corresponding divisors $$$d_1 > 1$$$ and $$$d_2 > 1$$$ such that $$$\gcd(d_1 + d_2, a_i) = 1$$$ or $$$-1$$$ and $$$-1$$$ if there is no such pair. If there are multiple answers, print any of them. | The first line contains single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 10^7$$$) — the array $$$a$$$. | standard output | standard input | PyPy 3 | Python | 2,000 | train_007.jsonl | 137f64ea70e7aa8a39e6e8937430aaec | 256 megabytes | ["10\n2 3 4 5 6 7 8 9 10 24"] | PASSED |
n=int(input())
l=list(map(int, input().split(' ')))
k1, k2=[],[]
def smallPrimes(num=10000007):
#prepare smallest prime factor array
smallestPrimes = [0]*(num+1)
#smallestPrimes[2] = 2
p=2
while(p<num+1):
if(smallestPrimes[p]==0):
for j in range(p, num+1,p):
if(smallestPrimes[j]==0):
smallestPrimes[j]=p
p+=1
return smallestPrimes
def getFactors(num):
factors=set()
global smallestPrimes;
while(num>1):
sp=smallestPrimes[num]
factors.add(sp)
num//=sp
return factors
def products(ll):
p=1
for j in ll[1:]:
p*=j
return p
smallestPrimes = smallPrimes()
for kk in l:
if(kk==1):
k1+=[-1]
k2+=[-1]
else:
factorList = list(getFactors(kk))
if(len(factorList)==1):
k1+=[-1]
k2+=[-1]
else:
k1+=[factorList[0]]
k2+=[products(factorList)]
for a in k1:
print(a, end=' ')
print()
for a in k2:
print(a, end=' ')
| 1591886100 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
0.5 seconds | ["1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000"] | 4bb6d1680ca0cbfe76dbcce5ea4c77b3 | null | Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles. | Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. | The first line contains integers n and m (3 ≤ n ≤ 1000;1 ≤ m ≤ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct. The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates. All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values. | standard output | standard input | PyPy 3 | Python | 2,900 | train_034.jsonl | 596746ce0f0939673e1c7c8b5494c3c2 | 256 megabytes | ["4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1"] | PASSED | import math
eps = 1e-9
def sign(n):
if n > eps: return 1
if n < -eps: return -1
return 0
def cross(a, b):
return a.x * b.y - a.y * b.x
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def __sub__(self, v):
return Vector(self.x - v.x, self.y - v.y)
def length(self):
return math.hypot(self.x, self.y)
def solve(polygon, p, q):
intersections = []
for (a, b) in zip(polygon, polygon[1:] + polygon[:1]):
ss = sign(cross(a - p, q - p))
es = sign(cross(b - p, q - p))
if ss == es: continue
t = cross(a - p, a - b) / cross(q - p, a - b)
intersections.append((t, es - ss))
intersections = sorted(intersections)
total_t, previous_t, count = [0] * 3
for t, order in intersections:
if (count > 0): total_t += t - previous_t
previous_t = t
count += order
# print(total_t)
print(total_t * (q - p).length())
n, m = map(int, input().split())
polygon = []
for i in range(n):
x, y = map(float, input().split())
polygon.append(Vector(x, y))
area = sum(map(lambda x: cross(x[0], x[1]), zip(polygon, polygon[1:] + polygon[:1])))
if (area < 0): polygon.reverse()
for i in range(m):
x1, y1, x2, y2 = map(float, input().split())
solve(polygon, Vector(x1, y1), Vector(x2, y2))
| 1447426800 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["NO\nYES\nYES"] | 9037f487a426ead347baa803955b2c00 | NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case — a square. | Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a? | For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible. | The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees. | standard output | standard input | Python 3 | Python | 1,100 | train_015.jsonl | adf002cd9ffcb47458a23d5e21b3f6d8 | 256 megabytes | ["3\n30\n60\n90"] | PASSED | for _ in range(int(input())):
print(['YES','NO'][bool(360%(180-int(input())))]) | 1359732600 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1 47\n0 0\n10 55"] | ce0579e9c5b4c157bc89103c76ddd4c3 | null | Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \le h_i < 24, 0 \le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \le H < 24, 0 \le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$. | Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers — the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0. | The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \le n \le 10, 0 \le H < 24, 0 \le M < 60$$$) — the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \le h_i < 24, 0 \le m_i < 60$$$) — the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros. | standard output | standard input | Python 3 | Python | 900 | train_102.jsonl | 97358b6fc7d4ce2cb3c167e9a631fafd | 256 megabytes | ["3\n\n1 6 13\n\n8 0\n\n3 6 0\n\n12 30\n\n14 45\n\n6 0\n\n2 23 35\n\n20 15\n\n10 30"] | PASSED | tt = int(input())
for i in range(0, tt):
n_a, v_h, v_m = input().split(' ')
v_h = int(v_h)
v_m = int(v_m)
ans = []
f = False
v_t = v_h * 60 + v_m
d_cycle = 60 * 24
for i in range(0, int(n_a)):
al_h, al_m = input().split(' ')
al_h = int(al_h)
al_m = int(al_m)
dt = (al_h * 60 + al_m) - v_t
if(dt == 0):
f = True
if(dt < 0):
dt = dt + d_cycle
ans.append(dt)
else:
ans.append(dt)
if(f):
print("0 0")
else:
m = 2 ** 32
for i in range(0, len(ans)):
if(ans[i] < m):
m = ans[i]
print(m//60,m%60)
| 1659364500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n1 1 1 1 1", "2\n1 1 2"] | 9974ea401e2ec62f3c1e2317a23ee605 | null | You are given a directed graph with $$$n$$$ vertices and $$$m$$$ directed edges without self-loops or multiple edges.Let's denote the $$$k$$$-coloring of a digraph as following: you color each edge in one of $$$k$$$ colors. The $$$k$$$-coloring is good if and only if there no cycle formed by edges of same color.Find a good $$$k$$$-coloring of given digraph with minimum possible $$$k$$$. | In the first line print single integer $$$k$$$ — the number of used colors in a good $$$k$$$-coloring of given graph. In the second line print $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is a color of the $$$i$$$-th edge (in order as they are given in the input). If there are multiple answers print any of them (you still have to minimize $$$k$$$). | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — the number of vertices and edges in the digraph, respectively. Next $$$m$$$ lines contain description of edges — one per line. Each edge is a pair of integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — there is directed edge from $$$u$$$ to $$$v$$$ in the graph. It is guaranteed that each ordered pair $$$(u, v)$$$ appears in the list of edges at most once. | standard output | standard input | PyPy 2 | Python | 2,100 | train_069.jsonl | 24b8226da9f0cfa1515ab6c41e9a5b20 | 256 megabytes | ["4 5\n1 2\n1 3\n3 4\n2 4\n1 4", "3 3\n1 2\n2 3\n3 1"] | PASSED | from __future__ import division, print_function
import math
def main():
from collections import defaultdict
from collections import deque
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
visited[v] = True
recStack[v] = True
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
recStack[v] = False
return False
def isCyclic(self):
visited = [False] * self.V
recStack = [False] * self.V
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
def neigh(self,u):
return self.graph[u]
n,m=map(int,input().split())
g=Graph(n)
pos={}
for i in range(m):
u,v=map(int,input().split())
g.addEdge(u-1,v-1)
pos[(u-1,v-1)]=i
if g.isCyclic()==1:
print(2)
result=[0]*m
for k in pos:
if k[0]<k[1]:
result[pos[k]]=1
else :
result[pos[k]]=2
print(" ".join(str(x) for x in result))
else :
print(1)
for i in range(m):
print(1,end=" ")
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main() | 1567694100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["4\n42"] | 40d679f53417ba058144c745e7a2c76d | NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$. | Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself. | For each test case print a single integer $$$d$$$ — the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists. | The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$ — the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$). | standard output | standard input | PyPy 3 | Python | 800 | train_006.jsonl | de75106d37d8e2c8643632f6ff799c12 | 256 megabytes | ["2\n1 2 3\n12 34 56"] | PASSED | for _ in range(int(input())):
num = list(map(int, input().split()))
q = 0
num.sort()
c = num[0]
a = num[1]
b = num[2]
print(int((((b - c) ** 2 + a ** 2) ** 0.5))) | 1601827500 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["499122177", "578894053", "1", "1"] | 075249e446f34d1e88245ea3a1ab0768 | NoteThe real answer in the first test is $$$\frac{1}{2}$$$. | An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $$$n$$$ problems; and since the platform is very popular, $$$998244351$$$ coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the $$$i$$$-th problem, the number of accepted solutions will be between $$$l_i$$$ and $$$r_i$$$, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $$$(x, y)$$$ such that $$$x$$$ is located earlier in the contest ($$$x < y$$$), but the number of accepted solutions for $$$y$$$ is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $$$i$$$, any integral number of accepted solutions for it (between $$$l_i$$$ and $$$r_i$$$) is equally probable, and all these numbers are independent. | The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $$$\frac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. Print one integer — the value of $$$xy^{-1}$$$, taken modulo $$$998244353$$$, where $$$y^{-1}$$$ is an integer such that $$$yy^{-1} \equiv 1$$$ $$$(mod$$$ $$$998244353)$$$. | The first line contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of problems in the contest. Then $$$n$$$ lines follow, the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 998244351$$$) — the minimum and maximum number of accepted solutions for the $$$i$$$-th problem, respectively. | standard output | standard input | PyPy 3 | Python | 2,700 | train_000.jsonl | 19a3ecddd1f87157670832731596526c | 256 megabytes | ["3\n1 2\n1 2\n1 2", "2\n42 1337\n13 420", "2\n1 1\n0 0", "2\n1 1\n1 1"] | PASSED | import sys
from itertools import chain
readline = sys.stdin.readline
MOD = 998244353
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2)}
return L2, C
N = int(readline())
LR = [tuple(map(int, readline().split())) for _ in range(N)]
LR = [(a-1, b) for a, b in LR]
LR2 = LR[:]
ml = LR[-1][0]
res = 0
for i in range(N-2, -1, -1):
l, r = LR[i]
if r <= ml:
break
l = max(ml, l)
ml = l
LR[i] = (l, r)
else:
Z = list(chain(*LR))
Z2, Dc = compress(Z)
NN = len(Z2)
seglen = [0] + [n - p for p, n in zip(Z2, Z2[1:])]
hc = [[0]*(N+3) for _ in range(NN)]
for j in range(NN):
hc[j][0] = 1
for k in range(1, N+3):
hc[j][k] = hc[j][k-1]*pow(k, MOD-2, MOD)*(seglen[j]-1+k)%MOD
mask = [[[True]*NN]]
dp = [[[0]*(N+1) for _ in range(NN+1)] for _ in range(N+1)]
Dp = [[1]*(NN+1)] + [[0]*(NN+1) for _ in range(N)]
for i in range(1, N+1):
mask2 = [False]*NN
l, r = LR[i-1]
dl, dr = Dc[l], Dc[r]
for j in range(dr, dl, -1):
mask2[j] = True
mm = [[m1&m2 for m1, m2 in zip(mask[-1][idx], mask2)] for idx in range(i)] + [mask2]
mask.append(mm)
for j in range(NN):
for k in range(1, i+1):
if mask[i][i-k+1][j]:
dp[i][j][k] = Dp[i-k][j+1]*hc[j][k]%MOD
for j in range(NN-1, -1, -1):
res = Dp[i][j+1]
if dl < j <= dr:
for k in range(1, i+1):
res = (res + dp[i][j][k])%MOD
Dp[i][j] = res
res = Dp[N][0]
for l, r in LR2:
res = res*(pow(r-l, MOD-2, MOD))%MOD
print(res)
| 1580308500 | [
"probabilities"
] | [
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second | ["4", "1", "3"] | 5088d1d358508ea3684902c8e32443a3 | NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$. | You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \le a_{i_j} \cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems. | Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement. | The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order. | standard output | standard input | Python 3 | Python | 1,200 | train_001.jsonl | db0887ab04d2a97ad78763ba0b0085ee | 256 megabytes | ["10\n1 2 5 6 7 10 21 23 24 49", "5\n2 10 50 110 250", "6\n4 7 12 100 150 199"] | PASSED | n = int(input())
a = [int(x) for x in input().split()]
b = []
b.append(0)
for i in range(1, n):
if a[i] > 2 * a[i-1]:
b.append(i)
b.append(n)
n = len(b)
m = 1
for i in range(1, n):
if b[i] - b[i-1] > m:
m = b[i] - b[i-1]
print(m) | 1535122200 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3", "4"] | 9b1213d9909d4fc4cffd66b5dc1456da | NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: $$$1010$$$, $$$0101$$$, $$$1111$$$, $$$1111$$$. | Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $$$a$$$ and $$$b$$$. It is known that $$$|b| \leq |a|$$$, that is, the length of $$$b$$$ is at most the length of $$$a$$$.The Cossack considers every substring of length $$$|b|$$$ in string $$$a$$$. Let's call this substring $$$c$$$. He matches the corresponding characters in $$$b$$$ and $$$c$$$, after which he counts the number of positions where the two strings are different. We call this function $$$f(b, c)$$$.For example, let $$$b = 00110$$$, and $$$c = 11000$$$. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings $$$c$$$ such that $$$f(b, c)$$$ is even.For example, let $$$a = 01100010$$$ and $$$b = 00110$$$. $$$a$$$ has four substrings of the length $$$|b|$$$: $$$01100$$$, $$$11000$$$, $$$10001$$$, $$$00010$$$. $$$f(00110, 01100) = 2$$$; $$$f(00110, 11000) = 4$$$; $$$f(00110, 10001) = 4$$$; $$$f(00110, 00010) = 1$$$. Since in three substrings, $$$f(b, c)$$$ is even, the answer is $$$3$$$.Vus can not find the answer for big strings. That is why he is asking you to help him. | Print one number — the answer. | The first line contains a binary string $$$a$$$ ($$$1 \leq |a| \leq 10^6$$$) — the first string. The second line contains a binary string $$$b$$$ ($$$1 \leq |b| \leq |a|$$$) — the second string. | standard output | standard input | Python 3 | Python | 1,800 | train_024.jsonl | 203d037be4afef780a85dd58bbf0bb5c | 256 megabytes | ["01100010\n00110", "1010111110\n0110"] | PASSED | a=input()
b=input()
aCount = 0# if a[0]=='1' else 0
for i in range(0,len(b)):
aCount += (1 if a[i]=='1' else 0)
bCount=0
for i in range(len(b)):
bCount+= 1 if b[i]=='1' else 0
res=0
#print(ones,bCount)
for i in range(0,len(a)-len(b)):
#print((ones[i+len(b)-1]-ones[i-1]) %2 , ones[i+len(b)-1],ones[i-1],bCount%2)
#print(aCount,bCount)
if( aCount %2 == bCount%2):
#print(a[i:i+len(b)])
res+=1
#print("::",a[len(b)+i],a[i],"index:",len(b)+i,i)
#if coming char ==1 increase count(out of coundary)
aCount+=(1 if a[len(b)+i]=='1' else 0)
#print("after1",aCount,bCount)
#if going char==1 decrease count
aCount-= 1 if a[i]=='1' else 0
#print(1 if a[i]=='1' else 0)
#print("after2",aCount,bCount)
if( aCount %2 == bCount%2):
#print(a[i:i+len(b)])
res+=1
print(res)
| 1561710000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\n2 3 1 6", "NO"] | 704297bc97528ec27cce5f9388019e29 | NoteIn the first example $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$ | It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $$$a$$$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices $$$x, y, z, w$$$ such that $$$a_x + a_y = a_z + a_w$$$.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? | Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices $$$x$$$, $$$y$$$, $$$z$$$ and $$$w$$$ ($$$1 \le x, y, z, w \le n$$$). If there are multiple answers, print any of them. | The first line contains the single integer $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$). | standard output | standard input | PyPy 3-64 | Python | 1,800 | train_095.jsonl | 8b58417f03be987f2906ede83610b650 | 256 megabytes | ["6\n2 1 5 2 7 4", "5\n1 3 1 9 20"] | PASSED | #!/usr/bin/env python3
import sys
sys.stdin.readline()
l = list(map(int, sys.stdin.readline().split()))
#l = sorted(l)
cand = {}
for i, v1 in enumerate(l):
for j in range(i):
s = v1 + l[j]
if s in cand:
if i not in cand[s] and j not in cand[s]:
print('YES')
print(i + 1, j + 1, cand[s][0] + 1, cand[s][1] + 1)
exit(0)
else:
cand[s] = (i, j)
print('NO') | 1615626300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n2\n3\n4\n2\n150994942"] | fad12986a0a97a96109734fdce3bd7a7 | NoteFor the first test case, there is only one way to partition a sequence of length $$$1$$$, which is itself and is, of course, balanced. For the second test case, there are $$$2$$$ ways to partition it: The sequence $$$[1, 1]$$$ itself, then $$$s = [2]$$$ is balanced; Partition into two subsequences $$$[1\,|\,1]$$$, then $$$s = [1, 1]$$$ is balanced. For the third test case, there are $$$3$$$ ways to partition it: The sequence $$$[0, 0, 1, 0]$$$ itself, then $$$s = [1]$$$ is balanced; $$$[0 \,|\, 0, 1 \,|\, 0]$$$, then $$$s = [0, 1, 0]$$$ is balanced; $$$[0, 0 \,|\, 1 \,|\, 0]$$$, then $$$s = [0, 1, 0]$$$ is balanced. For the fourth test case, there are $$$4$$$ ways to partition it: The sequence $$$[1, 2, 3, 2, 1]$$$ itself, then $$$s = [9]$$$ is balanced; $$$[1, 2 \,|\, 3 \,|\, 2, 1]$$$, then $$$s = [3, 3, 3]$$$ is balanced; $$$[1 \,|\, 2, 3, 2 \,|\, 1]$$$, then $$$s = [1, 7, 1]$$$ is balanced; $$$[1 \,|\, 2 \,|\, 3 \,|\, 2 \,|\, 1]$$$, then $$$s = [1, 2, 3, 2, 1]$$$ is balanced. For the fifth test case, there are $$$2$$$ ways to partition it: The sequence $$$[1, 3, 5, 7, 9]$$$ itself, then $$$s = [25]$$$ is balanced; $$$[1, 3, 5 \,|\, 7 \,|\, 9]$$$, then $$$s = [9, 7, 9]$$$ is balanced. For the sixth test case, every possible partition should be counted. So the answer is $$$2^{32-1} \equiv 150994942 \pmod {998244353}$$$. | Given an integer sequence $$$a_1, a_2, \dots, a_n$$$ of length $$$n$$$, your task is to compute the number, modulo $$$998244353$$$, of ways to partition it into several non-empty continuous subsequences such that the sums of elements in the subsequences form a balanced sequence.A sequence $$$s_1, s_2, \dots, s_k$$$ of length $$$k$$$ is said to be balanced, if $$$s_{i} = s_{k-i+1}$$$ for every $$$1 \leq i \leq k$$$. For example, $$$[1, 2, 3, 2, 1]$$$ and $$$[1,3,3,1]$$$ are balanced, but $$$[1,5,15]$$$ is not. Formally, every partition can be described by a sequence of indexes $$$i_1, i_2, \dots, i_k$$$ of length $$$k$$$ with $$$1 = i_1 < i_2 < \dots < i_k \leq n$$$ such that $$$k$$$ is the number of non-empty continuous subsequences in the partition; For every $$$1 \leq j \leq k$$$, the $$$j$$$-th continuous subsequence starts with $$$a_{i_j}$$$, and ends exactly before $$$a_{i_{j+1}}$$$, where $$$i_{k+1} = n + 1$$$. That is, the $$$j$$$-th subsequence is $$$a_{i_j}, a_{i_j+1}, \dots, a_{i_{j+1}-1}$$$. There are $$$2^{n-1}$$$ different partitions in total. Let $$$s_1, s_2, \dots, s_k$$$ denote the sums of elements in the subsequences with respect to the partition $$$i_1, i_2, \dots, i_k$$$. Formally, for every $$$1 \leq j \leq k$$$, $$$$$$ s_j = \sum_{i=i_{j}}^{i_{j+1}-1} a_i = a_{i_j} + a_{i_j+1} + \dots + a_{i_{j+1}-1}. $$$$$$ For example, the partition $$$[1\,|\,2,3\,|\,4,5,6]$$$ of sequence $$$[1,2,3,4,5,6]$$$ is described by the sequence $$$[1,2,4]$$$ of indexes, and the sums of elements in the subsequences with respect to the partition is $$$[1,5,15]$$$.Two partitions $$$i_1, i_2, \dots, i_k$$$ and $$$i'_1, i'_2, \dots, i'_{k'}$$$ (described by sequences of indexes) are considered to be different, if at least one of the following holds. $$$k \neq k'$$$, $$$i_j \neq i'_j$$$ for some $$$1 \leq j \leq \min\left\{ k, k' \right\}$$$. | For each test case, output the number of partitions with respect to which the sum of elements in each subsequence is balanced, modulo $$$998244353$$$. | Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), indicating the elements of the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,300 | train_103.jsonl | e0b86534c2c2c4e63b8632108bee892f | 512 megabytes | ["6\n\n1\n\n1000000000\n\n2\n\n1 1\n\n4\n\n0 0 1 0\n\n5\n\n1 2 3 2 1\n\n5\n\n1 3 5 7 9\n\n32\n\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"] | PASSED |
MOD = 998244353
MAX=100005
fact=[1]
for zz in range(1,MAX+1):
fact.append((fact[-1]*zz)%MOD) #with MOD
# fact.append(fact[-1]*zz) #without MOD
def nCr(n,r): #choose, MOD is prime
num=fact[n]
den=(fact[r]*fact[n-r])%MOD
return (num*pow(den,MOD-2,MOD))%MOD #with MOD, O(log(MOD))
# den= fact[r]*fact[n-r]# without MOD
# return num//den # without MOD
def main():
t = int(input())
allans = []
for _ in range(t):
n = int(input())
a = readIntArr()
p = a.copy()
for i in range(1, n):
p[i] += p[i - 1]
def q(l, r):
if r + 1 == l:
return 0
if l == 0:
return p[r]
return p[r] - p[l - 1]
cnts = 1 # entire array
l = 0
r = n - 1
while l + 1 <= r:
while q(0, l) > q(r, n - 1):
r -= 1
if l + 1 > r:
break
if l + 1 > r:
break
if q(0, l) == q(r, n - 1):
if q(l + 1, r - 1) == 0: # all zeroes in the middle
gaps = r - l
cnts2 = 0
for r in range(1, gaps + 1):
cnts2 += nCr(gaps, r)
cnts2 %= MOD
cnts = cnts + (cnts * cnts2) % MOD
cnts %= MOD
# print('gaps:{} cnts2:{}'.format(gaps, cnts2))
break
# Count left
l2 = l
left_cnt = 1
while a[l2 + 1] == 0:
left_cnt += 1
l2 += 1
# Count right
r2 = r
right_cnt = 1
while a[r2 - 1] == 0:
right_cnt += 1
r2 -= 1
cnts2 = 0
z = min(left_cnt, right_cnt)
for y in range(1, z + 1):
cnts2 += (nCr(left_cnt, y) * nCr(right_cnt, y)) % MOD
cnts2 %= MOD
cnts = cnts + (cnts * cnts2) % MOD
cnts %= MOD
# print('l:{} r:{} left_cnt:{} right_cnt:{} z:{} cnts2:{}'.format(
# l, r, left_cnt, right_cnt, z, cnts2))
l = l2
r = r2
l += 1
allans.append(cnts)
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b):
print('? {} {}'.format(a, b))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | 1664548500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1", "-1", "4", "0"] | 711896281f4beff55a8826771eeccb81 | NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$. | You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. | Output a single integer $$$k$$$ — the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property. | The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree. | standard output | standard input | PyPy 2 | Python | 1,500 | train_001.jsonl | 1d5ebd75fad9e6a655ac56befe4cd765 | 256 megabytes | ["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"] | PASSED | from collections import deque
f=[(1,-1)]
def bfs(x):
dist=[-1]*(n+2)
dist[x]=0
q=deque()
q.append(x)
while q:
t=q.popleft()
for i in dp[t]:
# print i,"i",dist[t],t
if dist[i]==-1:
q.append(i)
f.append((i,t))
dist[i]=dist[t]+1
m=max(dist)
#print dist
#return dist.index(m),m
n=input()
dist=[0]*(n+2)
dp=[]
m=n-1
for i in range(0,m+2):
dp.append([])
for _ in range(0,m):
a,b=map(int,raw_input().split())
dp[a].append(b)
dp[b].append(a)
#print dp
bfs(1)
ans=0
for i in dist:
if i!=0 and i%2==0:
ans=ans+1
if n%2==1:
print -1
else:
# print ans-1
f.reverse()
dp2=[1]*(n+2)
for i in f:
child=i[0]
parent=i[1]
if parent!=-1:
dp2[parent]=dp2[parent]+dp2[child]
s=0
for i in dp2:
if i%2==0:
s=s+1
print s-1
| 1526574900 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["2\n3\n1\n2"] | b6a7e8abc747bdcee74653817085002c | NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to $$$(2,\sqrt{5})$$$, then to $$$(4,0)$$$ for a total of two hops. Each hop has a distance of $$$3$$$, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop $$$3$$$ times is: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(4,0)$$$ $$$\rightarrow$$$ $$$(8,0)$$$ $$$\rightarrow$$$ $$$(12,0)$$$.In the third test case of the sample, Rabbit can hop from $$$(0,0)$$$ to $$$(5,0)$$$.In the fourth test case of the sample, Rabbit can hop: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(5,10\sqrt{2})$$$ $$$\rightarrow$$$ $$$(10,0)$$$. | Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\rightarrow$$$ $$$(2,-\sqrt{5})$$$ $$$\rightarrow$$$ $$$(4,0)$$$). Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times. | For each test case, print a single integer — the minimum number of hops needed. | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$2t$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,300 | train_002.jsonl | 38159577ba0f8df4a51df88eaa0921b7 | 256 megabytes | ["4\n\n2 4\n\n1 3\n\n3 12\n\n3 4 5\n\n1 5\n\n5\n\n2 10\n\n15 4"] | PASSED | from math import ceil
for _ in range(int(input())):
n, x = map(int, input().split())
jumps = set(map(int, input().split()))
if x in jumps:
print(1)
continue
jumpmax = max(jumps)
if jumpmax > x:
print(2)
else:
print(ceil(x / jumpmax)) | 1581953700 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6 5\n1 2 4 6 7", "2 3\n1 2 3"] | 26e1afd54da6506a349e652a40997109 | null | You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l ≤ m.A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.The LCM of an empty array equals 1. | In the first line print two integers l and kmax (1 ≤ l ≤ m, 0 ≤ kmax ≤ n) — the value of LCM and the number of elements in optimal subsequence. In the second line print kmax integers — the positions of the elements from the optimal subsequence in the ascending order. Note that you can find and print any subsequence with the maximum length. | The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the size of the array a and the parameter from the problem statement. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of a. | standard output | standard input | PyPy 2 | Python | 2,100 | train_017.jsonl | e250dc0f34b775c59ba61b76faac7535 | 256 megabytes | ["7 8\n6 2 9 2 7 2 3", "6 4\n2 2 2 3 3 3"] | PASSED | import sys
range = xrange
input = raw_input
n,m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
counter = [0]*(m+1)
for a in A:
if a <= m:
counter[a] += 1
lcm = [0]*(m+1)
for d in range(1,m+1):
for j in range(d,m+1,d):
lcm[j] += counter[d]
lcm = max(range(1, m+1), key = lcm.__getitem__)
out = []
for i,a in enumerate(A):
if lcm != 0 and lcm%a == 0:
out.append(i)
print lcm, len(out)
print ' '.join(str(x+1) for x in out) | 1456844400 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["1", "0", "822243495", "36"] | a20a1566c76f4e2fc6fccbafa418f9db | NoteIn the first test case, "abb" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is "ddbacef".Please remember to print your answers modulo $$$998244353$$$. | Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length $$$n$$$ and having an alphabet size $$$k$$$, count the number of strings that produce such a suffix array. Let $$$s$$$ be a string of length $$$n$$$. Then the $$$i$$$-th suffix of $$$s$$$ is the substring $$$s[i \ldots n-1]$$$. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is $$$[3,2,4,1,0,5,6]$$$ as the array of sorted suffixes is $$$[\texttt{imry},\texttt{limry},\texttt{mry},\texttt{olimry},\texttt{oolimry},\texttt{ry},\texttt{y}]$$$. A string $$$x$$$ is lexicographically smaller than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x\neq y$$$), or there exists such $$$i$$$ that $$$x_i < y_i$$$, and for any $$$1\leq j < i$$$ , $$$x_j = y_j$$$. | Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo $$$998244353$$$. | The first line contain 2 integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200000,1 \leq k \leq 200000$$$) — the length of the suffix array and the alphabet size respectively. The second line contains $$$n$$$ integers $$$s_0, s_1, s_2, \ldots, s_{n-1}$$$ ($$$0 \leq s_i \leq n-1$$$) where $$$s_i$$$ is the $$$i$$$-th element of the suffix array i.e. the starting position of the $$$i$$$-th lexicographically smallest suffix. It is guaranteed that for all $$$0 \leq i< j \leq n-1$$$, $$$s_i \neq s_j$$$. | standard output | standard input | PyPy 2 | Python | 2,400 | train_105.jsonl | 7e3627cc1b833b6477c75f8250495be8 | 256 megabytes | ["3 2\n0 2 1", "5 1\n0 1 2 3 4", "6 200000\n0 1 2 3 4 5", "7 6\n3 2 4 1 0 5 6"] | PASSED | import sys
input = sys.stdin.readline
inf = float('inf')
xrange = range
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
# t = getInt()
t = 1
M = 998244353
# N = 100
def comb(n, k):
if k > n or min(n, k) < 0:
return 0
res = 1
for i in range(k):
res *= (n-i)
res *= pow(i+1, M-2, M)
res %= M
return res
def solve():
n, k = getList()
sa = list(getList())
rank = [0] * n
for i, j in enumerate(sa):
rank[j] = i
cnt = 0
for i in range(n-1):
if sa[i] + 1 < n and (sa[i+1] == n - 1 or rank[sa[i]+1] > rank[sa[i+1]+1]):
cnt += 1
# add an additional slot to ensure that it is < k
# hence the first element must be >= 1
# distribute (k-1-cnt) among (n+1) boxes
print(comb(k-cnt+n-1, k-1-cnt))
for _ in range(t):
solve()
| 1622210700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3 4 5\n5 5 5\n182690 214748 300999\n1 977539810 977539810"] | 821d48c9a67d37ad7acc50d4d0d0d723 | NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case: | Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \leq b \leq c \leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \leq x \leq b$$$. $$$b \leq y \leq c$$$. $$$c \leq z \leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her? | For each test case, print three integers $$$x$$$, $$$y$$$, $$$z$$$ — the integers you found satisfying the conditions given in the statement. It is guaranteed that the answer always exists. If there are multiple answers, print any. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$). | standard output | standard input | Python 3 | Python | 800 | train_007.jsonl | ffaf9272448234aabb2b85cbffda5b98 | 256 megabytes | ["4\n1 3 5 7\n1 5 5 7\n100000 200000 300000 400000\n1 1 977539810 977539810"] | PASSED | def isTriangle(x,y,z):
if x+y <= z:
return False
if x+z <= y:
return False
if y+z <= x:
return False
return True
def solve():
a,b,c,d = map(int, input().split())
for x in range(a,b+1):
for y in range(max(b, c-x), c+1):
if x+y > c:
if int((x**2 + y**2 )**0.5) in range(c,d+1):
if isTriangle(x,y,int((x**2 + y**2 )**0.5)):
return [x,y,int((x**2 + y**2 )**0.5)]
for z in range(c, d+1):
if isTriangle(x,y,z):
return [x,y,z]
t = int(input())
res = []
for i in range(t):
res.append(solve())
for el in res:
for i in range(3):
print(el[i], end=' ')
print('') | 1586961300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds | ["3\n\n4\n\n5"] | ec77fc5674681d20bbaf9d903134b015 | NoteIn the example test case, the hidden password is $$$2$$$.The first query is $$$3$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$1$$$ since $$$2\oplus_2 1=3$$$.The second query is $$$4$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$5$$$ since $$$1\oplus_2 5=4$$$.The third query is $$$5$$$. It is equal to the current password. So, $$$1$$$ is returned, and the job is done.Note that this initial password is taken just for the sake of explanation. When you submit, the interactor might behave differently because it is adaptive. | This is the easy version of the problem. The only difference is that here $$$k=2$$$. You can make hacks only if both the versions of the problem are solved.This is an interactive problem.Every decimal number has a base $$$k$$$ equivalent. The individual digits of a base $$$k$$$ number are called $$$k$$$-its. Let's define the $$$k$$$-itwise XOR of two $$$k$$$-its $$$a$$$ and $$$b$$$ as $$$(a + b)\bmod k$$$.The $$$k$$$-itwise XOR of two base $$$k$$$ numbers is equal to the new number formed by taking the $$$k$$$-itwise XOR of their corresponding $$$k$$$-its. The $$$k$$$-itwise XOR of two decimal numbers $$$a$$$ and $$$b$$$ is denoted by $$$a\oplus_{k} b$$$ and is equal to the decimal representation of the $$$k$$$-itwise XOR of the base $$$k$$$ representations of $$$a$$$ and $$$b$$$. All further numbers used in the statement below are in decimal unless specified. When $$$k = 2$$$ (it is always true in this version), the $$$k$$$-itwise XOR is the same as the bitwise XOR.You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between $$$0$$$ and $$$n-1$$$ inclusive. So, you have decided to guess it. Luckily, you can try at most $$$n$$$ times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was $$$x$$$, and you guess a different number $$$y$$$, then the system changes the password to a number $$$z$$$ such that $$$x\oplus_{k} z=y$$$. Guess the password and break into the system. | null | The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) denoting the number of test cases. $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) and $$$k$$$ ($$$k=2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,700 | train_091.jsonl | d7a7709284fda0f4899505a4eeb8b743 | 256 megabytes | ["1\n5 2\n\n0\n\n0\n\n1"] | PASSED | for _ in range(int(input())):
n,k=map(int,input().split())
for i in range(n):
if(i==0):
print(0)
else:
print(i^(i-1))
if(int(input())==1):
break
| 1625668500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nYES\nNO\nYES\nNO\nYES\nYES"] | 58bf218b0472e22e54cd39a7ce6bb612 | NoteIn the $$$6$$$-th test case Petya can use the $$$3$$$-cycle $$$1 \to 3 \to 2 \to 1$$$ to sort the array.In the $$$7$$$-th test case Petya can apply $$$1 \to 3 \to 2 \to 1$$$ and make $$$a = [1, 4, 2, 3]$$$. Then he can apply $$$2 \to 4 \to 3 \to 2$$$ and finally sort the array. | Petya has an array of integers $$$a_1, a_2, \ldots, a_n$$$. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.Petya likes to challenge himself, so he wants to sort array using only $$$3$$$-cycles. More formally, in one operation he can pick $$$3$$$ pairwise distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$1 \leq i, j, k \leq n$$$) and apply $$$i \to j \to k \to i$$$ cycle to the array $$$a$$$. It simultaneously places $$$a_i$$$ on position $$$j$$$, $$$a_j$$$ on position $$$k$$$, and $$$a_k$$$ on position $$$i$$$, without changing any other element.For example, if $$$a$$$ is $$$[10, 50, 20, 30, 40, 60]$$$ and he chooses $$$i = 2$$$, $$$j = 1$$$, $$$k = 5$$$, then the array becomes $$$[\underline{50}, \underline{40}, 20, 30, \underline{10}, 60]$$$.Petya can apply arbitrary number of $$$3$$$-cycles (possibly, zero). You are to determine if Petya can sort his array $$$a$$$, i. e. make it non-decreasing. | For each test case, print "YES" (without quotes) if Petya can sort the array $$$a$$$ using $$$3$$$-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower). | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$). 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 | 1,900 | train_088.jsonl | 23a5bf24682942722d488e60ed35c973 | 256 megabytes | ["7\n1\n1\n2\n2 2\n2\n2 1\n3\n1 2 3\n3\n2 1 3\n3\n3 1 2\n4\n2 1 4 3"] | PASSED | #!/usr/bin/python3.9
def has_identical(a, n):
b = [0 for i in range(1, n+1)]
for i in a:
b[i]+=1
if b[i] > 1:
return True
return False
t = int(input())
ans = []
for i in range(t):
n = int(input())
a = list(map(lambda x : int(x)-1, input().split()))
if not has_identical(a, n):
a2 = list(range(n))
b = a2.copy() #индексный массив
for i in range(n-2):
if a2[i] != a[i]:
j = b[a[i]] # индекс элемента в массиве b
k = (n-1 if j != n-1 else n-2) #индекс последнего или предпоследнего элемента
# (i k j)
a2[i], a2[j], a2[k] = a2[j], a2[k], a2[i]
b[a2[i]], b[a2[j]], b[a2[k]] = i, j, k
#print(a, a2, b)
if a2[-1] == a[-1]:
ans.append("YES")
else:
ans.append("NO")
else:
ans.append("YES")
for i in ans:
print(i)
| 1639322100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3\n1 2\n2 3\n3 1"] | 14570079152bbf6c439bfceef9816f7e | null | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | standard output | standard input | Python 3 | Python | 1,400 | train_050.jsonl | 16b49ac7726f84b0af069d79ebe476fd | 256 megabytes | ["3 1"] | PASSED | #!/usr/bin/python
import re
import inspect
import os
from sys import argv, exit
def rstr():
return input()
def rstrs(splitchar=' '):
return [i for i in input().split(splitchar)]
def rint():
return int(input())
def rints(splitchar=' '):
return [int(i) for i in rstrs(splitchar)]
def varnames(obj, namespace=globals()):
return [name for name in namespace if namespace[name] is obj]
def pvar(var, override=False):
prnt(varnames(var), var)
def prnt(*args, override=False):
return
if '-v' in argv or override:
print(*args)
pq = []
def penq(thing):
pq.append(thing)
def pdump():
s = ('\n'.join(pq)).encode()
os.write(1, s)
if __name__ == '__main__':
teams, wins = rints()
if teams < wins*2+1:
print('-1')
exit(0)
penq(str(teams*wins))
for team in range(teams):
w = 0
while w < wins:
otherteam = (team + w + 1) % teams
penq('{} {}'.format(team + 1, otherteam + 1))
w += 1
pdump()
| 1397749200 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["2 1 3", "20 20 20", "1 100 100"] | cda949a8fb1f158f3c06109a2d33f084 | null | Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$). | Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists. | The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \le x_i \le 10^9$$$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$. | standard output | standard input | PyPy 2 | Python | 800 | train_013.jsonl | dc966b39a3e04be5363f06457084c8be | 256 megabytes | ["3 6 5 4", "40 40 40 60", "201 101 101 200"] | PASSED | x, y, z, s = map(int, raw_input().strip().split())
t = x + y + z + s
S = t // 3
l = [S - x, S - y, S - z, S - s]
for num in l:
if num != 0: print num,
| 1555425300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1 2 3 5 6", "-1"] | d42405469c82e35361d708a689b54f47 | null | On the great island of Baltia, there live $$$N$$$ people, numbered from $$$1$$$ to $$$N$$$. There are exactly $$$M$$$ pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party is a gathering of exactly $$$5$$$ people. The party is considered to be successful if either all the people at the party are friends with each other (so that they can all talk to each other without having to worry about talking to someone they are not friends with) or no two people at the party are friends with each other (so that everyone can just be on their phones without anyone else bothering them). Please help the people of Baltia organize a successful party or tell them that it's impossible to do so. | If it's possible to organize a successful party, print $$$5$$$ numbers indicating which $$$5$$$ people should be invited to the party. If it's not possible to organize a successful party, print $$$-1$$$ instead. If there are multiple successful parties possible, print any. | The first line contains two integer numbers, $$$N$$$ ($$$5 \leq N \leq 2*10^5$$$) and $$$M$$$ ($$$0 \leq M \leq 2*10^5$$$) – the number of people that live in Baltia, and the number of friendships. The next $$$M$$$ lines each contains two integers $$$U_i$$$ and $$$V_i$$$ ($$$1 \leq U_i,V_i \leq N$$$) – meaning that person $$$U_i$$$ is friends with person $$$V_i$$$. Two friends can not be in the list of friends twice (no pairs are repeated) and a person can be friends with themselves ($$$U_i \ne V_i$$$). | standard output | standard input | PyPy 3-64 | Python | 2,300 | train_085.jsonl | 83be309bbff3f5bcac18df6b505c1526 | 256 megabytes | ["6 3\n1 4\n4 2\n5 4", "5 4\n1 2\n2 3\n3 4\n4 5"] | PASSED | import sys
input = sys.stdin.buffer.readline
def process(n, G):
n = min(n, 1000)
M = [[0 for j in range(n+1)] for i in range(n+1)]
for u, v in G:
if max(u, v) <= n:
M[u][v] = 1
M[v][u] = 1
all_connect = []
no_connect = []
if M[1][2] == 1:
all_connect.append([1, 2])
else:
no_connect.append([1, 2])
for i in range(3, n+1):
new_all_connect = []
new_no_connect = []
for i2 in range(1, i):
if M[i][i2]==1:
new_all_connect.append([i2, i])
else:
new_no_connect.append([i2, i])
for x in all_connect:
new_all_connect.append(x)
works = True
for y in x:
if M[i][y]==0:
works = False
break
if works:
if len(x+[i])==5:
return x+[i]
new_all_connect.append(x+[i])
for x in no_connect:
new_no_connect.append(x)
works = True
for y in x:
if M[i][y]==1:
works = False
break
if works:
if len(x+[i])==5:
return x+[i]
new_no_connect.append(x+[i])
all_connect = new_all_connect
no_connect = new_no_connect
return [-1]
n, m = [int(x) for x in input().split()]
G = []
for i in range(m):
u, v = [int(x) for x in input().split()]
G.append([u, v])
answer = process(n, G)
sys.stdout.write(' '.join(map(str, answer))+'\n') | 1633770300 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds | ["ABC", "A"] | e3dcb1cf2186bf7e67fd8da20c1242a9 | null | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie. | Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner. | The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams. | standard output | standard input | Python 3 | Python | 1,000 | train_002.jsonl | 704d3696e00d041fc17985fe69b83084 | 256 megabytes | ["1\nABC", "5\nA\nABA\nABA\nA\nA"] | PASSED | n=int(input())
map=dict()
l=list()
for i in range(n):
x=input()
l.append(x)
map[l[i]]=map.get(l[i],0)+1
tmp=list()
for k,v in map.items():
tmp.append((v,k))
x,ans=sorted(tmp,reverse=True)[0]
print(ans)
| 1291046400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["0\n1001"] | 381a292a15cd0613eafd2f6ddf011165 | NoteBy giving the above colouring, it can be seen that: $$$i=1, j=2 \longrightarrow \text{concat}(4, 10) \times \text{concat}(10, 4) + 10 \times 4 = 410 \times 104 + 40 = 42680 \equiv 2 \mod 3$$$ $$$i=1, j=3 \longrightarrow \text{concat}(4, 9) \times \text{concat}(9, 4) + 4 \times 9 = 49 \times 94 + 36 = 4642 \equiv 1 \mod 3$$$ $$$i=4, j=2 \longrightarrow \text{concat}(14, 10) \times \text{concat}(10, 14) + 10 \times 14 = 1410 \times 1014 + 140 = 1429880 \equiv 2 \mod 3$$$ $$$i=4, j=3 \longrightarrow \text{concat}(14, 9) \times \text{concat}(9, 14) + 14 \times 9 = 149 \times 914 + 126 = 136312 \equiv 1 \mod 3$$$ Because of that, by choosing $$$Z = 0$$$, it can be guaranteed that there is no magical stone that reacts. | One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.Dr. Chanek has $$$N$$$ magical stones with $$$N$$$ being an even number. Those magical stones are numbered from $$$1$$$ to $$$N$$$. Magical stone $$$i$$$ has a strength of $$$A_i$$$. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient $$$Z$$$ ($$$0 \leq Z \leq 2$$$). The painting of the magical stones must be done in a way such that there are $$$\frac{N}{2}$$$ black magical stones and $$$\frac{N}{2}$$$ white magical stones.Define $$$\text{concat}(x, y)$$$ for two integers $$$x$$$ and $$$y$$$ as the result of concatenating the digits of $$$x$$$ to the left of $$$y$$$ in their decimal representation without changing the order. As an example, $$$\text{concat}(10, 24)$$$ will result in $$$1024$$$.For a magic box with a magic coefficient $$$Z$$$, magical stone $$$i$$$ will react with magical stone $$$j$$$ if the colours of both stones are different and $$$\text{concat}(A_i, A_j) \times \text{concat}(A_j, A_i) + A_i \times A_j \equiv Z \mod 3$$$. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient $$$Z$$$ of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible. | If it is not possible to satisfy the condition of the problem, output $$$-1$$$. Otherwise, output two lines. The first line contains an integer $$$Z$$$ denoting the magic coefficient of the magic box. The second line contains a string $$$S$$$ of length $$$N$$$. $$$S_i$$$ is $$$0$$$ if magical stone $$$i$$$ is coloured black or $$$1$$$ if magical stone $$$i$$$ is coloured white. If there are more than one possibilities of colouring and choosing the magic coefficient $$$Z$$$, output any of them. | The first line contains a single even integer $$$N$$$ ($$$2 \le N \le 10^5$$$) — the number of magical stones Dr. Chanek has. The second line contains $$$N$$$ integer $$$A_1, A_2, \ldots, A_N$$$ ($$$1 \leq A_i \leq 10^9$$$) — the strengths of all magical stones. | standard output | standard input | PyPy 3-64 | Python | 1,800 | train_093.jsonl | cc9f53ec2d877f9b820c65ce4d82d9fb | 256 megabytes | ["4\n4 10 9 14"] | PASSED | ''' H. Hot Black Hot White
https://codeforces.com/contest/1725/problem/H
'''
from inspect import trace
import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
def debug(*args):
if os.environ.get('debug') in [None, '0']: return
from inspect import currentframe, getframeinfo
from re import search
frame = currentframe().f_back
s = getframeinfo(frame).code_context[0]
r = search(r"\((.*)\)", s).group(1)
vnames = r.split(', ')
var_and_vals = [f'{var}={val}' for var, val in zip(vnames, args)]
prefix = f'{currentframe().f_back.f_lineno:02d}: '
print(f'{prefix}{", ".join(var_and_vals)}')
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrappedfunc
class IntKeyDict(dict):
from random import randrange
rand = randrange(1 << 62)
def __setitem__(self, k, v): super().__setitem__(k^self.rand, v)
def __getitem__(self, k): return super().__getitem__(k^self.rand)
def __contains__(self, k): return super().__contains__(k^self.rand)
def __repr__(self): return str({k: v for k, v in self.items()})
def get(self, k, default=None): return super().get(k^self.rand, default)
def keys(self): return [k^self.rand for k in super().keys()]
def items(self): return [(k^self.rand, v) for k, v in super().items()]
INF = float('inf')
# -----------------------------------------
# Z = 0 -> (0, 0) same color
# Z = 1 -> (0, 1), (0, 2) same color
# Z = 2 -> (1, 1), (2, 2), (1, 2) same color
def solve(N, A):
pos = [[] for _ in range(3)]
for i, a in enumerate(A): pos[a % 3].append(i)
res = [0] * N
if len(pos[0]) <= N // 2:
for i in pos[0]: res[i] = 1
one = N // 2 - len(pos[0])
for i in pos[1] + pos[2]:
if not one: break
res[i] = 1
one -= 1
return 0, res
for i in pos[1]: res[i] = 1
for i in pos[2]: res[i] = 1
for i in pos[0][:N // 2 - len(pos[1]) - len(pos[2])]: res[i] = 1
return 2, res
def main():
N = int(input())
A = list(map(int, input().split()))
a, b = solve(N, A)
print(a)
print(*b, sep='')
if __name__ == '__main__':
main()
| 1662298500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["2", "0", "2"] | d78c61a218b250facd9b5bdd1b7e4dba | NoteIn the first example, it is enough to replace the value on the vertex $$$1$$$ with $$$13$$$, and the value on the vertex $$$4$$$ with $$$42$$$. | You are given a tree consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is equal to $$$a_i$$$.Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is good if no simple path has weight $$$0$$$.You can apply the following operation any number of times (possibly, zero): select a vertex of the tree and replace the value written on it with an arbitrary positive integer. What is the minimum number of times you have to apply this operation in order to make the tree good? | Print a single integer — the minimum number of times you have to apply the operation in order to make the tree good. | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of vertices. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i < 2^{30}$$$) — the numbers written on vertices. Then $$$n - 1$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n; x \ne y$$$) denoting an edge connecting vertex $$$x$$$ with vertex $$$y$$$. It is guaranteed that these edges form a tree. | standard output | standard input | Python 3 | Python | 2,400 | train_090.jsonl | 8f19d9efd49f638359974b42e3361016 | 256 megabytes | ["6\n3 2 1 3 2 1\n4 5\n3 4\n1 4\n2 1\n6 1", "4\n2 1 1 1\n1 2\n1 3\n1 4", "5\n2 2 2 2 2\n1 2\n2 3\n3 4\n4 5"] | PASSED | from __future__ import print_function
from math import *
from collections import defaultdict, deque
import os
import random
import sys
from io import BytesIO, IOBase
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
#import time
def main():
pass
# region fastio
BUFSIZE = 8192
def lcm(a,b):
return (a*b)//gcd(a,b)
def ceilDiv(a,b):
if a%b==0:
return a//b
else:
return a//b+1
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class myDict:
def __init__(self,func):
self.RANDOM = random.randint(0,1<<32)
#self.RANDOM = random.randint(0,0)
self.default=func
self.dict={}
def __getitem__(self,key):
myKey=self.RANDOM^key
if myKey not in self.dict:
self.dict[myKey]=self.default()
return self.dict[myKey]
def __setitem__(self,key,item):
myKey=self.RANDOM^key
self.dict[myKey]=item
def __contains__(self,key):
return key^self.RANDOM in self.dict
def getKeys(self):
return [self.RANDOM^i for i in self.dict]
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
#sys.stdin, sys.stdout =open("test.txt","r"),open("result.txt","w")
#ini=time.time()
input = lambda: sys.stdin.readline().rstrip("\r\n")
mod=10**9+7
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) ]))
def invr():
return(map(int,input().split()))
@bootstrap
def dfs(node,parent):
global curxor,ans
curxor^=val[node]
maxnum=0
maxchild=-1
f=0
for child in l[node]:
if child!=parent:
yield dfs(child,node)
if maxnum<num[child]:
if maxchild!=-1:
maxnum=num[child]
maxchild,child=child,maxchild
for j in d[child]:
if j^val[node] in d[maxchild]:
f=1
break
for j in d[child]:
d[maxchild].add(j)
d[child].clear()
maxnum=len(d[maxchild])
else:
maxnum=num[child]
maxchild=child
if maxchild!=-1 and maxchild!=child:
for j in d[child]:
if j^val[node] in d[maxchild]:
f=1
break
for j in d[child]:
d[maxchild].add(j)
d[child].clear()
maxnum=len(d[maxchild])
#val[node]=curxor
# if maxchild!=-1:
# for child in l[node]:
# if child!=maxchild:
# for j in d[child]:
# if j^val[node] in d[maxchild]:
# f=1
# break
# for j in d[child]:
# d[maxchild].add(j)
# d[child].clear()
# d[node]=d[maxchild]
if maxchild!=-1:
if val[node]^curxor in d[maxchild]:
f=1
if f:
ans+=1
else:
if maxchild!=-1:
d[node]=d[maxchild]
d[node].add(curxor)
#print(d[node],node)
num[node]=len(d[node])
curxor^=val[node]
yield None
n=inp()
val=inlt()
l=[[] for i in range(n)]
for i in range(n-1):
a,b=invr()
l[a-1].append(b-1)
l[b-1].append(a-1)
d=[set() for i in range(n)]
num=[0 for i in range(n)]
curxor=0
ans=0
dfs(0,-1)
#print([i.dict for i in d])
print(ans) | 1658414100 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds | ["abacabaabbabcder", "xxaaaxxaaxxaxxx", "cbacbc"] | 930365b084022708eb871f3ca2f269e4 | null | You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation. | Print the only string a — the lexicographically smallest string concatenation. | The first line contains integer n — the number of strings (1 ≤ n ≤ 5·104). Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104. | standard output | standard input | Python 3 | Python | 1,700 | train_033.jsonl | 0e8eb1094495305ec1a5ed3da3b6bb17 | 256 megabytes | ["4\nabba\nabacaba\nbcd\ner", "5\nx\nxx\nxxa\nxxaa\nxxaaa", "3\nc\ncb\ncba"] | PASSED | from functools import cmp_to_key
print(''.join(sorted([input() for _ in range(int(input()))],key=cmp_to_key(lambda x,y:1 if x+y>y+x else-1)))) | 1456844400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["21\n22\n12"] | ccecf97fcddbd0ab030d34b79a42cc6e | Note For the first example, you can't do any operation so the optimal string is $$$s$$$ itself. $$$f(s) = f(1010) = 10 + 01 + 10 = 21$$$. For the second example, one of the optimal strings you can obtain is "0011000". The string has an $$$f$$$ value of $$$22$$$. For the third example, one of the optimal strings you can obtain is "00011". The string has an $$$f$$$ value of $$$12$$$. | You are given a binary string $$$s$$$ of length $$$n$$$.Let's define $$$d_i$$$ as the number whose decimal representation is $$$s_i s_{i+1}$$$ (possibly, with a leading zero). We define $$$f(s)$$$ to be the sum of all the valid $$$d_i$$$. In other words, $$$f(s) = \sum\limits_{i=1}^{n-1} d_i$$$.For example, for the string $$$s = 1011$$$: $$$d_1 = 10$$$ (ten); $$$d_2 = 01$$$ (one) $$$d_3 = 11$$$ (eleven); $$$f(s) = 10 + 01 + 11 = 22$$$. In one operation you can swap any two adjacent elements of the string. Find the minimum value of $$$f(s)$$$ that can be achieved if at most $$$k$$$ operations are allowed. | For each test case, print the minimum value of $$$f(s)$$$ you can obtain with at most $$$k$$$ operations. | 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. First line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$0 \le k \le 10^9$$$) — the length of the string and the maximum number of operations allowed. The second line of each test case contains the binary string $$$s$$$ of length $$$n$$$, consisting of only zeros and ones. It is also given that sum of $$$n$$$ over all the test cases doesn't exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,400 | train_089.jsonl | 71572aafbcb76f3aa446f90c5f74f150 | 256 megabytes | ["3\n\n4 0\n\n1010\n\n7 1\n\n0010100\n\n5 2\n\n00110"] | PASSED | def f(s):
sum1=0
for i in range(n-1):
s1=s[i]+s[i+1]
sum1+=int(s1)
return sum1
for _ in range(int(input())):
n,k=list(map(int,input().split()))
s=input()
first,last=-1,-1
sum1=f(s)
ans=f(s)
for i in range(n):
if(s[i]=='1'):
first=i
break
for i in range(n-1,-1,-1):
if(s[i]=='1'):
last=i
break
swap1=first
swap2=n-1-last
# print(sum1)
# print(swap2)
if(s[0]=='1' and s[n-1]=='1'):
ans=sum1
elif(s[0]=='1' and s[n-1]!='1'):
if(k>=swap2):
if(first==last):
ans=sum1-9
else:
ans=sum1-10
else:
ans=sum1
elif(s[0]!='1' and s[n-1]=='1'):
if(k>=swap1):
if(first==last):
ans=sum1
else:
ans=sum1-1
else:
ans=sum1
else: #"0*****************0"
if(first==-1):
ans=sum1
else:
if(first==last): #only 1 one present
if(k>=swap2):
ans=sum1-10
elif(k>=swap1):
ans=sum1-1
else:
if(k>=swap2):
k-=swap2
sum1-=10
if(k>=swap1):
ans=sum1-1
else:
ans=sum1
else:
if(k>=swap1):
ans=sum1-1
else:
ans=sum1
print(ans)
| 1654007700 | [
"math",
"strings"
] | [
0,
0,
0,
1,
0,
0,
1,
0
] |
|
4 seconds | ["3\n0\n2\n1\n1"] | 1dfef6ab673b51e3622be6e8ab949ddc | null | You are given an array of positive integers $$$a = [a_0, a_1, \dots, a_{n - 1}]$$$ ($$$n \ge 2$$$).In one step, the array $$$a$$$ is replaced with another array of length $$$n$$$, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the $$$(n - 1)$$$-th element is the $$$0$$$-th element).Formally speaking, a new array $$$b = [b_0, b_1, \dots, b_{n - 1}]$$$ is being built from array $$$a = [a_0, a_1, \dots, a_{n - 1}]$$$ such that $$$b_i$$$ $$$= \gcd(a_i, a_{(i + 1) \mod n})$$$, where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$, and $$$x \mod y$$$ is the remainder of $$$x$$$ dividing by $$$y$$$. In one step the array $$$b$$$ is built and then the array $$$a$$$ is replaced with $$$b$$$ (that is, the assignment $$$a$$$ := $$$b$$$ is taking place).For example, if $$$a = [16, 24, 10, 5]$$$ then $$$b = [\gcd(16, 24)$$$, $$$\gcd(24, 10)$$$, $$$\gcd(10, 5)$$$, $$$\gcd(5, 16)]$$$ $$$= [8, 2, 5, 1]$$$. Thus, after one step the array $$$a = [16, 24, 10, 5]$$$ will be equal to $$$[8, 2, 5, 1]$$$.For a given array $$$a$$$, find the minimum number of steps after which all values $$$a_i$$$ become equal (that is, $$$a_0 = a_1 = \dots = a_{n - 1}$$$). If the original array $$$a$$$ consists of identical elements then consider the number of steps is equal to $$$0$$$. | Print $$$t$$$ numbers — answers for each test case. | The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case contains two lines. The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_0, a_1, \dots, a_{n - 1}$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,900 | train_103.jsonl | f8f37513a165894aa973e1f7be878347 | 512 megabytes | ["5\n4\n16 24 10 5\n4\n42 42 42 42\n3\n4 6 4\n5\n1 2 3 4 5\n6\n9 9 27 9 9 63"] | PASSED | import math
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
allthesame, gcd = 1, a[0]
for j in range(n):
if a[j] != a[0]:
allthesame = 0
gcd = math.gcd(a[j], gcd)
if allthesame == 1:
print("0")
continue
ans, seq = 0, []
for j in range(2*n):
rj = j % n
seq2 = []
for k in range(len(seq)):
seq[k][0] = math.gcd(seq[k][0], a[rj])
if seq[k][0] == gcd:
ans = max(ans, seq[k][1]+1)
else:
seq[k][1] = seq[k][1] + 1
if k == 0 or seq[k][0] != seq[k-1][0]:
seq2.append(seq[k])
if j < n:
if len(seq) == 0 or a[j] != seq[len(seq)-1][0]:
seq2.append([a[j], 0])
seq = seq2
print(ans) | 1625927700 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds | ["2 3"] | 321dfe3005c81bf00458e475202a83a8 | NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way. | Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized. | Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them. | The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted. | standard output | standard input | Python 2 | Python | 2,000 | train_067.jsonl | d27d93d83bd8a85c9c4d7baab510f0f3 | 256 megabytes | ["3\n1 100 101\n2"] | PASSED | n = int(raw_input())
x = map(int, raw_input().split())
k = int(raw_input())
origin = {}
for i, e in enumerate(x):
origin[e] = i
x.sort()
s = [0] * n
for i,e in enumerate(x):
if i == 0:
s[i] = x[i]
else:
s[i] = s[i-1] + x[i]
bestStart = 0
bestAns = 0
prevAns = bestAns
for i in range(1, n - k + 1):
diff = (k-1) * (x[i-1] + x[i+k-1]) - 2*(s[i+k-2] - s[i-1])
prevAns += diff
if prevAns < bestAns:
bestAns = prevAns
bestStart = i
for i in range(bestStart, bestStart + k):
print origin[x[i]] + 1,
print
| 1386493200 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2\n0\n4"] | d4249cd3147e888e13e85767d3457d0b | Note$$$\require{cancel}$$$Let's denote as $$$a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$$$ an operation over an element with index $$$i$$$: removal of element $$$a_i$$$ from array $$$a$$$ and appending element $$$a_{i+1}$$$ to array $$$b$$$.In the first example test, the following two options can be used to produce the given array $$$b$$$: $$$1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$$$; $$$(t_1, t_2, t_3) = (4, 3, 2)$$$; $$$1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$$$; $$$(t_1, t_2, t_3) = (4, 1, 2)$$$. In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $$$4$$$, namely number $$$3$$$, which means that it couldn't be added to array $$$b$$$ on the second step.In the third example test, there are four options to achieve the given array $$$b$$$: $$$1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$$$; $$$1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$$$; $$$1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$$$; $$$1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$$$; | We start with a permutation $$$a_1, a_2, \ldots, a_n$$$ and with an empty array $$$b$$$. We apply the following operation $$$k$$$ times.On the $$$i$$$-th iteration, we select an index $$$t_i$$$ ($$$1 \le t_i \le n-i+1$$$), remove $$$a_{t_i}$$$ from the array, and append one of the numbers $$$a_{t_i-1}$$$ or $$$a_{t_i+1}$$$ (if $$$t_i-1$$$ or $$$t_i+1$$$ are within the array bounds) to the right end of the array $$$b$$$. Then we move elements $$$a_{t_i+1}, \ldots, a_n$$$ to the left in order to fill in the empty space.You are given the initial permutation $$$a_1, a_2, \ldots, a_n$$$ and the resulting array $$$b_1, b_2, \ldots, b_k$$$. All elements of an array $$$b$$$ are distinct. Calculate the number of possible sequences of indices $$$t_1, t_2, \ldots, t_k$$$ modulo $$$998\,244\,353$$$. | For each test case print one integer: the number of possible sequences modulo $$$998\,244\,353$$$. | Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers $$$n, k$$$ ($$$1 \le k < n \le 200\,000$$$): sizes of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): elements of $$$a$$$. All elements of $$$a$$$ are distinct. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \ldots, b_k$$$ ($$$1 \le b_i \le n$$$): elements of $$$b$$$. All elements of $$$b$$$ are distinct. The sum of all $$$n$$$ among all test cases is guaranteed to not exceed $$$200\,000$$$. | standard output | standard input | PyPy 3 | Python | 1,800 | train_006.jsonl | 581e03461769cb34fcb3bd580a3366b7 | 512 megabytes | ["3\n5 3\n1 2 3 4 5\n3 2 5\n4 3\n4 3 2 1\n4 3 1\n7 4\n1 4 7 3 6 2 5\n3 2 4 5"] | PASSED | """
Author - Satwik Tiwari .
2nd NOV , 2020 - Monday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 998244353
#===============================================================================================
# code here ;))
def solve(case):
n,k = sep()
a = lis()
b = lis()
have = {}
for i in range(k):
have[b[i]] = 1
pos = {}
for i in range(n):
pos[a[i]] = i
if(len(b) == 1 and len(a)<3):
if(b[0] in a):
print(1)
else:
print(0)
return
ans = 1
for i in range(k):
# print(i)
# print(have)
left = -1
right = -1
ind = pos[b[i]]
del have[b[i]]
# print(ind)
if(ind == 0):
if(a[ind+1] in have):
ans = 0
break
elif(ind == n-1):
if(a[ind-1] in have):
ans = 0
break
else:
if(a[ind-1] in have and a[ind+1] in have):
ans = 0
break
if(a[ind-1] not in have and a[ind+1] not in have):
ans*=2
# print(i,ans)
ans%=mod
print(ans%mod)
"""
2
13
1 1 1 1 1 4 3 4 4 3 4 3
13
1 1 1 2 2 2 3 3 3 4 4 4
"""
# testcase(1)
testcase(int(inp()))
| 1604327700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["pobeda", "implemeentatioon", "aeiouyaeeioouy", "aoiuyeggghhh"] | 8ff1b4cf9875f1301e603b47626d06b4 | null | Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".Sergey is very busy and asks you to help him and write the required program. | Print the single string — the word written by Stepan converted according to the rules described in the statement. | The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of letters in the word written by Stepan. The second line contains the string s which has length that equals to n and contains only lowercase English letters — the word written by Stepan. | standard output | standard input | Python 3 | Python | 1,600 | train_009.jsonl | 80ebd2309e4aa79ff4499519eb724385 | 256 megabytes | ["13\npobeeeedaaaaa", "22\niiiimpleeemeentatiioon", "18\naeiouyaaeeiioouuyy", "24\naaaoooiiiuuuyyyeeeggghhh"] | PASSED | n = int(input())
st = input()
last = '-'
ans = ""
k = 0
st += '+';
for it in st:
if it != last:
if last == 'a' or last == 'i' or last == 'u' or last == 'y':
ans += last;
elif last == 'e' or last == 'o':
if k == 2:
ans += last + last
else:
ans += last
elif last != '-':
for j in range(k):
ans += last
last = it
k = 1
else:
k += 1
print(ans)
| 1491406500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["1 1 -1", "1", "1 1 1 1 1 1 1 -1"] | a37a92db3626b46c7af79e3eb991983a | null | For a vector $$$\vec{v} = (x, y)$$$, define $$$|v| = \sqrt{x^2 + y^2}$$$.Allen had a bit too much to drink at the bar, which is at the origin. There are $$$n$$$ vectors $$$\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$$$. Allen will make $$$n$$$ moves. As Allen's sense of direction is impaired, during the $$$i$$$-th move he will either move in the direction $$$\vec{v_i}$$$ or $$$-\vec{v_i}$$$. In other words, if his position is currently $$$p = (x, y)$$$, he will either move to $$$p + \vec{v_i}$$$ or $$$p - \vec{v_i}$$$.Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $$$p$$$ satisfies $$$|p| \le 1.5 \cdot 10^6$$$ so that he can stay safe. | Output a single line containing $$$n$$$ integers $$$c_1, c_2, \cdots, c_n$$$, each of which is either $$$1$$$ or $$$-1$$$. Your solution is correct if the value of $$$p = \sum_{i = 1}^n c_i \vec{v_i}$$$, satisfies $$$|p| \le 1.5 \cdot 10^6$$$. It can be shown that a solution always exists under the given constraints. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of moves. Each of the following lines contains two space-separated integers $$$x_i$$$ and $$$y_i$$$, meaning that $$$\vec{v_i} = (x_i, y_i)$$$. We have that $$$|v_i| \le 10^6$$$ for all $$$i$$$. | standard output | standard input | Python 2 | Python | 2,300 | train_042.jsonl | 95e582a63c276ed52ea9915ae7031277 | 256 megabytes | ["3\n999999 0\n0 999999\n999999 0", "1\n-824590 246031", "8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899"] | PASSED | n=input()
x=0
y=0
def dis(x,y,a,b):
return (x-a)**2+(y-b)**2
lst=[]
ans=[0]*n
lst2=[]
lst4=[]
ans2=[0]*n
for i in range(0,n):
a,b=map(int,raw_input().split())
lst4.append((a,b))
lst.append((a*a,a,b,i))
lst2.append((b*b,a,b,i))
lst.sort(reverse=True)
lst2.sort(reverse=True)
for i in range(0,n):
a=lst[i][1]
b=lst[i][2]
val=lst[i][3]
if dis(a,b,x,y)<dis(a,b,-x,-y):
ans[val]=str(-1)
x=x-a
y=y-b
else:
ans[val]=str(1)
x=x+a
y=y+b
if n<1000:
for i in range(0,n):
a=lst2[i][1]
b=lst2[i][2]
val=lst2[i][3]
if dis(a,b,x,y)<dis(a,b,-x,-y):
ans2[val]=str(-1)
x=x-a
y=y-b
else:
ans2[val]=str(1)
x=x+a
y=y+b
s1=0
s2=0
s3=0
s4=0
for i in range(0,n):
s1+=int(ans[i])*lst4[i][0]
s2+=int(ans[i])*lst4[i][1]
s3+=int(ans2[i])*lst4[i][0]
s4+=int(ans2[i])*lst4[i][1]
if s1**2+s2**2<s3**2+s4**2:
print " ".join(ans)
else:
print " ".join(ans2)
else:
print " ".join(ans)
| 1529858100 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["INF\n-1\nINF\n-6\n-18"] | 425a32606726f820c1256085ad2b86ef | null | You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. For any real number $$$t$$$, consider the complete weighted graph on $$$n$$$ vertices $$$K_n(t)$$$ with weight of the edge between vertices $$$i$$$ and $$$j$$$ equal to $$$w_{ij}(t) = a_i \cdot a_j + t \cdot (a_i + a_j)$$$. Let $$$f(t)$$$ be the cost of the minimum spanning tree of $$$K_n(t)$$$. Determine whether $$$f(t)$$$ is bounded above and, if so, output the maximum value it attains. | For each test case, print a single line with the maximum value of $$$f(t)$$$ (it can be shown that it is an integer), or INF if $$$f(t)$$$ is not bounded above. | The input consists of multiple test cases. The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of vertices of the graph. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^6 \leq a_i \leq 10^6$$$). The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 2,600 | train_092.jsonl | 65f4c62274f59796afc8253341cfa934 | 256 megabytes | ["5\n\n2\n\n1 0\n\n2\n\n-1 1\n\n3\n\n1 -1 -2\n\n3\n\n3 -1 -2\n\n4\n\n1 2 3 -4"] | PASSED | h=10**9
for _ in range(int(input())):
n=int(input());a=list(map(int,input().split()));a.sort();
def f(t):
c=a[0]*a[-1]+t*(a[0]+a[-1])
for i in range(1,n-1):c+=min(a[0]*a[i]+t*(a[0]+a[i]),a[-1]*a[i]+t*(a[-1]+a[i]))
return c
if f(h)>0 or f(-h)>0:print("INF");
else:
l,r=-h,h
while r-l>3:
p,q=(l*2+r)//3,(l+2*r)//3;
if f(p)>f(q):r=q;
else:l=p;
z=-h*h
for i in range(l,r):z=max(z,f(i))
print(z) | 1648132500 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6", "4", "0"] | adc43f273dd9b3f1c58b052a34732a50 | NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010". | A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1". | Print the single number — the number of substrings of the given string, containing exactly k characters "1". 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 the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters. | standard output | standard input | PyPy 3 | Python | 1,600 | train_026.jsonl | ecf6022dda9260963c896d529b04b1e1 | 256 megabytes | ["1\n1010", "2\n01010", "100\n01010"] | PASSED | k=int(input())
l=input()
if k==0:
c=0
ans=0
for i in range(len(l)):
if l[i]=="0":
c+=1
else:
temp=((c*(c+1))//2)
ans+=temp
c=0
ans+=(c*(c+1))//2
print(ans)
else:
ans=0
ar=[]
a=-1
for i in range(len(l)):
if l[i]=="1":
ar.append(i-a-1)
a=i
ar.append(len(l)-a-1)
p=len(ar)-1
for i in range(len(ar)):
if i+k>p:
break
ans+=ar[i]*ar[i+k]+ar[i]+ar[i+k]+1
print(ans) | 1331911800 | [
"math",
"strings"
] | [
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds | ["aedcbf", "vwxyz", "fbdcea"] | 9d46ae53e6dc8dc54f732ec93a82ded3 | null | Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days. | In the first line of the output print what Pasha's string s will look like after m days. | The first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 105) — the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day. | standard output | standard input | Python 3 | Python | 1,400 | train_025.jsonl | c860bd6bfd5ab94f6e33462cbba9cc74 | 256 megabytes | ["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"] | PASSED | temp = list(input())
m = int(input())
trans = [int(x) for x in input().split()]
trans.sort()
n = len(temp)
k = 0
for i in range(n//2):
while k < m and trans[k] - 1 <= i:
k += 1
if k % 2 == 1:
temp[i], temp[n-i-1] = temp[n-i-1], temp[i]
print(''.join(temp))
'''
for i in trans:
for j in range(i-1, n-i+1):
# print(j)
line[j] += 1
#line = list(map(lambda x: x % 2, line))
#print(line)
for i in range(n//2):
if line[i] % 2 == 1:
temp[i], temp[n-i-1] = temp[n-i-1], temp[i]
print(''.join(temp))
'''
| 1427387400 | [
"math",
"strings"
] | [
0,
0,
0,
1,
0,
0,
1,
0
] |
|
1 second | ["1\n2\n0\n2\n12\n331032489"] | 0f58ac08a26ce735bfe13fd089b7f746 | NoteIn the first test case, $$$a=[2,1,3]$$$. There are two possible ways to fill out the $$$-1$$$s in $$$b$$$ to make it a permutation: $$$[3,1,2]$$$ or $$$[3,2,1]$$$. We can make $$$a$$$ into $$$[3,1,2]$$$ with a strength of $$$1$$$ as follows: $$$$$$[2,1,3] \xrightarrow[x=1,\,y=1]{} [2,1,3] \xrightarrow[x=2,\,y=3]{} [3,1,2] \xrightarrow[x=3,\,y=3]{} [3,1,2].$$$$$$ It can be proven that it is impossible to make $$$[2,1,3]$$$ into $$$[3,2,1]$$$ with a strength of $$$1$$$. Thus only one permutation $$$b$$$ satisfies the constraints, so the answer is $$$1$$$.In the second test case, $$$a$$$ and $$$b$$$ the same as the previous test case, but we now have a strength of $$$2$$$. We can make $$$a$$$ into $$$[3,2,1]$$$ with a strength of $$$2$$$ as follows: $$$$$$[2,1,3] \xrightarrow[x=1,\,y=3]{} [2,3,1] \xrightarrow[x=2,\,y=3]{} [3,2,1] \xrightarrow[x=3,\,y=3]{} [3,2,1].$$$$$$ We can still make $$$a$$$ into $$$[3,1,2]$$$ using a strength of $$$1$$$ as shown in the previous test case, so the answer is $$$2$$$. In the third test case, there is only one permutation $$$b$$$. It can be shown that it is impossible to turn $$$a$$$ into $$$b$$$, so the answer is $$$0$$$. | You are given a permutation $$$a$$$ of length $$$n$$$. Recall that permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order.You have a strength of $$$s$$$ and perform $$$n$$$ moves on the permutation $$$a$$$. The $$$i$$$-th move consists of the following: Pick two integers $$$x$$$ and $$$y$$$ such that $$$i \leq x \leq y \leq \min(i+s,n)$$$, and swap the positions of the integers $$$x$$$ and $$$y$$$ in the permutation $$$a$$$. Note that you can select $$$x=y$$$ in the operation, in which case no swap will occur. You want to turn $$$a$$$ into another permutation $$$b$$$ after $$$n$$$ moves. However, some elements of $$$b$$$ are missing and are replaced with $$$-1$$$ instead. Count the number of ways to replace each $$$-1$$$ in $$$b$$$ with some integer from $$$1$$$ to $$$n$$$ so that $$$b$$$ is a permutation and it is possible to turn $$$a$$$ into $$$b$$$ with a strength of $$$s$$$. Since the answer can be large, output it modulo $$$998\,244\,353$$$. | For each test case, output a single integer — the number of ways to fill up the permutation $$$b$$$ so that it is possible to turn $$$a$$$ into $$$b$$$ using a strength of $$$s$$$, modulo $$$998\,244\,353$$$. | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq s \leq n$$$) — the size of the permutation and your strength, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the elements of $$$a$$$. All elements of $$$a$$$ are distinct. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$ or $$$b_i = -1$$$) — the elements of $$$b$$$. All elements of $$$b$$$ that are not equal to $$$-1$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 2,300 | train_102.jsonl | ad7ef552703769b81327420616bda135 | 256 megabytes | ["6\n\n3 1\n\n2 1 3\n\n3 -1 -1\n\n3 2\n\n2 1 3\n\n3 -1 -1\n\n4 1\n\n1 4 3 2\n\n4 3 1 2\n\n6 4\n\n4 2 6 3 1 5\n\n6 1 5 -1 3 -1\n\n7 4\n\n1 3 6 2 7 4 5\n\n2 5 -1 -1 -1 4 -1\n\n14 14\n\n1 2 3 4 5 6 7 8 9 10 11 12 13 14\n\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1"] | PASSED | from functools import reduce
from sys import stdin, stdout
def read(): return stdin.readline().strip()
def write(x): stdout.write(str(x) + '\n')
def get_index(a):
a_index = [-1] * len(a)
for i in range(len(a)):
if a[i] != -1:
a_index[a[i]] = i
return a_index
def solve():
n, s = map(int, read().split())
a_ = list(map(int, read().split()))
b_ = list(map(int, read().split()))
a = [i - 1 for i in a_]
b = [i - 1 if i != -1 else -1 for i in b_]
a_index = get_index(a)
b_index = get_index(b)
a = [a_index[i] for i in range(n)]
b = [b_index[i] if b_index[i] != -1 else -1 for i in range(n)]
a_index = get_index(a)
b_index = get_index(b)
# p = [a[i] for i in range(s)]
# p_in_b = [a[i] for i in range(s) if a[i] in b]
p_in_b = [a[i] for i in range(s) if b_index[a[i]] != -1]
# p_not_in_b = [a[i] for i in range(s) if a[i] not in b]
p_not_in_b = [a[i] for i in range(s) if b_index[a[i]] == -1]
p_in_b_index = [-1] * n
for i in range(len(p_in_b)):
p_in_b_index[p_in_b[i]] = i
c = [0] * n
for i in range(n):
j = i + s
if j < n:
# p.append(a[j])
# if a[j] in b:
if b_index[a[j]] != -1:
p_in_b.append(a[j])
p_in_b_index[a[j]] = len(p_in_b) - 1
else:
p_not_in_b.append(a[j])
if b[i] == -1:
# c[i] = len([i for i in p if i not in b])
c[i] = len(p_not_in_b)
# for i in p:
# if i not in b:
# p.remove(i)
# break
# p_not_in_b.remove(p_not_in_b[0])
if p_not_in_b:
p_not_in_b.pop()
else:
# if b[i] in p_in_b:
if p_in_b_index[b[i]] != -1:
# if p_in_b_index[b[i]] != -1:
c[i] = 1
# p_in_b.remove(b[i])
p_in_b_index[b[i]] = -1
else:
c[i] = 0
break
# print(c)
write(reduce(lambda x, y: x * y % 998244353, c))
T = 1
T = int(read())
for _ in range(T):
solve()
| 1656426900 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["YES\n(((0)->1)->(1->0))", "NO", "YES\n0"] | 98380bd9d6865fa9a2d100ca3484b005 | null | Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. Implication is written by using character '', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication: When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,. When there are brackets, we first calculate the expression in brackets. For example,.For the given logical expression determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets. | Print "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0. Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line. The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to n. The order in which the digits follow in the expression from left to right must coincide with a1, a2, ..., an. The expression should be correct. More formally, a correct expression is determined as follows: Expressions "0", "1" (without the quotes) are correct. If v1, v2 are correct, then v1->v2 is a correct expression. If v is a correct expression, then (v) is a correct expression. The total number of characters in the resulting expression mustn't exceed 106. If there are multiple possible answers, you are allowed to print any of them. | The first line contains integer n (1 ≤ n ≤ 100 000) — the number of arguments in a logical expression. The second line contains n numbers a1, a2, ..., an (), which means the values of arguments in the expression in the order they occur. | standard output | standard input | Python 3 | Python | 2,200 | train_017.jsonl | 2d867fa51a507a36e047344968f3cf62 | 256 megabytes | ["4\n0 1 1 0", "2\n1 1", "1\n0"] | PASSED | def f(a):
if len(a) == 1:
if a[0] == 0:
print("YES\n0")
return
else:
print("NO")
return
if a[-1] == 1:
print("NO")
return
if a[-2] == 1:
print("YES")
print("->".join(str(x) for x in a))
return
elif len(a) == 2:
print("NO")
return
elif len(a) >= 3 and a[-3] == 0:
a[-3] = '(0'
a[-2] = '0)'
print("YES\n" + "->".join(str(x) for x in a))
return
for i in range(len(a) - 3, -1, -1):
if a[i] == 0:
a[i] = '(' + str(a[i])
a[i+1] = '(' + str(a[i+1])
a[-2] = '0))'
print("YES\n" + "->".join(str(x) for x in a))
return
print("NO")
return
n = int(input())
a = list(int(x) for x in input().split())
f(a) | 1433435400 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["2", "665496238"] | 881c694ecf973da66073e77f38abcae2 | NoteIn the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to $$$\frac{1^2 + 2^2+ 1^2}{3} = 2$$$. | Vasya has got a magic matrix $$$a$$$ of size $$$n \times m$$$. The rows of the matrix are numbered from $$$1$$$ to $$$n$$$ from top to bottom, the columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Let $$$a_{ij}$$$ be the element in the intersection of the $$$i$$$-th row and the $$$j$$$-th column.Vasya has also got a chip. Initially, the chip is in the intersection of the $$$r$$$-th row and the $$$c$$$-th column (that is, in the element $$$a_{rc}$$$). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.Euclidean distance between matrix elements with coordinates $$$(i_1, j_1)$$$ and $$$(i_2, j_2)$$$ is equal to $$$\sqrt{(i_1-i_2)^2 + (j_1-j_2)^2}$$$.Calculate the expected value of the Vasya's final score.It can be shown that the answer can be represented as $$$\frac{P}{Q}$$$, where $$$P$$$ and $$$Q$$$ are coprime integer numbers, and $$$Q \not\equiv 0~(mod ~ 998244353)$$$. Print the value $$$P \cdot Q^{-1}$$$ modulo $$$998244353$$$. | Print the expected value of Vasya's final score in the format described in the problem statement. | The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 1\,000)$$$ — the number of rows and the number of columns in the matrix $$$a$$$. The following $$$n$$$ lines contain description of the matrix $$$a$$$. The $$$i$$$-th line contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im} ~ (0 \le a_{ij} \le 10^9)$$$. The following line contains two integers $$$r$$$ and $$$c$$$ $$$(1 \le r \le n, 1 \le c \le m)$$$ — the index of row and the index of column where the chip is now. | standard output | standard input | PyPy 2 | Python | 2,300 | train_004.jsonl | bdd767f9de78c27593f4b89431b24790 | 256 megabytes | ["1 4\n1 1 2 1\n1 3", "2 3\n1 5 7\n2 3 1\n1 2"] | PASSED | n,m = map(int,raw_input().split(" "))
mat = [0]*(n*m)
for i in range(n):
mat[i*m:i*m+m] = map(int,raw_input().split(" "))
r,c = map(int,raw_input().split(" "))
idx = range(n*m)
idx.sort(key = lambda x:mat[x])
rank = [0]*(n*m)
for i in xrange(n*m):
rank[idx[i]] = i
dp = [0]*(n*m)
mod = 998244353
inv = [1]*(n*m)
for i in xrange(2,n*m):
inv[i] = (mod-mod/i)*inv[mod%i] % mod
i = idx[0]
x1,y1,x2,y2,s = [0]*2,[0]*2,[0]*2,[0]*2,[0]*2
x1[1] = i/m
y1[1] = i%m
x2[1] = (x1[1]*x1[1])
y2[1] = (y1[1]*y1[1])
s[1] = 0
la = -1
final = (r-1)*m+c-1
for i in xrange(1,rank[final]+1):
j = idx[i]
x,y = j/m,j%m
if mat[j] == mat[idx[i-1]]:
dp[i] =(s[0]*deno+x*x+y*y+deno*(x2[0]+y2[0]-2*x1[0]*x-2*y1[0]*y))%mod if la!=-1 else 0
else:
deno = inv[i]
dp[i] = (s[-1]*deno+x*x+y*y+deno*(x2[-1]+y2[-1]-2*x1[-1]*x-2*y1[-1]*y))%mod
x1[0] = x1[1]
y1[0] = y1[1]
x2[0] = x2[1]
y2[0] = y2[1]
s[0] = s[1]
la = 0
x1[-1] = (x1[-1]+x)%mod
y1[-1] = (y1[-1]+y)%mod
x2[-1] = (x2[-1]+x*x)%mod
y2[-1] = (y2[-1]+y*y)%mod
s[-1] = (s[-1]+dp[i])%mod
print dp[rank[final]] | 1537171500 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
3 seconds | ["3\n6\n3\n3\n10\n3\n2000000000000000000", "200\n300\n150"] | 7b394dbced93130f83d61f7e325a980a | NoteIn the first example:After the first and second queries, the set will contain elements $$$\{0, 1, 2\}$$$. The smallest non-negative number that is divisible by $$$1$$$ and is not contained in the set is $$$3$$$.After the fourth query, the set will contain the elements $$$\{0, 1, 2, 4\}$$$. The smallest non-negative number that is divisible by $$$2$$$ and is not contained in the set is $$$6$$$.In the second example: Initially, the set contains only the element $$$\{0\}$$$. After adding an integer $$$100$$$ the set contains elements $$$\{0, 100\}$$$. $$$100\text{-mex}$$$ of the set is $$$200$$$. After adding an integer $$$200$$$ the set contains elements $$$\{0, 100, 200\}$$$. $$$100\text{-mex}$$$ of the set is $$$300$$$. After adding an integer $$$50$$$ the set contains elements $$$\{0, 50, 100, 200\}$$$. $$$50\text{-mex}$$$ of the set is $$$150$$$. | This is the easy version of the problem. The only difference is that in this version there are no "remove" queries.Initially you have a set containing one element — $$$0$$$. You need to handle $$$q$$$ queries of the following types:+ $$$x$$$ — add the integer $$$x$$$ to the set. It is guaranteed that this integer is not contained in the set; ? $$$k$$$ — find the $$$k\text{-mex}$$$ of the set. In our problem, we define the $$$k\text{-mex}$$$ of a set of integers as the smallest non-negative integer $$$x$$$ that is divisible by $$$k$$$ and which is not contained in the set. | For each query of type ? output a single integer — the $$$k\text{-mex}$$$ of the set. | The first line contains an integer $$$q$$$ ($$$1 \leq q \leq 2 \cdot 10^5$$$) — the number of queries. The following $$$q$$$ lines describe the queries. An addition query of integer $$$x$$$ is given in the format + $$$x$$$ ($$$1 \leq x \leq 10^{18}$$$). It is guaranteed that $$$x$$$ was not contained in the set. A search query of $$$k\text{-mex}$$$ is given in the format ? $$$k$$$ ($$$1 \leq k \leq 10^{18}$$$). It is guaranteed that there will be at least one query of type ?. | standard output | standard input | PyPy 3-64 | Python | 1,500 | train_097.jsonl | f206406a5d19cdb245dd241fdcba056c | 256 megabytes | ["15\n\n+ 1\n\n+ 2\n\n? 1\n\n+ 4\n\n? 2\n\n+ 6\n\n? 3\n\n+ 7\n\n+ 8\n\n? 1\n\n? 2\n\n+ 5\n\n? 1\n\n+ 1000000000000000000\n\n? 1000000000000000000", "6\n\n+ 100\n\n? 100\n\n+ 200\n\n? 100\n\n+ 50\n\n? 50"] | PASSED | # Code by B3D
# Love
from math import *
from collections import *
import io, os
import sys
from bisect import *
from heapq import *
from itertools import permutations
from functools import *
import re
import sys
import threading
# from temps import *
MOD = 998244353
# sys.setrecursionlimit(10**6)
def subinp():
sys.stdin = open("input.txt", "r")
sys.stdout = open("op1.txt", "w")
def subinp_1():
sys.stdin = open("input.txt", "r")
sys.stdout = open("op2.txt", "w")
"""
pow2 = [1]
# print(log2(10 ** 9))
for i in range(29):
pow2.append(pow2[-1] * 2)
"""
input = sys.stdin.readline
class Point:
def __init__(self, x, l1):
self.x = x
self.l1 = l1
def __lt__(self, b):
return self.l1[self.x] < self.l1[b.x]
def getval(self):
return self.x
inp = lambda: int(input())
strin = lambda: input().strip()
strl = lambda: list(input().rstrip("\r\n"))
strlst = lambda: list(map(str, input().split()))
mult = lambda: map(int,input().strip().split())
mulf = lambda: map(float,input().strip().split())
lstin = lambda: list(map(int,input().strip().split()))
flush = lambda: stdout.flush()
stdpr = lambda x: stdout.write(str(x))
# @lru_cache(maxsize = 128)
# print(pref)
# ac = [chr(i) for i in range(ord('a'), ord('z') + 1)]
# Power comes in response to a need, not a desire.
# n = int(input())
# n, k = map(int, input().split())
# s = input()
# l = list(map(int, input().split()))
# dp = [[-1 for i in range(n + 1)] for j in range(2)]
class Queen:
def __init__(self):
self.chk = defaultdict(bool)
self.mp = defaultdict(lambda:1)
def addnum(self, n):
self.chk[n] = True
while self.chk[self.mp[n] * n]:
self.mp[n] += 1
def query(self, n):
m = n
ans = 0
i = self.mp[n]
# print(d)
while self.chk[m]:
self.mp[n] = i
m = n * i
i += 1
print(m)
def panda(q):
obj = Queen()
lock = threading.Semaphore(10)
for _ in range(q):
inp = strl()
qx = inp[0]
n = int(''.join(inp[2:]))
if qx == '+':
lock.acquire()
obj.addnum(n)
lock.release()
else:
lock.acquire()
obj.query(n)
lock.release()
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = 1
# t = int(input())
for _ in range(t):
n = inp()
ans = panda(n)
# print(ans)
# a1 = redpanda(n, l)
# print(a)
# print(a1)
# sys.stdout.write(str(ans))
# print("Case #" + str(_ + 1) + ": " + str(ans)) | 1666519500 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["4 12\n2 9", "0"] | acebe5e1d927d32d65a4500d1d45c4ba | NoteIn the first example, the GCDs of rows are $$$b_1 = 4$$$ and $$$b_2 = 1$$$, and the GCDs of columns are $$$b_3 = 2$$$ and $$$b_4 = 3$$$. All GCDs are pairwise distinct and the maximum of them is $$$4$$$. Since the GCDs have to be distinct and at least $$$1$$$, it is clear that there are no diverse matrices of size $$$2 \times 2$$$ with magnitude smaller than $$$4$$$.In the second example, no matter what $$$a_{1,1}$$$ is, $$$b_1 = b_2$$$ will always hold, so there are no diverse matrices. | Let $$$a$$$ be a matrix of size $$$r \times c$$$ containing positive integers, not necessarily distinct. Rows of the matrix are numbered from $$$1$$$ to $$$r$$$, columns are numbered from $$$1$$$ to $$$c$$$. We can construct an array $$$b$$$ consisting of $$$r + c$$$ integers as follows: for each $$$i \in [1, r]$$$, let $$$b_i$$$ be the greatest common divisor of integers in the $$$i$$$-th row, and for each $$$j \in [1, c]$$$ let $$$b_{r+j}$$$ be the greatest common divisor of integers in the $$$j$$$-th column. We call the matrix diverse if all $$$r + c$$$ numbers $$$b_k$$$ ($$$k \in [1, r + c]$$$) are pairwise distinct. The magnitude of a matrix equals to the maximum of $$$b_k$$$.For example, suppose we have the following matrix: $$$\begin{pmatrix} 2 & 9 & 7\\ 4 & 144 & 84 \end{pmatrix}$$$ We construct the array $$$b$$$: $$$b_1$$$ is the greatest common divisor of $$$2$$$, $$$9$$$, and $$$7$$$, that is $$$1$$$; $$$b_2$$$ is the greatest common divisor of $$$4$$$, $$$144$$$, and $$$84$$$, that is $$$4$$$; $$$b_3$$$ is the greatest common divisor of $$$2$$$ and $$$4$$$, that is $$$2$$$; $$$b_4$$$ is the greatest common divisor of $$$9$$$ and $$$144$$$, that is $$$9$$$; $$$b_5$$$ is the greatest common divisor of $$$7$$$ and $$$84$$$, that is $$$7$$$. So $$$b = [1, 4, 2, 9, 7]$$$. All values in this array are distinct, so the matrix is diverse. The magnitude is equal to $$$9$$$.For a given $$$r$$$ and $$$c$$$, find a diverse matrix that minimises the magnitude. If there are multiple solutions, you may output any of them. If there are no solutions, output a single integer $$$0$$$. | If there is no solution, output a single integer $$$0$$$. Otherwise, output $$$r$$$ rows. The $$$i$$$-th of them should contain $$$c$$$ space-separated integers, the $$$j$$$-th of which is $$$a_{i,j}$$$ — the positive integer in the $$$i$$$-th row and $$$j$$$-th column of a diverse matrix minimizing the magnitude. Furthermore, it must hold that $$$1 \leq a_{i,j} \leq 10^9$$$. It can be shown that if a solution exists, there is also a solution with this additional constraint (still having minimum possible magnitude). | The only line in the input contains two space separated integers $$$r$$$ and $$$c$$$ ($$$1 \leq r,c \leq 500$$$) — the number of rows and the number of columns of the matrix to be found. | standard output | standard input | PyPy 3 | Python | 1,400 | train_006.jsonl | 9e2e8f4f8c7981d834bc616ad00007cd | 256 megabytes | ["2 2", "1 1"] | PASSED | import sys
def gcd(a, b):
if min(a, b) == 0:
return max(a,b)
if a >= b:
return gcd(a % b, b)
elif b > a:
return gcd(a, b % a)
n, m = list(map(int, input().split()))
if n == 1 and m == 1:
print(0)
exit()
a = []
if n == 1:
for i in range(m):
a.append(str(i+2))
print(' '.join(a))
exit()
for i in range(n):
a.append([0] * m)
for i in range(n):
a[i][0]= i + 2
num = n+1
for i in range(len(a)):
for j in range(1, len(a[i])):
a[i][j] = (a[i][0] * (num+j))
for i in range(len(a)):
sys.stdout.write(' '.join(list(map(str, a[i]))) + '\n') | 1576595100 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["-1 20\n8 -1\n1 2\n-1 1000000000"] | 002801f26568a1b3524d8754207d32c1 | NoteIn the first testcase buying any number of donuts will be cheaper in the second shop. For example, for $$$3$$$ or $$$5$$$ donuts you'll have to buy a box of $$$10$$$ donuts for $$$4$$$ dollars. $$$3$$$ or $$$5$$$ donuts in the first shop would cost you $$$15$$$ or $$$25$$$ dollars, respectively, however. For $$$20$$$ donuts you'll have to buy two boxes for $$$8$$$ dollars total. Note that $$$3$$$ and $$$5$$$ are also valid answers for the second shop, along with many other answers.In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. $$$8$$$ donuts cost $$$32$$$ dollars in the first shop and $$$40$$$ dollars in the second shop (because you have to buy two boxes). $$$10$$$ donuts will cost $$$40$$$ dollars in both shops, so $$$10$$$ is not a valid answer for any of the shops.In the third testcase $$$1$$$ donut costs $$$2$$$ and $$$3$$$ dollars, respectively. $$$2$$$ donuts cost $$$4$$$ and $$$3$$$ dollars. Thus, $$$1$$$ is a valid answer for the first shop and $$$2$$$ is a valid answer for the second shop.In the fourth testcase $$$10^9$$$ donuts cost $$$10^{18}$$$ dollars in the first shop and $$$10^9$$$ dollars in the second shop. | There are two rival donut shops.The first shop sells donuts at retail: each donut costs $$$a$$$ dollars.The second shop sells donuts only in bulk: box of $$$b$$$ donuts costs $$$c$$$ dollars. So if you want to buy $$$x$$$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $$$x$$$.You want to determine two positive integer values: how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop? how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to $$$-1$$$. If there are multiple possible answers, then print any of them.The printed values should be less or equal to $$$10^9$$$. It can be shown that under the given constraints such values always exist if any values exist at all. | For each testcase print two positive integers. For both shops print such $$$x$$$ that buying $$$x$$$ donuts in this shop is strictly cheaper than buying $$$x$$$ donuts in the other shop. $$$x$$$ should be greater than $$$0$$$ and less or equal to $$$10^9$$$. If there is no such $$$x$$$, then print $$$-1$$$. If there are multiple answers, then print any of them. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a \le 10^9$$$, $$$2 \le b \le 10^9$$$, $$$1 \le c \le 10^9$$$). | standard output | standard input | PyPy 3 | Python | 1,000 | train_000.jsonl | da687bae02561ee9c14a5e964e17b2ba | 256 megabytes | ["4\n5 10 4\n4 5 20\n2 2 3\n1000000000 1000000000 1000000000"] | PASSED | mx=1000000000
def solve():
a,b,c=map(int,input().split())
if(a>=c):
ans1=-1
ans2=c//a+1
elif(c>a*b or c==a*b):
ans1=1
ans2=-1
else:
ans1=1
ans2=c//a+1
print(ans1,ans2)
for _ in range(int(input())):
solve() | 1593095700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO\nNO"] | 801bf7c73c44c68eaa61c714d5aedf50 | NoteThe example contains test cases from the main part of the condition. | A string $$$s$$$ of length $$$n$$$ ($$$1 \le n \le 26$$$) is called alphabetical if it can be obtained using the following algorithm: first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$ := ""); then perform the next step $$$n$$$ times; at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$ := $$$c+s$$$ or $$$s$$$ := $$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical. | Output $$$t$$$ lines, each of them must contain the answer to the corresponding test case. Output YES if the given string $$$s$$$ is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer). | 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 is written on a separate line that contains one string $$$s$$$. String $$$s$$$ consists of lowercase letters of the Latin alphabet and has a length between $$$1$$$ and $$$26$$$, inclusive. | standard output | standard input | PyPy 3-64 | Python | 800 | train_103.jsonl | 5be5352b5574622db9696b6ae847361e | 512 megabytes | ["11\na\nba\nab\nbac\nihfcbadeg\nz\naa\nca\nacb\nxyz\nddcba"] | PASSED | t = int(input())
import string
def is_abc(S):
abc = list(string.ascii_lowercase)
del abc[0]
if S == 'a':
return True
if S == '':
return True
if len(set(S)) == len(S) and 'a' in S:
a = S.index('a')
prev_S = list(reversed(S[:a]))
post_S = S[a+1:]
c = len(prev_S) + len(post_S)
for i in range(c):
current_S = abc[i]
prev = prev_S[0] if prev_S else None
post = post_S[0] if post_S else None
if current_S == prev:
del prev_S[0]
elif current_S == post:
del post_S[0]
else:
return False
return True
else:
return False
for i in range(t):
S = list(input())
if is_abc(S):
print('YES')
else:
print('NO') | 1625927700 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["4", "3", "-1"] | 480db1d8e2fadc75fd07693c22254fc1 | NoteIn the first example, the shortest cycle is $$$(9, 3, 6, 28)$$$.In the second example, the shortest cycle is $$$(5, 12, 9)$$$.The graph has no cycles in the third example. | You are given $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$. Consider graph on $$$n$$$ nodes, in which nodes $$$i$$$, $$$j$$$ ($$$i\neq j$$$) are connected if and only if, $$$a_i$$$ AND $$$a_j\neq 0$$$, where AND denotes the bitwise AND operation.Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. | If the graph doesn't have any cycles, output $$$-1$$$. Else output the length of the shortest cycle. | The first line contains one integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — number of numbers. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$). | standard output | standard input | Python 3 | Python | 1,900 | train_010.jsonl | 071f4f0febb0e01dc089b1f41c972b34 | 256 megabytes | ["4\n3 6 28 9", "5\n5 12 9 16 48", "4\n1 2 4 8"] | PASSED | import sys
n = int(input())
dat = [int(i) for i in input().split()]
data = [i for i in dat if i != 0]
n = len(data)
dic = {}
for d in data:
if d in dic:
dic[d] += 1
else:
dic[d] = 1
keys = list(dic.keys())
if len(keys) != len(data):
if len(data) > 200:
print(3)
sys.exit()
else:
data2 = []
for i in range(len(keys)):
k = keys[i]
if k != 0:
if dic[k] == 2:
for j in range(len(keys)):
if k & keys[j] and i != j:
print(3)
sys.exit()
elif dic[k] > 2:
print(3)
sys.exit()
else:
data2.append(k)
data = data2
n = len(data)
inf = 1 << 10
if n > 100:
print(3)
sys.exit()
def bfs(a):
layer = {a}
parent = {a: -1}
cnt = 0
while len(layer) > 0:
# print(a, layer)
cnt += 1
new = set()
ret = -1
for l in layer:
for v in data:
if l & v and v != l and parent[l] != v:
if v in layer:
return 2 * cnt - 1
elif v in new:
ret = 2 * cnt
parent[v] = l
new.add(v)
# if v == a:
# print(l, v)
# print(parent)
# return cnt
# 5
# 5 12 9 16 48
layer = new
if ret != -1:
return ret
return inf
ans = inf
for d in data:
a2 = bfs(d)
# print(a2)
if a2 == inf:
continue
elif a2 == 3:
print(3)
sys.exit()
elif a2 < ans:
ans = a2
if ans == inf:
print(-1)
else:
print(ans)
| 1566135900 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3", "1", "3"] | 15aac7420160f156d5b73059af1fae3b | NotePicture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.In the second test case, we can put all four small boxes into a box with side length 2. | Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure: Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes. | Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p. | The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct. | standard output | standard input | Python 3 | Python | 1,600 | train_009.jsonl | 0f4cf960a6c9521bb702f7e6ee9b8164 | 256 megabytes | ["2\n0 3\n1 5", "1\n0 4", "2\n1 10\n2 2"] | PASSED | import math
n = int(input())
arr = []
for i in range(n):
k,a = list(map(int,input().split()))
arr.append([k,a])
arr.sort()
ans = 0
for i in arr:
x = math.log(i[1],4)+i[0]
ans = max(ans,math.ceil(x))
if i[1]==1:
ans = max(ans,i[0]+1)
print(ans) | 1359732600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4", "6", "-1"] | c3cbc9688594d6611fd7bdd98d9afaa0 | null | The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point. | If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one. | The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105. | standard output | standard input | PyPy 3 | Python | 1,800 | train_029.jsonl | a09fe0e2d1fdac307b063596867caaa5 | 256 megabytes | ["5 7 6 11\n3\n5 3 8\n6 7 11\n5 2 5", "3 4 3 10\n3\n3 1 4\n4 5 9\n3 10 10", "1 1 2 10\n2\n1 1 3\n2 6 10"] | PASSED | INF = 1000000000
def bfs(sta,fin):
from collections import deque
visit = deque()
dx = [0,-1,-1,-1,0,1,1,1]
dy = [1,1,0,-1,-1,-1,0,1]
visit.append(sta)
while len(visit) > 0:
vertex = visit.popleft()
for i in range(8):
nx = vertex[0] + dx[i]
ny = vertex[1] + dy[i]
if (1 <= nx <= INF) and (1 <= ny <= INF) and ((nx,ny) in board) and (board[(nx,ny)] == -1):
visit.append((nx,ny))
board[(nx, ny)] = 0
dist[(nx,ny)] = dist[vertex] + 1
if (nx,ny) == fin:
print(dist[(nx,ny)],end='')
return True
return False
if __name__ == '__main__':
board, dist = dict(), dict()
x0, y0, x1, y1 = map(int, input().split())
sta = (x0, y0)
fin = (x1, y1)
dist[sta] = 0
n = int(input())
for _ in range(n):
line = input()
r, a, b = map(int, line.split())
for i in range(a,b+1):
board[(r,i)] = -1
dist[(r, i)] = 0
if not bfs(sta,fin):
print(-1,end='') | 1352647800 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds | ["5", "3", "6"] | 900c85e25d457eb8092624b1d42be2a2 | NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5. | Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you? | Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line. | The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds. | standard output | standard input | Python 2 | Python | 2,000 | train_001.jsonl | e5f87428b0950f99dadcdcc2c509af75 | 256 megabytes | ["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"] | PASSED | from sys import stdin
from itertools import repeat
def main():
n, k = map(int, stdin.readline().split())
mod = 10 ** 9 + 7
f = [1] * (n + 1)
inv = [1] * (n + 1)
invf = [1] * (n + 1)
for i in xrange(2, n + 1):
f[i] = f[i-1] * i % mod
inv[i] = mod - mod / i * inv[mod%i] % mod
invf[i] = invf[i-1] * inv[i] % mod
dat = map(int, stdin.read().split(), repeat(10, 2 * n))
for i in xrange(1, 2 * n, 2):
dat[i] += 1
s = list(set(dat))
s.sort()
d = {x: i for i, x in enumerate(s)}
l = len(d)
ev = [0 for _ in xrange(l)]
for i in xrange(n):
x, y = dat[i*2], dat[i*2+1]
ev[d[x]] += 1
ev[d[y]] -= 1
p = s[0]
t = ev[0]
ans = 0
def comb(a, b):
return f[a] * invf[b] * invf[a-b] % mod
for i in xrange(1, l):
q = s[i]
if t >= k:
ans += (q - p) * comb(t, k)
ans %= mod
t += ev[i]
p = q
print ans
main()
| 1467822900 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3", "6", "7"] | 2e41dde8b3466e5a8c26e3d4eda1fd53 | NoteIn the first example Ivan will choose this compressed version: c1 is 10, s1 is a.In the second example Ivan will choose this compressed version: c1 is 1, s1 is abcab.In the third example Ivan will choose this compressed version: c1 is 2, s1 is c, c2 is 1, s2 is z, c3 is 4, s3 is ab. | Ivan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters.Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of the string itself.The compressed version of string s is a sequence of strings c1, s1, c2, s2, ..., ck, sk, where ci is the decimal representation of number ai (without any leading zeroes) and si is some string consisting of lowercase Latin letters. If Ivan writes string s1 exactly a1 times, then string s2 exactly a2 times, and so on, the result will be string s.The length of a compressed version is |c1| + |s1| + |c2| + |s2|... |ck| + |sk|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length. | Output one integer number — the minimum possible length of a compressed version of s. | The only line of input contains one string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 8000). | standard output | standard input | PyPy 3 | Python | 2,400 | train_053.jsonl | 28ccd236ba0acc0afcddcb6a83e01f37 | 512 megabytes | ["aaaaaaaaaa", "abcab", "cczabababab"] | PASSED | def prefix(s):
p = [0]
for i in range(1, len(s)):
j = p[-1]
while j > 0 and s[j] != s[i]:
j = p[j - 1]
if s[i] == s[j]:
j += 1
p.append(j)
return p
s = input()
n = len(s)
ans = [0] * (n + 1)
i = n - 1
while i >= 0:
p = prefix(s[i:])
ans[i] = 2 + ans[i + 1]
for j in range(len(p)):
z = 1
if (j + 1) % (j + 1 - p[j]) == 0:
z = (j + 1) // (j + 1 - p[j])
res = len(str(z)) + (j + 1) // z + ans[i + j + 1]
ans[i] = min(ans[i], res)
i -= 1
print(ans[0])
| 1500217500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["AG\nCT", "TGCAT\nCATGC\nTGCAT"] | d80a963af909638d5504dbc6adb2ba38 | NoteIn the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice. | You are given an $$$n \times m$$$ table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every $$$2 \times 2$$$ square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters. | Output $$$n$$$ lines, $$$m$$$ characters each. This table must be nice and differ from the input table in the minimum number of characters. | First line contains two positive integers $$$n$$$ and $$$m$$$ — number of rows and columns in the table you are given ($$$2 \leq n, m, n \times m \leq 300\,000$$$). Then, $$$n$$$ lines describing the table follow. Each line contains exactly $$$m$$$ characters «A», «G», «C», «T». | standard output | standard input | PyPy 2 | Python | 2,100 | train_066.jsonl | 25a45a2ef8ab4e29f237955986c5c4be | 256 megabytes | ["2 2\nAG\nCT", "3 5\nAGCAG\nAGCAG\nAGCAG"] | PASSED | import sys
range = xrange
input = raw_input
tran = [0]*1000
tran[ord('A')] = 0
tran[ord('G')] = 1
tran[ord('C')] = 2
tran[ord('T')] = 3
inv = ['A','G','C','T']
h,w = [int(x) for x in input().split()]
A = [[tran[ord(c)] for c in inp] for inp in sys.stdin.read().splitlines()]
comb = []
for i in range(4):
for j in range(4):
if i!=j:
comb.append((i,j))
working = [[] for _ in range(12)]
for i in range(12):
a,b = comb[i]
for j in range(12):
c,d = comb[j]
if a!=c and a!=d and b!=c and b!=d:
working[i].append(j)
opt = h*w+1
for rot in [False,True]:
if rot:
B = [[0]*h for _ in range(w)]
for x in range(w):
for y in range(h):
B[x][y] = A[y][x]
h,w,A = w,h,B
cost = [[0]*h for _ in range(12)]
for i in range(12):
for y in range(h):
alt = comb[i]
c = 0
for x in range(w):
if A[y][x]!=alt[x%2]:
c += 1
cost[i][y] = c
DP = [[0]*h for _ in range(12)]
color = [-1]*h
for i in range(12):
DP[i][0] = cost[i][0]
for y in range(1,h):
for i in range(12):
DP[i][y] = min(DP[j][y-1] for j in working[i]) + cost[i][y]
score = min(DP[i][-1] for i in range(12))
color[-1] = min(range(12),key=lambda i: DP[i][-1])
for y in reversed(range(1,h)):
i = color[y]
for j in working[i]:
if DP[j][y-1]+cost[i][y]==DP[i][y]:
color[y-1] = j
break
if score<opt:
opt = score
opt_color = color
opt_rot = rot
opt_h = h
opt_w = w
C = []
for y in range(opt_h):
alt = comb[opt_color[y]]
C.append([alt[x%2] for x in range(opt_w)])
if opt_rot:
B = [[0]*opt_h for _ in range(opt_w)]
for x in range(opt_w):
for y in range(opt_h):
B[x][y] = C[y][x]
opt_h,opt_w,C = opt_w,opt_h,B
opt_rot = False
print '\n'.join(''.join(inv[c] for c in C[y]) for y in range(opt_h))
| 1546706100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["2 3 6\n-1\n1 2 3"] | 341555349b0c1387334a0541730159ac | NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle. | You are given an array $$$a_1, a_2, \dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \le i < j < k \le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it. | For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$) — the array $$$a$$$. 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_002.jsonl | 51145621ae7bf015013f974f18993dec | 256 megabytes | ["3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000"] | PASSED | for u in range(int(input())):
n = int(input())
x = [int(w) for w in input().split()]
if x[0] + x[1] > x[-1]:
print(-1)
else:
print(1, 2, n) | 1597415700 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | dfe0f5da0cb90706f33365009d9baf5b | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | standard output | standard input | PyPy 2 | Python | 2,100 | train_013.jsonl | ec5495f6659e77c300ed83bb627d412a | 256 megabytes | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | PASSED | from __future__ import division, print_function
def main():
n, k = map(int, input().split())
l1 = list(input())
stages = []
while 1:
l2 = []
temp = []
i = 0
while i < n - 1:
if l1[i] == "R" and l1[i+1] == "L":
temp.append(i + 1)
l2.append("L")
l2.append("R")
i += 2
else:
l2.append(l1[i])
i += 1
while i < n:
l2.append(l1[i])
i += 1
l1 = l2
if len(temp) == 0:
break
stages.append(temp)
total_moves = 0
min_moves = len(stages)
#print(*stages, sep = "\n")
for x in stages:
total_moves += len(x)
if total_moves < k or k < min_moves:
print(-1)
else:
x = len(stages)
if x == k:
for i in range(x):
print(len(stages[i]), end = " ")
print(*stages[i])
else:
flag = 0
for i in range(len(stages)):
for j in range(len(stages[i])):
print(1, stages[i][j])
k -= 1
rows_left = len(stages) - i
if j == len(stages[i]) - 1:
rows_left -= 1
if k == rows_left:
flag = 1
row_number = i
column_number = j + 1
break
if flag == 1:
break
if flag == 1:
if column_number != len(stages[row_number]):
print(len(stages[row_number][column_number:]), end = " ")
print(*stages[row_number][column_number:])
row_number += 1
for i in range(row_number, len(stages)):
print(len(stages[i]), end =" ")
print(*stages[i])
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main() | 1586356500 | [
"games",
"graphs"
] | [
1,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["3", "1", "6"] | b18bbefd2a948da9dec1d6f27f219ed1 | NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$. | Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone: Initially he stands in the end of the queue in front of the first entrance. Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone. | Print a single integer — the number of entrance that Allen will use. | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen. | standard output | standard input | PyPy 3 | Python | 1,300 | train_007.jsonl | 6be21dd1f93ab5dbfaaaf75256475901 | 256 megabytes | ["4\n2 3 2 0", "2\n10 10", "6\n5 2 6 5 7 4"] | PASSED | from math import ceil
def main():
n = int(input())
a = list(map(int,input().split()))
found = False
for i in range(n):
if a[i] <= i:
found = True
index = i+1
break
if not found:
temp = ceil(a[0]/n)
index = 1
for i in range(1,n):
if ceil((a[i]-i)/n) < temp:
temp = ceil((a[i]-i)/n)
index = i+1
print(index)
if __name__ == '__main__':
main()
| 1529858100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1.6E1", "1.234", "1E-1", "1E2"] | b1eebb3928925b84a95b9f1e5a31e4f3 | null | You are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b. | Print the only line — the "simple exponential notation" of the given number x. | The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other. | standard output | standard input | Python 3 | Python | 1,800 | train_009.jsonl | 039bf47e81c255ce23e3e9637d0f9535 | 256 megabytes | ["16", "01.23400", ".100", "100."] | PASSED | #############<------------ Xorcestor_X ---------------->############
from math import *
def is_even(p):
n=len(p)
count=0
for i in range(n):
index=p.index(i,i,n)
if i==index:
pass
else:
count+=1
temp=p[i]
p[i]=p[index]
p[index]=temp
# print(p)
if count%2==0:
return True
else:
return False
prime=[]
def SieveOfEratosthenes():
global prime
prime=[1]*2000010
prime[1]=0
p=2
while p*p<=2000001:
if prime[p]:
for i in range(p*p,2000002,p):
prime[i]=0
lpf=[]
def precompute():
global lpf
lpf=[0]*1000001
for i in range(2,1000001):
if not lpf[i]:
for j in range(i,1000001,i):
if not lpf[j]:
lpf[j]=i
def binpow(a,b):
res=1
while b>0:
if b&1:
res*=a
a*=a
b>>=1
return res
def modpow(a,b,x):
res=1
while b>0:
if b&1:
res*=a
res%=x
a*=a
a%=x
b>>=1
return res
cont=[]
def f(x):
global cont
total=0
for i in cont:
total+=abs(i-x)
return total
def bs(low,high,target):
while low+3<high:
mid=(low+high)/2
if arr[mid]<target:
low=mid
else:
high=mid-1
for i in range(high,low-1,-1):
if arr[o]<target:
return i
return -1
def ternary_search(l,r):
while r-l>10:
m1=l+(r-l)/3
m2=r-(r-l)/3
f1=f(m1)
f2=f(m2)
if f1>f2:
l=m1
else:
r=m2
mino=f(l)
for i in range(l,r+1):
mino=min(mino,f(i))
return mino
s=input()
s=s.replace('0',' ')
s=s.lstrip()
s=s.replace(' ','0')
l=s.find('.')
if l==-1:
sz=len(s)
tr=s[0]+'.'+s[1:]
tr=tr.replace('0',' ')
tr=tr.rstrip()
tr=tr.replace(' ','0')
if tr[-1]=='.':
tr=tr[0:-1]
if sz==1:
print(tr)
else:
tr+="E"+str(sz-1)
print(tr)
else:
if l==0:
s=s[1:]
sz=len(s)
s=s.replace('0',' ')
s=s.lstrip()
s=s.replace(' ','0')
new_sz=len(s)
counter=-1
counter-=(sz-new_sz)
s=s.replace('0',' ')
s=s.rstrip()
s=s.replace(' ','0')
tr=s[0]+'.'+s[1:]
if tr[-1]=='.':
tr=tr[0:-1]
tr+="E"+str(counter)
print(tr)
else:
diff=l-1
s=s.replace('0',' ')
s=s.rstrip()
s=s.replace(' ','0')
if diff==0:
if s[-1]==".":
s=s[0:-1]
print(s)
else:
tr=s[0]+"."+s[1:l]+s[l+1:]
tr=tr.replace('0',' ')
tr=tr.rstrip()
tr=tr.replace(' ','0')
if tr[-1]=='.':
tr=tr[0:-1]
tr+="E"+str(diff)
print(tr)
| 1468425600 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1\n2\n1\n5\n534\n-1\n500000500000"] | 570b8bfd5f860ee2b258fdbb0d6e20ce | NoteIn the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.In the fourth test case of the example the enemy gets: $$$4$$$ damage ($$$1$$$-st spell cast) at time $$$0$$$; $$$4$$$ damage ($$$2$$$-nd spell cast) and $$$3$$$ heal ($$$1$$$-st spell cast) at time $$$1$$$ (the total of $$$5$$$ damage to the initial health); $$$4$$$ damage ($$$3$$$-nd spell cast) and $$$6$$$ heal ($$$1$$$-st and $$$2$$$-nd spell casts) at time $$$2$$$ (the total of $$$3$$$ damage to the initial health); and so on. One can prove that there is no time where the enemy gets the total of $$$6$$$ damage or more, so the answer is $$$5$$$. Please note how the health is recalculated: for example, $$$8$$$-health enemy would not die at time $$$1$$$, as if we first subtracted $$$4$$$ damage from his health and then considered him dead, before adding $$$3$$$ heal.In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.In the seventh test case the answer does not fit into a 32-bit integer type. | Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $$$a$$$ instant damage to him, and then heal that enemy $$$b$$$ health points at the end of every second, for exactly $$$c$$$ seconds, starting one second after the ability is used. That means that if the ability is used at time $$$t$$$, the enemy's health decreases by $$$a$$$ at time $$$t$$$, and then increases by $$$b$$$ at time points $$$t + 1$$$, $$$t + 2$$$, ..., $$$t + c$$$ due to this ability.The ability has a cooldown of $$$d$$$ seconds, i. e. if Meka-Naruto uses it at time moment $$$t$$$, next time he can use it is the time $$$t + d$$$. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under $$$k$$$ spells gets $$$k\cdot b$$$ amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every $$$d$$$ seconds). The enemy is killed if their health points become $$$0$$$ or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them? | For each testcase in a separate line print $$$-1$$$ if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed. | The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) standing for the number of testcases. Each test case is described with one line containing four numbers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1\leq a, b, c, d\leq 10^6$$$) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively. | standard output | standard input | Python 2 | Python | 2,100 | train_005.jsonl | a810fb3d2ae126183426f03feaa796b0 | 256 megabytes | ["7\n1 1 1 1\n2 2 2 2\n1 2 3 4\n4 3 2 1\n228 21 11 3\n239 21 11 3\n1000000 1 1000000 1"] | PASSED | import math
t = int(raw_input())
for i in range(t):
a, b, c, d = map(float,raw_input().split())
badm = int(math.ceil(a / b))
if badm > c:
print(-1)
else:
goodm = (badm - 1)
#goodm -= goodm % d
times = goodm // d
dmg = ((times + 1) * a) - (times * (times + 1) // 2 * d * b)
print(int(dmg))
| 1603623900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n-1\n2"] | d6ac9ca9cc5dfd9f43f5f65ce226349e | NoteIn the first example, you can replace any letter 'a' with the string "a", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.In the second example, you can replace the second letter 'a' with "abc". String $$$s$$$ becomes equal to "aabc". Then the second letter 'a' again. String $$$s$$$ becomes equal to "aabcbc". And so on, generating infinitely many different strings.In the third example, you can either leave string $$$s$$$ as is, performing zero moves, or replace the only 'a' with "b". String $$$s$$$ becomes equal to "b", so you can't perform more moves on it. | You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index. | For each testcase, print the number of different strings $$$s$$$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number. | The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a non-empty string $$$s$$$, consisting only of Latin letters 'a'. The length of $$$s$$$ doesn't exceed $$$50$$$. The second line contains a non-empty string $$$t$$$, consisting of lowercase Latin letters. The length of $$$t$$$ doesn't exceed $$$50$$$. | standard output | standard input | Python 3 | Python | 1,000 | train_107.jsonl | 969d32573f93c595fe350d13d4780858 | 256 megabytes | ["3\n\naaaa\n\na\n\naa\n\nabc\n\na\n\nb"] | PASSED | '''
# Submitted By [email protected]
Don't Copy This Code, Try To Solve It By Yourself
'''
# Problem Name = "Infinite Replacement"
# Class: C
def Solve():
ss, rs = [], []
for t in range(int(input())):
ss.append(input())
rs.append(input())
for s, r in zip(ss, rs):
if "a" in s:
if r=="a":
print(1)
elif "a" in r:
print(-1)
else:
print(2**len(s))
else:
print(0)
if __name__ == "__main__":
Solve() | 1651502100 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["YES\n1 2 0\n1 3 1\n2 4 7\n3 6 0\n2 5 0\nYES\n1 2 1\n1 3 0\n1 4 1\n4 5 1\nNO\nNO"] | 884e547e8ccb05e618ec80904b2ea107 | NoteThe first test case is the image in the statement.One possible answer is assigning the value of the edge $$$(1, 2)$$$ to $$$5$$$, and the value of the edge $$$(2, 5)$$$ to $$$3$$$. This is correct because: The first elf goes from node $$$2$$$ to node $$$3$$$. This elf's favorite number is $$$4$$$, so he remembers the value $$$1$$$ (as $$$4$$$ has an odd number of $$$1$$$ bits in its binary representation). The second elf goes from node $$$2$$$ to node $$$5$$$. This elf's favorite number is $$$3$$$, so he remembers the value $$$0$$$ (as $$$3$$$ has an even number of $$$1$$$ bits in its binary representation). The third elf goes from node $$$5$$$ to node $$$6$$$. This elf's favorite number is $$$7$$$, so he remembers the value $$$1$$$ (as $$$7$$$ has an odd number of $$$1$$$ bits in its binary representation). The fourth elf goes from node $$$6$$$ to node $$$1$$$. This elf's favorite number is $$$1$$$, so he remembers the value $$$1$$$ (as $$$1$$$ has an odd number of $$$1$$$ bits in its binary representation). The fifth elf goes from node $$$4$$$ to node $$$5$$$. This elf's favorite number is $$$4$$$, so he remembers the number $$$1$$$ (as $$$4$$$ has an odd number of $$$1$$$ bits in its binary representation). Note that there are other possible answers. | 'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are $$$n$$$ nodes in the tree, connected by $$$n-1$$$ edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation. He has $$$m$$$ elves come over and admire his tree. Each elf is assigned two nodes, $$$a$$$ and $$$b$$$, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the bitwise XOR of the values of the lights on the edges in that path.However, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned $$$(a_i, b_i)$$$, as well as the parity of the number of set bits in his favorite number. In other words, he remembers whether the number of $$$1$$$'s when his favorite number is written in binary is odd or even.Help Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history! | For each test case, first print either YES or NO (in any case), whether there's a tree consistent with Santa's memory or not. If the answer is YES, print $$$n-1$$$ lines each containing three integers: $$$x$$$, $$$y$$$, and $$$v$$$ ($$$1 \le x, y \le n$$$; $$$0 \le v < 2^{30}$$$) — the edge and the integer on that edge. The set of edges must be the same as in the input, and if the value of some edge was specified earlier, it can not change. You can print the edges in any order. If there are multiple answers, print any. | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq m \leq 2 \cdot 10^5$$$) — the size of tree and the number of elves respectively. The next $$$n-1$$$ lines of each test case each contains three integers, $$$x$$$, $$$y$$$, and $$$v$$$ ($$$1 \leq x, y \leq n$$$; $$$-1 \leq v < 2^{30}$$$) — meaning that there's an edge between nodes $$$x$$$ and $$$y$$$. If $$$v = -1$$$: Santa doesn't remember what the set of lights were on for this edge. $$$v \geq 0$$$: The set of lights on the edge is $$$v$$$. The next $$$m$$$ lines of each test case each contains three integers, $$$a$$$, $$$b$$$, and $$$p$$$ ($$$1 \leq a, b \leq n$$$; $$$a \neq b$$$; $$$0 \leq p \leq 1$$$) — the nodes that the elf was assigned to, and the parity of the number of set bits in the elf's favorite number. It is guaranteed that the sum of all $$$n$$$ and the sum of all $$$m$$$ don't exceed $$$2 \cdot 10^5$$$ each. It is guaranteed that the given edges form a tree. | standard output | standard input | PyPy 3 | Python | 2,200 | train_100.jsonl | 47043625e837648a6cba1669566b4359 | 256 megabytes | ["4\n6 5\n1 2 -1\n1 3 1\n4 2 7\n6 3 0\n2 5 -1\n2 3 1\n2 5 0\n5 6 1\n6 1 1\n4 5 1\n5 3\n1 2 -1\n1 3 -1\n1 4 1\n4 5 -1\n2 4 0\n3 4 1\n2 3 1\n3 3\n1 2 -1\n1 3 -1\n1 2 0\n1 3 1\n2 3 0\n2 1\n1 2 1\n1 2 0"] | PASSED | from sys import stdin, stdout
from collections import deque
def parity(n):
parity = 0
while n:
parity = 1-parity
n = n & (n-1)
return parity
t = int(stdin.readline())
for _ in range(t):
n, m = [int(x) for x in stdin.readline().split()]
edges = []
fake_edges = {i: [] for i in range(n)}
possible = True
for bar in range(n-1):
x, y, v = [int(z) for z in stdin.readline().split()]
x -= 1
y -= 1
edges.append((x,y,v))
if v >= 0:
p = parity(v)
fake_edges[x].append((y,p))
fake_edges[y].append((x,p))
for bar in range(m):
x, y, v = [int(z) for z in stdin.readline().split()]
x -= 1
y -= 1
fake_edges[x].append((y,v))
fake_edges[y].append((x,v))
r_values = [-1]*n
touched = [False]*n
for i in range(n):
if not possible:
break
if not touched[i]:
queue = deque()
queue.append(i)
r_values[i] = 0
touched[i] = True
while len(queue) > 0:
if not possible:
break
v = queue.popleft()
for w,p in fake_edges[v]:
if r_values[w] == -1:
r_values[w] = r_values[v] ^ p
touched[w] = True
queue.append(w)
else:
if r_values[w] != r_values[v] ^ p:
possible = False
break
if possible:
stdout.write('YES\n')
for v, w, new_temp in edges:
if new_temp == -1:
new_temp = r_values[v] ^ r_values[w]
stdout.write('{} {} {}\n'.format(v+1,w+1,new_temp))
else:
stdout.write('NO\n')
| 1640356500 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["16", "24"] | 03bfe285856fa74b89de7a1bebb14bca | NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges $$$(1,3)$$$ and $$$(2,4)$$$ are crossed.Example 2Every permutation leads to a valid tree, so the answer is $$$4! = 24$$$. | Nauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are numbered from $$$1$$$ to $$$n$$$.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $$$n$$$ distinct points on the circle, and the edges should be straight without crossing each other."Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of $$$n$$$ elements. A permutation of $$$n$$$ elements is a sequence of integers $$$p_1,p_2,\ldots,p_n$$$ in which every integer from $$$1$$$ to $$$n$$$ appears exactly once.After a permutation is chosen Nauuo draws the $$$i$$$-th node in the $$$p_i$$$-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $$$998244353$$$, can you help her?It is obvious that whether a permutation is valid or not does not depend on which $$$n$$$ points on the circle are chosen. | The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $$$998244353$$$. | The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is an edge between $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. | standard output | standard input | Python 3 | Python | 1,900 | train_018.jsonl | d8788a4aab925b69120be07f1dc71ad7 | 256 megabytes | ["4\n1 2\n1 3\n2 4", "4\n1 2\n1 3\n1 4"] | PASSED | #import sys
#sys.stdin = open('inD', 'r')
n = int(input())
#a = [int(x) for x in input().split()]
#n,m = map(int, input().split())
ans = n
mod = 998244353
d = [0]*(n+1)
for i in range(n-1):
u,v = map(int, input().split())
d[u] += 1
d[v] += 1
ans = (ans * d[u] % mod) * d[v] % mod
print(ans)
| 1559909100 | [
"geometry",
"trees"
] | [
0,
1,
0,
0,
0,
0,
0,
1
] |
|
1 second | ["1", "1", "-1"] | bde1f233c7a49850c6b906af37982c27 | NoteIn the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one. | A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting. Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad? | Print $$$1$$$ if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations. Print $$$-1$$$ if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations. | The first line of input contains two integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{9}$$$, $$$0 \le k \le 2\cdot10^5$$$), where $$$n$$$ denotes total number of pirates and $$$k$$$ is the number of pirates that have any coins. The next $$$k$$$ lines of input contain integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le n$$$, $$$1 \le b_i \le 10^{9}$$$), where $$$a_i$$$ denotes the index of the pirate sitting at the round table ($$$n$$$ and $$$1$$$ are neighbours) and $$$b_i$$$ the total number of coins that pirate $$$a_i$$$ has at the start of the game. | standard output | standard input | PyPy 3 | Python | 2,700 | train_079.jsonl | d35ec812ca9c00c81f9aba0dec548858 | 256 megabytes | ["4 2\n1 2\n2 2", "6 2\n2 3\n4 1", "3 2\n1 1\n2 2"] | PASSED | import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n, k = map(int, input().split())
coins = 0
pos = 0
for _ in range(k):
a, b = map(int, input().split())
coins += b
pos += a * b
pos %= n
if coins < n or coins == n and (pos - (n*n-n)//2) % n == 0:
print(1)
else:
print(-1)
| 1601903100 | [
"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.