prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
β | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
β | prob_desc_input_spec
stringlengths 38
2.42k
β | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
β | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 seconds
|
["8\n6\n25"]
|
639eeeabcb005152035a1fcf09ed3b44
| null |
You are given a string $$$s$$$ consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i.Β e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string $$$s$$$.
|
For each test case, output a single integerΒ β the number of beautiful substrings of the string $$$s$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β number of test cases. The first and only line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) consisting of characters 0, 1, and ?. It is guaranteed that the sum of the string lengths over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400
|
train_085.jsonl
|
55574ab9369e8555c146282807e5d35b
|
256 megabytes
|
["3\n0?10\n???\n?10??1100"]
|
PASSED
|
'''
Author: your name
Date: 2021-12-10 14:18:39
LastEditTime: 2021-12-27 21:12:35
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /code_everyWeek/week3.py
'''
def unstable_string(input_str):
if len(input_str) == 1:
return 1
i = 0
j = 1
res = 0
lastj = 0
last_value = "0/1"
while i < len(input_str) and j < len(input_str):
ifok, last_value = judge_ok(input_str[j-1 : j+1], last_value)
if ifok:
j = j + 1
else:
res += (j - i) * (j - i + 1) // 2
if lastj > i:
res -= (lastj - i) * (lastj - i + 1) // 2
lastj = j
i = j
while i >= 0 and input_str[i-1] == '?':
i -= 1
last_value = "0/1"
j = i + 1
res += (j - i) * (j - i + 1) // 2
if lastj > i:
res -= (lastj - i) * (lastj - i +1) // 2
return res
def judge_ok(substr, last_value):
if substr == "10" or substr == "01" or (substr == "??" and last_value == "0/1"):
return True, last_value
if (substr == "?1" and last_value != "1") or (substr == "?0" and last_value != "0"):
return True, last_value
if substr == "??" and last_value == "0":
return True, "1"
if substr == "??" and last_value == "1":
return True, "0"
if substr == "1?":
return True, "0"
if substr == "0?":
return True, "1"
return False, last_value
def unstable_string_dp(input_str):
"""
ε¨ζθ§εεζ³
"""
ans = 0
n = len(input_str)
dp = [[0, 0] for i in range(n)]
if input_str[0] == '0':
dp[0][0] = 1
dp[0][1] = 0
elif input_str[0] == '1':
dp[0][0] = 0
dp[0][1] = 1
else:
dp[0][0] = 1
dp[0][1] = 1
ans += max(dp[0][1], dp[0][0])
for i in range(1, n):
if input_str[i] == '0':
dp[i][1] = 0
dp[i][0] = dp[i - 1][1] + 1
elif input_str[i] == '1':
dp[i][0] = 0
dp[i][1] = dp[i - 1][0] + 1
else:
dp[i][0] = dp[i - 1][1] + 1
dp[i][1] = dp[i - 1][0] + 1
ans += max(dp[i][1], dp[i][0])
return ans
if __name__ == "__main__":
num_test = int(input())
for i in range(num_test):
input_str = input()
res = unstable_string_dp(input_str)
print(res)
|
1622817300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["1 10", "2333333 2333333333333"]
|
52b8d97f216ea22693bc16fadcd46dae
| null |
Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234)β=β1β+β2β+β3β+β4). You are to calculate Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code: ans = solve(l, r) % a; if (ans <= 0) ans += a; This code will fail only on the test with . You are given number a, help Little X to find a proper test for hack.
|
Print two integers: l,βrΒ (1ββ€βlββ€βrβ<β10200) β the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.
|
The first line contains a single integer aΒ (1ββ€βaββ€β1018).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,500
|
train_024.jsonl
|
db8e385bb243dfd901f89b9483be9204
|
256 megabytes
|
["46", "126444381000032"]
|
PASSED
|
a=int(input())
d=10**100-1;
x=a-100*45*10**99%a
print(x,x+d)
|
1411218000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["16", "1", "10", "1"]
|
d666df06a7a7ecbe801c1018b3d482b9
|
NoteSome strings you can obtain in the first example: to obtain 0110110, you can take the substring from the $$$1$$$-st character to the $$$4$$$-th character, which is 1100, and reorder its characters to get 0110; to obtain 1111000, you can take the substring from the $$$3$$$-rd character to the $$$7$$$-th character, which is 00110, and reorder its characters to get 11000; to obtain 1100101, you can take the substring from the $$$5$$$-th character to the $$$7$$$-th character, which is 110, and reorder its characters to get 101. In the second example, $$$k = 0$$$ so you can only choose the substrings consisting only of 0 characters. Reordering them doesn't change the string at all, so the only string you can obtain is 10010.
|
You are given a binary string (i.βe. a string consisting of characters 0 and/or 1) $$$s$$$ of length $$$n$$$. You can perform the following operation with the string $$$s$$$ at most once: choose a substring (a contiguous subsequence) of $$$s$$$ having exactly $$$k$$$ characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).Calculate the number of different strings which can be obtained from $$$s$$$ by performing this operation at most once.
|
Print one integer β the number of different strings which can be obtained from $$$s$$$ by performing the described operation at most once. Since the answer can be large, output it modulo $$$998244353$$$.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 5000$$$; $$$0 \le k \le n$$$). The second line contains the string $$$s$$$ of length $$$n$$$, consisting of characters 0 and/or 1.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000
|
train_085.jsonl
|
9f6e5587e9aec288e916e1128ec1332c
|
512 megabytes
|
["7 2\n1100110", "5 0\n10010", "8 1\n10001000", "10 8\n0010011000"]
|
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
from tkinter import N
# 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())):
# a, b, c = list(map(int, input().split(' ')))
# if (a == b and c % 2 == 0) or (b == c and a % 2 == 0) or (a == c and b % 2 == 0):
# print('YES')
# continue
# s = [a, b, c]
# s.sort()
# if s[0] + s[1] == s[2]:
# print('YES')
# continue
# print('NO')
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# s = input()
# cnt = s.count('0')
# ans = [0] * n
# hi = []
# lo = []
# for i in range(n):
# if s[i] == '1':
# if a[i] > cnt:
# ans[i] = a[i]
# else:
# hi.append(a[i])
# ans[i] = -1
# else:
# if a[i] <= cnt:
# ans[i] = a[i]
# else:
# lo.append(a[i])
# ans[i] = -2
# for i in range(n):
# if ans[i] == -1:
# ans[i] = lo.pop()
# elif ans[i] == -2:
# ans[i] = hi.pop()
# print(*ans)
# for _ in range(int(input())):
# n, k = list(map(int, input().split(' ')))
# a = list(map(int, input().split(' ')))
# a.sort()
# pre = list(accumulate(a))
# ans = float('inf')
# for i in range(n):
# res = i
# tmp = pre[n - 1 - i] - pre[0]
# res += max(0, a[0] - (k - tmp) // (i + 1))
# ans = min(ans, res)
# print(ans)
mod = 998244353
N = 5010
fac = [1] * N
for i in range(2, N):
fac[i] = fac[i - 1] * i % mod
invfac = [1] * N
invfac[N - 1] = pow(fac[N - 1], mod - 2, mod)
for i in range(N - 1)[::-1]:
invfac[i] = invfac[i + 1] * (i + 1) % mod
def c(i, j):
return fac[i] * invfac[j] * invfac[i - j] % mod
def solve():
n, k = list(map(int, input().split(' ')))
a = list(map(int, input()))
pre = list(accumulate(a))
tmp = []
for i in range(n):
if i == 0:
r = bisect_right(pre, k)
if r - 1 >= 0 and pre[r - 1] == k:
tmp.append((i, r - 1))
else:
if a[i - 1] == 0: continue
r = bisect_right(pre, k + pre[i - 1])
if r - 1 >= i and pre[r - 1] == k + pre[i - 1]:
tmp.append((i, r - 1))
if not tmp:
print(1)
return
ans = 1
m = len(tmp)
for i in range(m):
l, r = tmp[i]
if l == 0:
cnt1 = pre[r]
else:
cnt1 = pre[r] - pre[l - 1]
ans += c(r - l + 1, cnt1) - 1
ans %= mod
if i > 0:
j = i - 1
r = tmp[j][1]
if l <= r:
if l == 0:
cnt1 = pre[r]
else:
cnt1 = pre[r] - pre[l - 1]
ans -= c(r - l + 1, cnt1) - 1
ans %= mod
print(ans % mod)
solve()
|
1640615700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0.200000000", "6.032163204", "3.000000000"]
|
db4a25159067abd9e3dd22bc4b773385
| null |
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant β 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.
|
Print one real number β the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10β-β6.
|
The first line contains two integers n and k (2ββ€βnββ€β100, 1ββ€βkββ€β1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai β integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.
|
standard output
|
standard input
|
Python 3
|
Python
| 900
|
train_012.jsonl
|
273a886296b7dce8d072b5688db9d8a9
|
256 megabytes
|
["2 1\n0 0\n10 0", "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0", "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0"]
|
PASSED
|
inn = list(map(int, input().split(" ")))
pnts = inn[0]
mult = inn[1]
dist = 0
c = list(map(int, input().split(" ")))
for i in range(1,pnts):
s = list(map(int, input().split(" ")))
x1 = c[0]
x2 = s[0]
y1 = c[1]
y2 = s[1]
dist += ((((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** 0.5)
c = s
tt = (dist/50)*mult
print('%.9f'%tt)
|
1320858000
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["a\nz\n\nbc"]
|
586a15030f4830c68f2ea1446e80028c
| null |
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened: if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing; if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.
|
For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000
|
train_000.jsonl
|
742d9aea83f22f45def1b3e7dff87a55
|
256 megabytes
|
["4\na\nzzaaz\nccff\ncbddbb"]
|
PASSED
|
t = int(input())
for tt in range(t):
s=input()
l=set()
#l.append(s[0])
n=len(s)
if n==1:
print(s,end="")
else:
left = 0
right = 1
while left<n and right<n:
if s[left]==s[right]:
left+=2
right+=2
else:
l.add(s[left])
left+=1
right+=1
if left==n-1:
l.add(s[left])
li = list(l)
li.sort()
for i in li:
print(i,end="")
print("")
|
1571929500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["160", "645"]
|
f9c53d180868776b6a2ee3f57c3b3a21
|
NotePossible partitions in the first sample: {{1,β2,β3},β{4}}, W(R)β=β3Β·(w1β+βw2β+βw3)β+β1Β·w4β=β24; {{1,β2,β4},β{3}}, W(R)β=β26; {{1,β3,β4},β{2}}, W(R)β=β24; {{1,β2},β{3,β4}}, W(R)β=β2Β·(w1β+βw2)β+β2Β·(w3β+βw4)β=β20; {{1,β3},β{2,β4}}, W(R)β=β20; {{1,β4},β{2,β3}}, W(R)β=β20; {{1},β{2,β3,β4}}, W(R)β=β26; Possible partitions in the second sample: {{1,β2,β3,β4},β{5}}, W(R)β=β45; {{1,β2,β3,β5},β{4}}, W(R)β=β48; {{1,β2,β4,β5},β{3}}, W(R)β=β51; {{1,β3,β4,β5},β{2}}, W(R)β=β54; {{2,β3,β4,β5},β{1}}, W(R)β=β57; {{1,β2,β3},β{4,β5}}, W(R)β=β36; {{1,β2,β4},β{3,β5}}, W(R)β=β37; {{1,β2,β5},β{3,β4}}, W(R)β=β38; {{1,β3,β4},β{2,β5}}, W(R)β=β38; {{1,β3,β5},β{2,β4}}, W(R)β=β39; {{1,β4,β5},β{2,β3}}, W(R)β=β40; {{2,β3,β4},β{1,β5}}, W(R)β=β39; {{2,β3,β5},β{1,β4}}, W(R)β=β40; {{2,β4,β5},β{1,β3}}, W(R)β=β41; {{3,β4,β5},β{1,β2}}, W(R)β=β42.
|
You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as . The weight of some partition R of a given set into k subsets is (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 109β+β7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.
|
Print one integer β the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 109β+β7.
|
The first line contains two integers n and k (1ββ€βkββ€βnββ€β2Β·105) β the number of elements and the number of subsets in each partition, respectively. The second line contains n integers wi (1ββ€βwiββ€β109)β weights of elements of the set.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700
|
train_024.jsonl
|
a3d24fe5ccf6a3bfc6cd9d4da3d32767
|
256 megabytes
|
["4 2\n2 3 2 3", "5 2\n1 2 3 4 5"]
|
PASSED
|
n, k = map(int, input().split())
MOD = 10**9+7
def fast_modinv(up_to, M):
''' Fast modular inverses of 1..up_to modulo M. '''
modinv = [-1 for _ in range(up_to + 1)]
modinv[1] = 1
for x in range(2, up_to + 1):
modinv[x] = (-(M//x) * modinv[M%x])%M
return modinv
maxn = 2*10**5 + 10
modinv = fast_modinv(maxn, MOD)
fact, factinv = [1], [1]
for i in range(1, maxn):
fact.append(fact[-1]*i % MOD)
factinv.append(factinv[-1]*modinv[i] % MOD)
def Stirling(n, k):
'''The Stirling number of second kind (number of nonempty partitions). '''
if k > n:
return 0
result = 0
for j in range(k+1):
result += (-1 if (k-j)&1 else 1) * fact[k] * factinv[j] * factinv[k - j] * pow(j, n, MOD) % MOD
result %= MOD
result *= factinv[k]
return result % MOD
W = sum(map(int, input().split())) % MOD
print((Stirling(n, k) + (n - 1) * Stirling(n - 1, k))* W % MOD)
|
1522850700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["> 25\n\n> 15\n\n? 1\n\n? 2\n\n? 3\n\n? 4\n\n! 9 5"]
|
36619f520ea5a523a94347ffd3dc2c70
|
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is $$$[14, 24, 9, 19]$$$.
|
This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($$$x_i - x_{i - 1}$$$, where $$$i \ge 2$$$) is constantΒ β such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form $$$x_i = x_1 + (i - 1) d$$$, where $$$d$$$ is a common difference of the sequence.There is a secret list of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$.It is guaranteed that all elements $$$a_1, a_2, \ldots, a_n$$$ are between $$$0$$$ and $$$10^9$$$, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($$$d > 0$$$). For example, the list $$$[14, 24, 9, 19]$$$ satisfies this requirement, after sorting it makes a list $$$[9, 14, 19, 24]$$$, which can be produced as $$$x_n = 9 + 5 \cdot (n - 1)$$$.Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $$$60$$$ queries of following two types: Given a value $$$i$$$ ($$$1 \le i \le n$$$), the device will show the value of the $$$a_i$$$. Given a value $$$x$$$ ($$$0 \le x \le 10^9$$$), the device will return $$$1$$$ if an element with a value strictly greater than $$$x$$$ exists, and it will return $$$0$$$ otherwise.Your can use this special device for at most $$$60$$$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $$$x_1$$$ and $$$d$$$ in the definition of the arithmetic progression. Note that the array $$$a$$$ is not sorted.
| null | null |
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200
|
train_013.jsonl
|
4023ddebd43f29b8818cc4f2e948b70f
|
256 megabytes
|
["4\n\n0\n\n1\n\n14\n\n24\n\n9\n\n19"]
|
PASSED
|
from __future__ import division
from random import sample
from sys import stdin, stdout
from fractions import gcd
def write(x):
stdout.write(str(x) + "\n")
stdout.flush()
def get():
rec = stdin.readline()
if "-1" in rec:
[][0]
return rec
n = int(get())
queries = 0
low = 0
high = 10 ** 9
while low + 1 != high:
mid = (low + high) // 2
write("> {}".format(mid))
queries += 1
if "1" in get():
low = mid
else:
high = mid
top = high
div = 0
for i in sample(xrange(1, n+1), min(60 - queries, n)):
write("? {}".format(i))
dist = top - int(get())
div = gcd(div, dist)
write("! {} {}".format(top - div * (n - 1), div))
|
1549807500
|
[
"number theory",
"probabilities"
] |
[
0,
0,
0,
0,
1,
1,
0,
0
] |
|
2 seconds
|
["1", "4", "0"]
|
0d95c84e73aa9b6567eadeb16acfda41
|
NoteHere is the tree from the first example: The only nice edge is edge $$$(2, 4)$$$. Removing it makes the tree fall apart into components $$$\{4\}$$$ and $$$\{1, 2, 3, 5\}$$$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.Here is the tree from the second example: Every edge is nice in it.Here is the tree from the third example: Edge $$$(1, 3)$$$ splits the into components $$$\{1\}$$$ and $$$\{3, 2\}$$$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $$$(2, 3)$$$ splits the into components $$$\{1, 3\}$$$ and $$$\{2\}$$$, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
|
You are given an undirected tree of $$$n$$$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree?
|
Print a single integer β the number of nice edges in the given tree.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) β the number of vertices in the tree. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2$$$) β the colors of the vertices. $$$a_i = 1$$$ means that vertex $$$i$$$ is colored red, $$$a_i = 2$$$ means that vertex $$$i$$$ is colored blue and $$$a_i = 0$$$ means that vertex $$$i$$$ is uncolored. The $$$i$$$-th of the next $$$n - 1$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \ne u_i$$$) β the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,800
|
train_008.jsonl
|
9ac6fd4edc3bd0b8f1970ba0d3d6cb25
|
256 megabytes
|
["5\n2 0 0 1 2\n1 2\n2 3\n2 4\n2 5", "5\n1 0 0 0 2\n1 2\n2 3\n3 4\n4 5", "3\n1 1 2\n2 3\n1 3"]
|
PASSED
|
#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>
"""
from __future__ import division, print_function
import itertools
import os
import sys
from atexit import register
from io import BytesIO
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
res = 0
def main():
n = int(input())
a = input().split()
red_cnt = a.count('1')
blue_cnt = a.count('2')
tree = [[] for _ in range(n)]
for _ in range(n - 1):
v, u = map(int, input().split())
tree[v - 1].append(u - 1)
tree[u - 1].append(v - 1)
dp, visited = [[0, 0] for _ in range(n)], [False] * n
def dfs(node):
global res
finished = [False] * n
stack = [node]
while stack:
node = stack[-1]
node_cnt = dp[node]
if not visited[node]:
visited[node] = True
else:
stack.pop()
node_cnt[0] += a[node] == '1'
node_cnt[1] += a[node] == '2'
finished[node] = True
for child in tree[node]:
if not visited[child]:
stack.append(child)
elif finished[child]:
child_cnt = dp[child]
node_cnt[0] += child_cnt[0]
node_cnt[1] += child_cnt[1]
if ((child_cnt[0] == red_cnt) and (child_cnt[1] == 0)) or ((child_cnt[0] == 0) and
(child_cnt[1] == blue_cnt)):
res += 1
dfs(0)
print(res)
if __name__ == '__main__':
main()
|
1550586900
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["Vivek\nAshish\nVivek\nAshish"]
|
3ccc98190189b0c8e58a96dd5ad1245d
|
NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left.
|
Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.
|
For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).
|
The first line consists of a single integer $$$t$$$ $$$(1 \le t \le 50)$$$Β β the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$Β β the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,100
|
train_004.jsonl
|
348d406e087873dab5e55ffc0182bc74
|
256 megabytes
|
["4\n2 2\n0 0\n0 0\n2 2\n0 0\n0 1\n2 3\n1 0 1\n1 1 0\n3 3\n1 0 0\n0 0 0\n1 0 0"]
|
PASSED
|
for _ in range(int(input())):
n,m=map(int,input().split())
mat=[]
r=[0]*n
for i in range(n):
a=list(map(int,input().split()))
if 1 in a:
r[i]=1
mat.append(a)
#print(mat[0][1])
c=[0]*m
for i in range(m):
for j in range(n):
if mat[j][i]==1:
c[i]=1
break
#print(r,c)
count=0
rd=0
cd=0
for i in r:
if i==1:
#print(r[i])
rd+=1
for i in c:
if i==1:
cd+=1
#print(rd,cd)
rd=n-rd
cd=m-cd
ma=min(rd,cd)
if(ma%2):
print('Ashish')
else:
print('Vivek')
'''if(rd>cd):
ma=n-rd
if(ma%2):
print('Ashish')
else:
print('Vivek')
else:
ma=m-cd
if(ma%2):
print('Ashish')
else:
print('Vivek')'''
|
1591540500
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["0 6 2 \n-1 -1 \n1 3"]
|
ecc9dc229b5d1f93809fb676eb6235c1
| null |
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with $$$n$$$ integers written on it.Polycarp wrote the numbers from the disk into the $$$a$$$ array. It turned out that the drive works according to the following algorithm: the drive takes one positive number $$$x$$$ as input and puts a pointer to the first element of the $$$a$$$ array; after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the $$$a$$$ array, the last element is again followed by the first one; as soon as the sum is at least $$$x$$$, the drive will shut down. Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you $$$m$$$ questions. To answer the $$$i$$$-th of them, you need to find how many seconds the drive will work if you give it $$$x_i$$$ as input. Please note that in some cases the drive can work infinitely.For example, if $$$n=3, m=3$$$, $$$a=[1, -3, 4]$$$ and $$$x=[1, 5, 2]$$$, then the answers to the questions are as follows: the answer to the first query is $$$0$$$ because the drive initially points to the first item and the initial sum is $$$1$$$. the answer to the second query is $$$6$$$, the drive will spin the disk completely twice and the amount becomes $$$1+(-3)+4+1+(-3)+4+1=5$$$. the answer to the third query is $$$2$$$, the amount is $$$1+(-3)+4=2$$$.
|
Print $$$m$$$ numbers on a separate line for each test case. The $$$i$$$-th number is: $$$-1$$$ if the drive will run infinitely; the number of seconds the drive will run, otherwise.
|
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 consists of two positive integers $$$n$$$, $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$)Β β the number of numbers on the disk and the number of asked questions. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line of each test case contains $$$m$$$ positive integers $$$x_1, x_2, \ldots, x_m$$$ ($$$1 \le x \le 10^9$$$). It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900
|
train_098.jsonl
|
2769e44e1d60ad2f696f8bd7de190062
|
256 megabytes
|
["3\n3 3\n1 -3 4\n1 5 2\n2 2\n-2 0\n1 2\n2 2\n0 1\n1 2"]
|
PASSED
|
import sys
from bisect import bisect_left
from itertools import accumulate
def solve(n, m, a, x):
p = list(accumulate(a))
s = p[-1]
for i in range(1, n):
p[i] = max(p[i], p[i-1])
ans = list()
for i in range(m):
if s <= 0 and x[i] > p[-1]:
ans.append(-1)
continue
elif s <= 0 or x[i] <= p[-1]:
k = 0
else:
k = (x[i] - p[-1]) // s
if (x[i] - p[-1]) % s > 0:
k += 1
x[i] -= k * s
index = bisect_left(p, x[i])
ans.append(k * n + index)
return ans
def main(argv=None):
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
x = list(map(int, input().split()))
print(' '.join(map(str, solve(n, m, a, x))))
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
|
1613486100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["3", "1", "0"]
|
d5913f8208efa1641f53caaee7624622
|
NoteNote to the first sample test. There are 3 triangles formed: (0,β0)β-β(1,β1)β-β(2,β0); (0,β0)β-β(2,β2)β-β(2,β0); (1,β1)β-β(2,β2)β-β(2,β0).Note to the second sample test. There is 1 triangle formed: (0,β0)β-β(1,β1)β-β(2,β0).Note to the third sample test. A single point doesn't form a single triangle.
|
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
|
In the first line print an integer β the number of triangles with the non-zero area among the painted points.
|
The first line contains integer n (1ββ€βnββ€β2000) β the number of the points painted on the plane. Next n lines contain two integers each xi,βyi (β-β100ββ€βxi,βyiββ€β100) β the coordinates of the i-th point. It is guaranteed that no two given points coincide.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900
|
train_015.jsonl
|
0533264df55564b9a5e65f767480df63
|
512 megabytes
|
["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"]
|
PASSED
|
from fractions import gcd
N = input()
points = [map(int, raw_input().split()) for _ in xrange(N)]
ans = N * (N-1) * (N-2) // 6
lines = {}
for i in xrange(N-1):
for j in range(i+1, N):
x1, y1 = points[i]
x2, y2 = points[j]
g = gcd(x1-x2, y1-y2)
dx, dy = (x1-x2)//g, (y1-y2)//g
a, b, c = dy, dx, dx * y1 - dy * x1
lines[(a, b, c)] = lines.get((a, b, c), 0) + 1
for val in lines.values():
if val != 1:
n = (1 + int(pow(1+8*val, 0.5))) // 2
ans -= n * (n-1) * (n-2) // 6
print(ans)
|
1434645000
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["a\nabcdfdcba\nxyzyx\nc\nabba"]
|
042008e186c5a7265fbe382b0bdfc9bc
|
NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$. It is a palindrome. "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".
|
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions: The length of $$$t$$$ does not exceed the length of $$$s$$$. $$$t$$$ is a palindrome. There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.
|
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
|
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$5000$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500
|
train_005.jsonl
|
13d6438ca59a651779ff99f96e465480
|
256 megabytes
|
["5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba"]
|
PASSED
|
import sys, heapq as h
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import math
"""
Longest matching prefix and suffix
Then for each start / end point, the longest palindrome going forwards and then longest palidrome going backwards
"""
def longest_prefix_suffix_palindrome(S,N):
i = -1
while i+1 <= N-i-2 and S[i+1] == S[N-i-2]:
i += 1
return i
def longest_palindromic_prefix(S):
tmp = S + "?"
S = S[::-1]
tmp = tmp + S
N = len(tmp)
lps = [0] * N
for i in range(1, N):
#Length of longest prefix till less than i
L = lps[i - 1]
# Calculate length for i+1
while (L > 0 and tmp[L] != tmp[i]):
L = lps[L - 1]
#If character at current index and L are same then increment length by 1
if (tmp[i] == tmp[L]):
L += 1
#Update the length at current index to L
lps[i] = L
return tmp[:lps[N - 1]]
def solve():
S = getStr()
N = len(S)
i = longest_prefix_suffix_palindrome(S,N)
#so S[:i+1] and S[N-i-1:] are palindromic
if i >= N//2-1:
return S
#so there are least 2 elements between S[i] and S[N-i-1]
new_str = S[i+1:N-i-1]
longest_pref = longest_palindromic_prefix(new_str)
longest_suff = longest_palindromic_prefix(new_str[::-1])[::-1]
add_on = longest_pref if len(longest_pref) >= len(longest_suff) else longest_suff
return S[:i+1] + add_on + S[N-i-1:]
for _ in range(getInt()):
print(solve())
#print(solve())
|
1584628500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["1 2 2 4", "2 1 4 3 1", "3 4 2 7 7 3"]
|
4de02364b27e697b5750f0bd88fac821
| null |
You are given a weighted undirected connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Let's define the weight of the path consisting of $$$k$$$ edges with indices $$$e_1, e_2, \dots, e_k$$$ as $$$\sum\limits_{i=1}^{k}{w_{e_i}} - \max\limits_{i=1}^{k}{w_{e_i}} + \min\limits_{i=1}^{k}{w_{e_i}}$$$, where $$$w_i$$$ β weight of the $$$i$$$-th edge in the graph.Your task is to find the minimum weight of the path from the $$$1$$$-st vertex to the $$$i$$$-th vertex for each $$$i$$$ ($$$2 \le i \le n$$$).
|
Print $$$n-1$$$ integers β the minimum weight of the path from $$$1$$$-st vertex to the $$$i$$$-th vertex for each $$$i$$$ ($$$2 \le i \le n$$$).
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) β the number of vertices and the number of edges in the graph. Following $$$m$$$ lines contains three integers $$$v_i, u_i, w_i$$$ ($$$1 \le v_i, u_i \le n$$$; $$$1 \le w_i \le 10^9$$$; $$$v_i \neq u_i$$$) β endpoints of the $$$i$$$-th edge and its weight respectively.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400
|
train_106.jsonl
|
a254bf34f9b6d4214757bd9b4c73e7d3
|
256 megabytes
|
["5 4\n5 3 4\n2 1 1\n3 2 2\n2 4 2", "6 8\n3 1 1\n3 6 2\n5 4 2\n4 2 2\n6 1 1\n5 2 1\n3 2 3\n1 5 4", "7 10\n7 5 5\n2 3 3\n4 7 1\n5 3 6\n2 7 6\n6 2 6\n3 7 6\n4 2 1\n3 1 4\n1 7 4"]
|
PASSED
|
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args) # 2979 ms
return dijkstraHeapComparatorWrong(*args) # 2823 ms
# return dijkstraHeapComparator(*args) # 2370 ms
# return dijkstraSegTree(*args) # 2417 ms with inf=float('inf), 2995 ms with inf=-1
# return dijkstraSortedList(*args) # 2995 ms
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
|
1610634900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["5 3 1 2 4", "7 3 2 1 4 5 6", "7 4 2 3 6 5 1", "2 1 4 5 3"]
|
bef323e7c8651cc78c49db38e49ba53d
| null |
There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.
|
Print $$$n$$$ integers $$$nf_1, nf_2, \dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.
|
The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, all $$$f_i \ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,500
|
train_005.jsonl
|
db0bff0f1fc2d9a07f73a948b77a9625
|
256 megabytes
|
["5\n5 0 0 2 4", "7\n7 0 0 1 4 0 6", "7\n7 4 0 3 0 5 1", "5\n2 1 0 0 0"]
|
PASSED
|
# -*- coding: utf-8 -*-
import sys
def read_int_list():
return map(int, sys.stdin.readline().strip().split())
def read_int():
return int(sys.stdin.readline().strip())
def solve():
_ = read_int()
friends = read_int_list()
with_present = set()
unknown = set()
for idx, f in enumerate(friends, 1):
if f > 0:
with_present.add(f)
else:
unknown.add(idx)
without_present = set(xrange(1, len(friends) + 1)) - with_present
# print('with present', with_present)
# print('without present', without_present)
# print('unknown', unknown)
hm = {}
common = unknown.intersection(without_present)
for u in common:
removed = False
if u in without_present:
without_present.remove(u)
removed = True
el = without_present.pop()
hm[u] = el
if removed:
without_present.add(u)
unknown = unknown - common
for u in unknown:
el = without_present.pop()
hm[u] = el
# print('u', u, 'without present', without_present, 'hm', hm)
# print('hm', hm)
for i in xrange(len(friends)):
idx = i + 1
v = friends[i]
if v == 0:
friends[i] = hm[idx]
sys.stdout.write(' '.join(map(str, friends)) + '\n')
solve()
|
1577552700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["-1\n330\n-1\n40"]
|
c01a5ed6a598a1c443611a8f1b1a3db7
|
NoteAll the subsets of multiset $$$\{20, 300, 10001\}$$$ are balanced, thus the answer is -1.The possible unbalanced subsets in the third query are $$$\{20, 310\}$$$ and $$$\{20, 310, 10001\}$$$. The lowest sum one is $$$\{20, 310\}$$$. Note that you are asked to choose a subset, not a subsegment, thus the chosen elements might not be adjancent in the array.The fourth query includes only the empty subset and subset $$$\{20\}$$$. Both of them are balanced.The last query includes the empty subset and the subsets $$$\{20\}$$$, $$$\{20\}$$$ and $$$\{20, 20\}$$$. Only $$$\{20, 20\}$$$ is unbalanced, its sum is $$$40$$$. Note that you are asked to choose a multiset, thus it might include equal elements.
|
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.For example, multiset $$$\{20, 300, 10001\}$$$ is balanced and multiset $$$\{20, 310, 10001\}$$$ is unbalanced: The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is $$$10321$$$, every position has the digit required. The sum of the second multiset is $$$10331$$$ and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ integers.You are asked to perform some queries on it. The queries can be of two types: $$$1~i~x$$$ β replace $$$a_i$$$ with the value $$$x$$$; $$$2~l~r$$$ β find the unbalanced subset of the multiset of the numbers $$$a_l, a_{l + 1}, \dots, a_r$$$ with the minimum sum, or report that no unbalanced subset exists. Note that the empty multiset is balanced.For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
|
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
|
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i < 10^9$$$). Each of the following $$$m$$$ lines contains a query of one of two types: $$$1~i~x$$$ ($$$1 \le i \le n$$$, $$$1 \le x < 10^9$$$) β replace $$$a_i$$$ with the value $$$x$$$; $$$2~l~r$$$ ($$$1 \le l \le r \le n$$$) β find the unbalanced subset of the multiset of the numbers $$$a_l, a_{l + 1}, \dots, a_r$$$ with the lowest sum, or report that no unbalanced subset exists. It is guaranteed that there is at least one query of the second type.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,300
|
train_045.jsonl
|
293f8cd68d6c41736e45fbbad469cf4d
|
256 megabytes
|
["4 5\n300 10001 20 20\n2 1 3\n1 1 310\n2 1 3\n2 3 3\n2 3 4"]
|
PASSED
|
class segtree:
def __init__(s, data):
s.n = len(data)
s.m = 1
while s.m < s.n: s.m *= 2
s.data = [0]*(2*s.m)
s.data[s.m : s.m + s.n] = data
for i in reversed(range(1, s.m)):
s.data[i] = min(s.data[2*i], s.data[2*i + 1])
def set(s,i,val):
i += s.m
while i:
s.data[i] = val
val = min(val, s.data[i ^ 1])
i >>= 1
def min(s,index):
ans = min(index, key = s.data.__getitem__)
goal = s.data[ans]
while ans < s.m:
ans <<= 1
if s.data[ans] != goal:
ans += 1
return ans - s.m, goal
def main():
big = 10**9 + 1
inp = readnumbers()
ii = 0
n = inp[ii]
ii += 1
m = inp[ii]
ii += 1
M = 1
while M < n:
M *= 2
A = inp[ii:ii+n]
ii += n
B = list(A)
segs = []
for _ in range(9):
tmp = []
for i in range(n):
B[i], diff = divmod(B[i], 10)
tmp.append(A[i] if diff else big)
segs.append(segtree(tmp))
for _ in range(m):
c = inp[ii]
ii += 1
if c == 1:
i = inp[ii] - 1
ii += 1
x = inp[ii]
ii += 1
A[i] = xx = x
for seg in segs:
xx, diff = divmod(xx, 10)
seg.set(i, x if diff else big)
else:
l = inp[ii] - 1
ii += 1
r = inp[ii]
ii += 1
if r - l <= 1:
cout << -1 << '\n'
continue
L = l + M
R = r + M
index = []
while L < R:
if L & 1:
index.append(L)
L += 1
if R & 1:
index.append(R - 1)
L >>= 1
R >>= 1
minval = 2 * big
for seg in segs:
idx,val = seg.min(index)
if 2 * val < minval:
seg.set(idx, big)
idx2,val2 = seg.min(index)
seg.set(idx, val)
if val2 != big:
minval = min(minval, val + val2)
cout << (minval if minval - 2 * big else -1) << '\n'
######## 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
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["First\nSecond\nSecond\nFirst"]
|
5f5b320c7f314bd06c0d2a9eb311de6c
|
NoteIn the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.In the third sample, the first player has no moves.In the fourth sample, the first player wins in one move, taking 30 modulo 10.
|
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it β a and b. The order of the numbers is not important. Let's consider aββ€βb for the sake of definiteness. The players can cast one of the two spells in turns: Replace b with bβ-βak. Number k can be chosen by the player, considering the limitations that kβ>β0 and bβ-βakββ₯β0. Number k is chosen independently each time an active player casts a spell. Replace b with bΒ modΒ a. If aβ>βb, similar moves are possible.If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.
|
For any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input.
|
The first line contains a single integer t β the number of input data sets (1ββ€βtββ€β104). Each of the next t lines contains two integers a, b (0ββ€βa,βbββ€β1018). The numbers are separated by a space. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,300
|
train_029.jsonl
|
7fdb0cb83d1f664f866c7230fe3ddb25
|
256 megabytes
|
["4\n10 21\n31 10\n0 1\n10 30"]
|
PASSED
|
import sys
from math import *
def win(a,b):
if (a==0):
return False
if (b==0):
return False
if (not win(b%a,a)):
return True
ans=b//a
ans%=a+1
ans%=2
if (ans%2==1):
return False
else:
return True
try:
fi = open("input.txt", "r")
fo = open("output.txt", "w")
except:
fi = sys.stdin
fo = sys.stdout
tests=int(fi.readline())
for test in range(tests):
a,b=map(int,fi.readline().split())
if (win(min(a,b),max(a,b))):
fo.write("First\n")
else:
fo.write("Second\n")
|
1332860400
|
[
"math",
"games"
] |
[
1,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["Yes\n2 1\n1 3 \n2 \nYes\n1 2\n2 \n1 3 \nNo\nNo"]
|
f91197e474bdc3f2b881d556a330e36b
|
NoteIn the first test case, we can select the first and the third resident as a jury. Both of them are not acquaintances with a second cat, so we can select it as a contestant.In the second test case, we can select the second resident as a jury. He is not an acquaintances with a first and a third cat, so they can be selected as contestants.In the third test case, the only resident is acquaintances with the only cat, so they can't be in the contest together. So it's not possible to make a contest with at least one jury and at least one cat.In the fourth test case, each resident is acquaintances with every cat, so it's again not possible to make a contest with at least one jury and at least one cat.
|
In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $$$n$$$ residents and $$$n$$$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th cat is living in the house of $$$i$$$-th resident.Each Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to $$$n$$$.Please help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.
|
For every test case print: "No", if it's impossible to select the jury and contestants. Otherwise print "Yes".In the second line print two integers $$$j$$$ and $$$p$$$ ($$$1 \le j$$$, $$$1 \le p$$$, $$$j + p = n$$$)Β β the number of jury members and the number of contest participants.In the third line print $$$j$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the residents forming a jury.In the fourth line print $$$p$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the cats, which will participate in the contest.In case there are several correct answers, print any of them.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), the number of test cases. Then description of $$$t$$$ test cases follow, where each description is as follows: The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le m \le 10^6$$$), the number of Catowice residents and the number of friendship pairs between residents and cats. Each of the next $$$m$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that $$$a_i$$$-th resident is acquaintances with $$$b_i$$$-th cat. It's guaranteed that each pair of some resident and some cat is listed at most once. It's guaranteed, that for every $$$i$$$ there exists a pair between $$$i$$$-th resident and $$$i$$$-th cat. Different test cases are separated with an empty line. It's guaranteed, that the sum of $$$n$$$ over all test cases is at most $$$10^6$$$ and that the sum of $$$m$$$ over all test cases is at most $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,400
|
train_054.jsonl
|
2d74438d128084b4838c6352e62d534f
|
512 megabytes
|
["4\n3 4\n1 1\n2 2\n3 3\n1 3\n\n3 7\n1 1\n1 2\n1 3\n2 2\n3 1\n3 2\n3 3\n\n1 1\n1 1\n\n2 4\n1 1\n1 2\n2 1\n2 2"]
|
PASSED
|
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
def add(dic,k,v):
if not dic.has_key(k):
dic[k] = v
else:
dic[k] += v
def main():
t = int(input())
for _ in range(t):
n,m = map(int,input().split(" "))
pairs = []
for i in range(m):
a,b = map(int,input().split(" "))
if a == b:
continue
pairs.append((a,b))
space = input()
if n == 1:
print "No"
continue
edges = {}
low = [-1]*(n+1)
dfn = [-1]*(n+1)
visited = [0]*(n+1)
for i in range(1,n+1):
add(edges,i,[])
for a,b in pairs:
add(edges,a,[b])
cnt = 1
stack = []
trace = []
res = []
tmp = []
for i in range(1,n+1):
if visited[i]:
continue
visited[i] = 1
stack.append(i)
while stack:
#print "stack",stack,"trace",trace
node = stack[-1]
if visited[node] == 2:
stack.pop()
continue
visited[node] = 1
flag = True
if dfn[node] == -1:
trace.append(node)
dfn[node] = cnt
low[node] = cnt
cnt += 1
flag = False
for nb in edges[node]:
if flag and dfn[nb]>dfn[node]:
low[node] = min(low[node],low[nb])
elif not visited[nb]:
# visited[nb] = 1
stack.append(nb)
elif visited[nb] == 1:
low[node] = min(low[node],dfn[nb])
#print node,nb,low[node]
#if node == 4:
#print low[node],visited
#if flag:
# print "node",node, low[node],dfn[node]
if flag and low[node] == dfn[node]:
tmp = []
while trace[-1]!=node:
nt = trace.pop()
tmp.append(nt)
visited[nt] = 2
visited[node] = 2
tmp.append(trace.pop())
res.append(tmp)
stack.pop()
elif flag:
stack.pop()
#print res
if len(res) == 1:
print "No"
else:
print "Yes"
print len(res[0]),n-len(res[0])
print " ".join(map(str,res[0]))
ss = [0]*(n+1)
for i in res[0]:
ss[i] = 1
other = []
for i in range(1,n+1):
if ss[i] == 0:
other.append(i)
print " ".join(map(str,other))
main()
|
1571562300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["Yes\nNo"]
|
287505698b6c850a768ee35d2e37753e
|
NoteYou can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity β he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission β ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket β because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where liββ€βxββ€βri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.In other words, you are given t requests, each of them contains numbers ni,βli,βri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
|
The first line contains the number of universities t, (1ββ€βtββ€β1000) Each of the next t lines contain three space-separated integers: ni,βli,βri (1ββ€βni,βli,βriββ€β109;Β liββ€βri).
|
standard output
|
standard input
|
PyPy 3
|
Python
| null |
train_035.jsonl
|
3088a8da3a98213f12798655cc3e9997
|
256 megabytes
|
["2\n5 2 3\n6 4 5"]
|
PASSED
|
def possible(numbers):
if int(numbers[0])//int(numbers[1])!=0 and int(numbers[0])%int(numbers[1])//(int(numbers[0])//int(numbers[1]))<=int(numbers[2])-int(numbers[1]) and int(numbers[0])%int(numbers[1])%int(numbers[0])//int(numbers[1])+int(numbers[0])%int(numbers[1])%(int(numbers[0])//int(numbers[1]))<=(int(numbers[2])-int(numbers[1]))*(int(numbers[0])//int(numbers[1])-int(numbers[0])//int(numbers[2])):
return 'Yes'
return 'No'
for i in range(0,int(input())):
numbers=input().split(' ')
if i == -1 and int(numbers[0])!=2 and int(numbers[0])!=912247143:
print(numbers)
print(possible(numbers))
|
1393428600
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3\n1 2\n1 3\n3 2", "3\n1 3\n1 4\n2 3", "-1"]
|
73668a75036dce819ff27c316de378af
| null |
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
|
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0ββ€βmββ€β106) β the number of edges in the found graph. In each of the next m lines print two space-separated integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
|
The first line contains two space-separated integers n and k (1ββ€βkβ<βnββ€β105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph. The second line contains space-separated integers d[1],βd[2],β...,βd[n] (0ββ€βd[i]β<βn). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800
|
train_007.jsonl
|
a50486b8dd4e04bf6e00d2a7d9529bfc
|
256 megabytes
|
["3 2\n0 1 1", "4 2\n2 0 1 3", "3 1\n0 0 0"]
|
PASSED
|
n, k = map(int, raw_input().split())
numbers = map(int, raw_input().split())
indices = range(1, len(numbers) + 1)
pairs = zip(numbers, indices)
pairs = sorted(pairs)
edges = []
valid = True
if pairs[0][0] != 0:
valid = False
else:
parent = 0
remaining_edges = k
for i in range(1, len(pairs)):
while (pairs[parent][0] != pairs[i][0]-1 or not remaining_edges)and parent < i:
parent += 1
remaining_edges = k - 1
if parent >= i or remaining_edges == 0:
valid = False
break
edges.append((pairs[parent][1], pairs[i][1]))
remaining_edges -= 1
if not valid:
print -1
else:
print len(edges)
for edge in edges:
print edge[0], edge[1]
|
1395243000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "1\n2", "-1\n-1\n-1"]
|
0c2550b2df0849a62969edf5b73e0ac5
|
Note12β=β4β+β4β+β4β=β4β+β8β=β6β+β6β=β12, but the first splitting has the maximum possible number of summands.8β=β4β+β4, 6 can't be split into several composite summands.1,β2,β3 are less than any composite number, so they do not have valid splittings.
|
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
|
For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.
|
The first line contains single integer q (1ββ€βqββ€β105)Β β the number of queries. q lines follow. The (iβ+β1)-th line contains single integer ni (1ββ€βniββ€β109)Β β the i-th query.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300
|
train_001.jsonl
|
6880fca2fa038169c64afba50294461a
|
256 megabytes
|
["1\n12", "2\n6\n8", "3\n1\n2\n3"]
|
PASSED
|
dp = [-1, -1, -1, 1, -1, 1, -1, 2, 1, 2, -1, 3, 2, 3, 2, 4, 3, 4, 3, 5, 4, 5, 4, 6, 5, 6, 5, 7, 6, 7, 6, 8, 7, 8, 7, 9, 8, 9, 8, 10, 9, 10, 9, 11, 10, 11, 10, 12, 11, 12, 11, 13, 12, 13, 12, 14, 13, 14, 13, 15, 14, 15, 14, 16, 15, 16, 15, 17, 16, 17, 16, 18, 17, 18, 17, 19, 18, 19, 18, 20, 19, 20, 19, 21, 20, 21, 20, 22, 21, 22, 21, 23, 22, 23, 22, 24, 23, 24, 23]
def main():
n = int(input())
if n < len(dp):
print(dp[n - 1])
return
res = (n - len(dp)) // 4
n -= ((n - len(dp)) // 4) * 4
while n >= len(dp):
n -= 4
res += 1
res += dp[n - 1]
print(res)
return
q = int(input())
for i in range(q):
main()
|
1508054700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1\n3\n7"]
|
644b8f95b66b7e4cb39af552ec518b3f
|
NoteThe binary representations of numbers from 1 to 10 are listed below:110β=β12210β=β102310β=β112410β=β1002510β=β1012610β=β1102710β=β1112810β=β10002910β=β100121010β=β10102
|
Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that lββ€βxββ€βr, and is maximum possible. If there are multiple such numbers find the smallest of them.
|
For each query print the answer in a separate line.
|
The first line contains integer nΒ β the number of queries (1ββ€βnββ€β10000). Each of the following n lines contain two integers li,βriΒ β the arguments for the corresponding query (0ββ€βliββ€βriββ€β1018).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,700
|
train_008.jsonl
|
7771eebb89c8ec80001d90e1da43c51e
|
256 megabytes
|
["3\n1 2\n2 4\n1 10"]
|
PASSED
|
import math
import bisect
dict = {}
#print dir(bisect)
List = []
def binary_search(l,r,a):
mid = (l+r)/2
if(l==r):
return mid+1
if r-l == 1 and List[r]<=a:
return r+1
if r-l == 1 and List[r]>a:
return l+1
if List[mid]==a:
return mid+1
if List[mid]>a:
return binary_search(l,mid-1,a)
if List[mid]<a:
return binary_search(mid,r,a)
def popcount1(a,b):
if(dict.has_key(a) > 0):
k1 = dict[a]
elif a <= 0:
k1 = 0
else:
k1 = bisect.bisect_right(List,a,0,len(List))
dict[a] = k1
if(dict.has_key(b) > 0):
k2 = dict[b]
elif b <= 0:
k2 = 0
else:
k2 = bisect.bisect_right(List,b,0,len(List))
dict[b] = k2
if(k1 == k2 and k1 == 0):
return 0
sum = List[k1-1]
#print k1,k2
if(k1 == k2):
return sum+(popcount1((a-sum),(b-sum)))
elif(k1!=k2 and b == List[k2]-1):
return b
else:
return List[k2-1]-1
T = input()
s = 1
while s<=pow(2,62):
List.append(s)
s*=2
#print List[len(List)-1]
while (T!=0):
T-=1
a,b=map(long,raw_input().split())
print long(popcount1(a,b))
|
1415205000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nNO"]
|
21a1aada3570f42093c7ed4e06f0766d
|
NoteThis is the graph of sample: Weight of minimum spanning tree on this graph is 6.MST with edges (1,β3,β4,β6), contains all of edges from the first query, so answer on the first query is "YES".Edges from the second query form a cycle of length 3, so there is no spanning tree including these three edges. Thus, answer is "NO".
|
For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible.You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph G, and you should determine whether there is a MST containing all these edges or not.
|
For each query you should print "YES" (without quotes) if there's a MST containing these edges and "NO" (of course without quotes again) otherwise.
|
The first line contains two integers n, m (2βββ€βn,βmβββ€β5Β·105, nβ-β1ββ€βm)Β β the number of vertices and edges in the graph and the number of queries. The i-th of the next m lines contains three integers ui, vi, wi (uiββ βvi, 1ββ€βwiββ€β5Β·105)Β β the endpoints and weight of the i-th edge. There can be more than one edges between two vertices. It's guaranteed that the given graph is connected. The next line contains a single integer q (1ββ€βqββ€β5Β·105)Β β the number of queries. q lines follow, the i-th of them contains the i-th query. It starts with an integer ki (1ββ€βkiββ€βnβ-β1)Β β the size of edges subset and continues with ki distinct space-separated integers from 1 to mΒ β the indices of the edges. It is guaranteed that the sum of ki for 1ββ€βiββ€βq does not exceed 5Β·105.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,300
|
train_080.jsonl
|
5891d9cd989c3433ac7c3fea851489c9
|
256 megabytes
|
["5 7\n1 2 2\n1 3 2\n2 3 1\n2 4 1\n3 4 1\n3 5 2\n4 5 2\n4\n2 3 4\n3 3 4 5\n2 1 7\n2 1 2"]
|
PASSED
|
import sys, collections
range = xrange
input = raw_input
class DisjointSetUnion0:
def __init__(self, n):
self.data = [-1] * n
def __getitem__(self, a):
acopy = a
while self.data[a] >= 0:
a = self.data[a]
while acopy != a:
self.data[acopy], acopy = a, self.data[acopy]
return a
def __call__(self, a, b):
a, b = self[a], self[b]
if a != b:
if self.data[a] > self.data[b]:
a, b = b, a
self.data[a] += self.data[b]
self.data[b] = a
class DisjointSetUnion1:
def __init__(self):
self.data = collections.defaultdict(lambda: -1)
def __getitem__(self, a):
acopy = a
while self.data[a] >= 0:
a = self.data[a]
while acopy != a:
self.data[acopy], acopy = a, self.data[acopy]
return a
def __call__(self, a, b):
a, b = self[a], self[b]
if a != b:
if self.data[a] > self.data[b]:
a, b = b, a
self.data[a] += self.data[b]
self.data[b] = a
return True
return False
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
V = []
W = []
for _ in range(m):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
w = inp[ii]; ii += 1
eind = len(V)
V.append(v)
V.append(u)
W.append(w)
q = inp[ii]; ii += 1
ans = [1]*q
queries = collections.defaultdict(list)
for qind in range(q):
k = inp[ii]; ii += 1
E = [eind - 1 << 1 for eind in inp[ii: ii + k]]; ii += k
found = set()
for eind in E:
w = W[eind >> 1]
if w not in found:
found.add(w)
queries[w].append([qind])
queries[w][-1].append(eind)
buckets = collections.defaultdict(list)
for eind in range(0, 2 * m, 2):
buckets[W[eind >> 1]].append(eind)
dsu0 = DisjointSetUnion0(n)
for w in sorted(buckets):
for query in queries[w]:
dsu1 = DisjointSetUnion1()
qind = query[0]
for eind in query[1:]:
v = dsu0[V[eind]]
u = dsu0[V[eind ^ 1]]
if not dsu1(u,v):
ans[qind] = 0
break
for eind in buckets[w]:
dsu0(V[eind], V[eind ^ 1])
print '\n'.join('YES' if a else 'NO' for a in ans)
|
1510929300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES\nYES\nNO"]
|
b34f29e6fb586c22fa1b9e559c5a6c50
|
NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is "NO".
|
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it! Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absentΒ β cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\frac{n \cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?
|
For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.
|
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$)Β β number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β volumes of cubes. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 900
|
train_012.jsonl
|
88967499f10d35b541afb94078133525
|
256 megabytes
|
["3\n5\n5 3 2 1 4\n6\n2 2 2 2 2 2\n2\n2 1"]
|
PASSED
|
t = int(input())
for i in range(t):
n = int(input())
lst = list(map(int, input().split()))
flag = 0
for i in range(n-1):
if lst[i] <= lst[i + 1]:
flag = 1
break
if flag == 1:
print("YES")
else:
print("NO")
|
1600958100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["block 192.168.0.1; #replica\nproxy 192.168.0.2; #main", "redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server"]
|
94501cd676a9214a59943b8ddd1dd31b
| null |
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.
|
Print m lines, the commands in the configuration file after Dustin did his task.
|
The first line of input contains two integers n and m (1ββ€βn,βmββ€β1000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1ββ€β|name|ββ€β10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1ββ€β|command|ββ€β10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.
|
standard output
|
standard input
|
Python 2
|
Python
| 900
|
train_013.jsonl
|
1ba0694dd7087e2d6ff52d9982d7ffb3
|
256 megabytes
|
["2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;", "3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;"]
|
PASSED
|
n,m = [int(x) for x in raw_input().split()]
arr = {}
for i in range(n):
a,b = [x for x in raw_input().split()]
b += ";"
arr[b] = a
for i in range(m):
a,b = [x for x in raw_input().split()]
c = "#"
c += arr[b]
print a,b,c
|
1517236500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["0\n1\n2\n2 \n2 3"]
|
3b8969f7f2051d559a1e375ce8275c73
|
NoteLet's describe what happens in the third test case: $$$x_1 = 2$$$: we choose all positions that are not divisible by $$$2$$$ and replace them, i.Β e. bzyx $$$\rightarrow$$$ bzbx; $$$x_2 = 3$$$: we choose all positions that are not divisible by $$$3$$$ and replace them, i.Β e. bzbx $$$\rightarrow$$$ bbbb.
|
Theofanis has a string $$$s_1 s_2 \dots s_n$$$ and a character $$$c$$$. He wants to make all characters of the string equal to $$$c$$$ using the minimum number of operations.In one operation he can choose a number $$$x$$$ ($$$1 \le x \le n$$$) and for every position $$$i$$$, where $$$i$$$ is not divisible by $$$x$$$, replace $$$s_i$$$ with $$$c$$$. Find the minimum number of operations required to make all the characters equal to $$$c$$$ and the $$$x$$$-s that he should use in his operations.
|
For each test case, firstly print one integer $$$m$$$Β β the minimum number of operations required to make all the characters equal to $$$c$$$. Next, print $$$m$$$ integers $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_j \le n$$$)Β β the $$$x$$$-s that should be used in the order they are given. It can be proved that under given constraints, an answer always exists. If there are multiple answers, print any.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$) and a lowercase Latin letter $$$c$$$Β β the length of the string $$$s$$$ and the character the resulting string should consist of. The second line of each test case contains a string $$$s$$$ of lowercase Latin lettersΒ β the initial string. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200
|
train_097.jsonl
|
67ea6d074f1a575ae12073af843c865c
|
256 megabytes
|
["3\n4 a\naaaa\n4 a\nbaaa\n4 b\nbzyx"]
|
PASSED
|
t = int(input())
while t:
n,c = input().split()
s = str(input())
copy = str(c)
copy*=(int(n))
if s == copy:
print(0)
else:
n = int(n)
f = False
for i in range(1,n+1):
if s[i-1] == str(c) and i*2 > n:
f = True
break
if f:
print(1)
print(i)
else:
print(2)
print(n-1,n)
t -= 1
|
1633705500
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds
|
["1", "9"]
|
422fda519243f084f82fac5488ee4faa
|
NoteIn the first test case, we can obtain $$$4$$$ bracket sequences by replacing all characters '?' with either '(' or ')': "((". Its depth is $$$0$$$; "))". Its depth is $$$0$$$; ")(". Its depth is $$$0$$$; "()". Its depth is $$$1$$$. So, the answer is $$$1 = 0 + 0 + 0 + 1$$$.In the second test case, we can obtain $$$4$$$ bracket sequences by replacing all characters '?' with either '(' or ')': "(((())". Its depth is $$$2$$$; "()()))". Its depth is $$$2$$$; "((()))". Its depth is $$$3$$$; "()(())". Its depth is $$$2$$$. So, the answer is $$$9 = 2 + 2 + 3 + 2$$$.
|
This is the hard version of this problem. The only difference is the limit of $$$n$$$ - the length of the input string. In this version, $$$1 \leq n \leq 10^6$$$.Let's define a correct bracket sequence and its depth as follow: An empty string is a correct bracket sequence with depth $$$0$$$. If "s" is a correct bracket sequence with depth $$$d$$$ then "(s)" is a correct bracket sequence with depth $$$d + 1$$$. If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of $$$s$$$ and $$$t$$$. For a (not necessarily correct) bracket sequence $$$s$$$, we define its depth as the maximum depth of any correct bracket sequence induced by removing some characters from $$$s$$$ (possibly zero). For example: the bracket sequence $$$s = $$$"())(())" has depth $$$2$$$, because by removing the third character we obtain a correct bracket sequence "()(())" with depth $$$2$$$.Given a string $$$a$$$ consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in $$$a$$$ by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo $$$998244353$$$.Hacks in this problem can be done only if easy and hard versions of this problem was solved.
|
Print the answer modulo $$$998244353$$$ in a single line.
|
The only line contains a non-empty string consist of only '(', ')' and '?'. The length of the string is at most $$$10^6$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,900
|
train_043.jsonl
|
61a766ba24d96451eb38ef7ceb8634b6
|
256 megabytes
|
["??", "(?(?))"]
|
PASSED
|
import sys
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod
MOD = 998244353
half = pow(2, MOD - 2, MOD)
S = input()
n = len(S)
A = []
for c in S:
if c == '?':
A.append(0)
elif c == '(':
A.append(1)
else:
A.append(2)
big = 10**6 + 10
modinv = [1]*big
for i in range(2,big):
modinv[i] = mulmod(-(MOD//i), modinv[MOD%i], MOD)
fac = [1]
for i in range(1,big):
fac.append(mulmod(fac[-1], i, MOD))
invfac = [1]
for i in range(1,big):
invfac.append(mulmod(invfac[-1], modinv[i], MOD))
def choose(n,k):
if k > n:
return 0
return mulmod(mulmod(fac[n], invfac[k], MOD), invfac[n-k], MOD)
count = sum(1 for a in A if a == 0)
cumsum0 = [0]
for k in range(n + 1):
cumsum0.append((cumsum0[-1] + choose(count - 1, k)) % MOD)
cumsum1 = [0]
for k in range(n + 1):
cumsum1.append((cumsum1[-1] + choose(count, k)) % MOD)
ans = 0
m = sum(1 for a in A if a != 1)
for i in range(n):
m -= A[i] != 1
if A[i] == 0 and m >= 0:
ans = (ans + cumsum0[m]) % MOD
elif A[i] == 1 and m >= 0:
ans = (ans + cumsum1[m]) % MOD
m -= A[i] == 1
print ans
|
1575556500
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["5\n2\n3\n5\n1\n0\n3\n5\n2\n0"]
|
7374246c559fb7b507b0edeea6ed0c5d
|
NoteIn the first test case, the program can run $$$5$$$ times as follows: $$$\text{iloveslim} \to \text{ilovslim} \to \text{iloslim} \to \text{ilslim} \to \text{islim} \to \text{slim}$$$In the second test case, the program can run $$$2$$$ times as follows: $$$\text{joobeel} \to \text{oel} \to \text{el}$$$In the third test case, the program can run $$$3$$$ times as follows: $$$\text{basiozi} \to \text{bioi} \to \text{ii} \to \text{i}$$$.In the fourth test case, the program can run $$$5$$$ times as follows: $$$\text{khater} \to \text{khatr} \to \text{khar} \to \text{khr} \to \text{kr} \to \text{r}$$$In the fifth test case, the program can run only once as follows: $$$\text{abobeih} \to \text{h}$$$In the sixth test case, the program cannot run as none of the characters in the password is a special character.
|
Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string $$$s$$$ of length $$$n$$$. He also knows that there are $$$k$$$ special letters of the alphabet: $$$c_1,c_2,\ldots, c_k$$$.Hosssam made a program that can do the following. The program considers the current password $$$s$$$ of some length $$$m$$$. Then it finds all positions $$$i$$$ ($$$1\le i<m$$$) such that $$$s_{i+1}$$$ is one of the $$$k$$$ special letters. Then it deletes all of those positions from the password $$$s$$$ even if $$$s_{i}$$$ is a special character. If there are no positions to delete, then the program displays an error message which has a very loud sound. For example, suppose the string $$$s$$$ is "abcdef" and the special characters are 'b' and 'd'. If he runs the program once, the positions $$$1$$$ and $$$3$$$ will be deleted as they come before special characters, so the password becomes "bdef". If he runs the program again, it deletes position $$$1$$$, and the password becomes "def". If he is wise, he won't run it a third time.Hosssam wants to know how many times he can run the program on Hemose's laptop without waking him up from the sound of the error message. Can you help him?
|
For each test case, print the maximum number of times Hosssam can run the program without displaying the error message, on a new line.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) β the initial length of the password. The next line contains a string $$$s$$$ consisting of $$$n$$$ lowercase English letters β the initial password. The next line contains an integer $$$k$$$ ($$$1 \le k \le 26$$$), followed by $$$k$$$ distinct lowercase letters $$$c_1,c_2,\ldots,c_k$$$ β the special letters. 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,100
|
train_100.jsonl
|
021e8104e716bb52211ca06d687161a6
|
256 megabytes
|
["10\n\n9\n\niloveslim\n\n1 s\n\n7\n\njoobeel\n\n2 o e\n\n7\n\nbasiozi\n\n2 s i\n\n6\n\nkhater\n\n1 r\n\n7\n\nabobeih\n\n6 a b e h i o\n\n5\n\nzondl\n\n5 a b c e f\n\n6\n\nshoman\n\n2 a h\n\n7\n\nshetwey\n\n2 h y\n\n5\n\nsamez\n\n1 m\n\n6\n\nmouraz\n\n1 m"]
|
PASSED
|
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
s = sys.stdin.readline().strip().lower()
a = sys.stdin.readline().strip().lower().split()
k = int(a[0])
d = [0]*256
for i in range(1, k+1):
d[ord(a[i])] = 1
parts = 0
maxlen = 0
curlen = 0
grps = []
for i in range(len(s)):
v = d[ord(s[i])]
if i == 0:
v = 0
if v > 0:
if curlen > 0:
parts += 1
if curlen > maxlen:
maxlen = curlen
grps.append(curlen)
curlen = 0
else:
curlen += 1
# print(grps)
cnt = 0
for i in range(len(grps)):
if i > 0:
if grps[i] == maxlen:
cnt += 1
res = 0
if parts == 1:
res = max(maxlen,1)
elif parts > 1:
if cnt >= 1:
res = maxlen + 1
else:
res = max(maxlen,1)
print(res)
|
1651847700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2\n4\n0\n0"]
|
f8a8bda80a75ed430465605deff249ca
|
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
|
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
|
For each test case, output one integerΒ β the smallest possible length of the segment which has at least one common point with all given segments.
|
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$)Β β the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$)Β β the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100
|
train_001.jsonl
|
569a676a8f1da2804903df120f97ed87
|
256 megabytes
|
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
|
PASSED
|
t = int(input())
aa = []
bb = []
for i in range(t):
n = int(input())
max = 0
min = 10**10
for j in range(n):
d = list(map(int, input().split(' ')))
if d[1] < min:
min = d[1]
if d[0] > max:
max = d[0]
print(max-min if max-min >= 0 else 0)
|
1574582700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
|
6059cfa13594d47b3e145d7c26f1b0b3
|
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
|
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
|
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any.
|
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$)Β β the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500
|
train_014.jsonl
|
8d64211582a3c498f2d4a6e340d85d7c
|
256 megabytes
|
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
|
PASSED
|
n = int(input())
a = [input() for _ in range(n)]
ans = []
ch = [False] * n
cur = -1
for i in a:
cur += 1
if '.' in i:
curi = i.split('.')
if curi[1].count("0") == len(curi[1]):
ans.append(int(curi[0]))
continue
ch[cur] = True
if curi[0][0] == '-':
ans.append(int(curi[0]) - 1)
else:
ans.append(int(curi[0]))
else:
ans.append(int(i))
curs = sum(ans)
for i in range(n):
if curs < 0 and ch[i]:
curs += 1
ans[i] += 1
print(*ans, sep='\n')
|
1561710000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["1 3\n2 2 3\n0\n3 1 2 4\n1 2"]
|
ff84bc8e8e01c82e1ecaa2a39a7f8dc6
|
NoteGraph of Andarz Gu in the sample case is as follows (ID of people in each city are written next to them):
|
Recently Duff has been a soldier in the army. Malek is her commander.Their country, Andarz Gu has n cities (numbered from 1 to n) and nβ-β1 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.There are also m people living in Andarz Gu (numbered from 1 to m). Each person has and ID number. ID number of iβ-βth person is i and he/she lives in city number ci. Note that there may be more than one person in a city, also there may be no people living in the city. Malek loves to order. That's why he asks Duff to answer to q queries. In each query, he gives her numbers v,βu and a.To answer a query:Assume there are x people living in the cities lying on the path from city v to city u. Assume these people's IDs are p1,βp2,β...,βpx in increasing order. If kβ=βmin(x,βa), then Duff should tell Malek numbers k,βp1,βp2,β...,βpk in this order. In the other words, Malek wants to know a minimums on that path (or less, if there are less than a people).Duff is very busy at the moment, so she asked you to help her and answer the queries.
|
For each query, print numbers k,βp1,βp2,β...,βpk separated by spaces in one line.
|
The first line of input contains three integers, n,βm and q (1ββ€βn,βm,βqββ€β105). The next nβ-β1 lines contain the roads. Each line contains two integers v and u, endpoints of a road (1ββ€βv,βuββ€βn, vββ βu). Next line contains m integers c1,βc2,β...,βcm separated by spaces (1ββ€βciββ€βn for each 1ββ€βiββ€βm). Next q lines contain the queries. Each of them contains three integers, v,βu and a (1ββ€βv,βuββ€βn and 1ββ€βaββ€β10).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200
|
train_039.jsonl
|
10e269a3dc6c3dd54a658cb451fd2f09
|
512 megabytes
|
["5 4 5\n1 3\n1 2\n1 4\n4 5\n2 1 4 3\n4 5 6\n1 5 2\n5 5 10\n2 3 3\n5 3 1"]
|
PASSED
|
import sys
range = xrange
input = raw_input
class Hld:
def __init__(self, graph, data, f = min):
root = 0
n = len(graph) + 1
self.data = data
self.f = f
bfs = [root]
self.depth = [-1]*n
self.depth[root] = 0
self.P = [-1]*n
for node in bfs:
for nei in graph[node]:
if self.depth[nei] == -1:
bfs.append(nei)
self.P[nei] = node
self.depth[nei] = 1 + self.depth[node]
fam_size = [1]*n
preffered_child = list(range(n))
for node in reversed(bfs):
p = self.P[node]
if fam_size[preffered_child[p]] <= fam_size[node]:
preffered_child[p] = node
fam_size[p] += fam_size[node]
fam_size[root] //= 2
self.hld_P = list(range(n))
self.prefix_values = [0]*n
values = [[] for _ in range(n)]
for node in bfs:
self.hld_P[preffered_child[node]] = self.hld_P[node]
values[self.hld_P[node]].append(data[node])
self.prefix_values[node] = data[node] if node == self.hld_P[node] else f(self.prefix_values[self.P[node]], data[node])
self.seg_values = [self.seg_builder(value) for value in values]
def seg_builder(self, data):
self.f = f
ans = [0]*len(data)
ans += data
for i in reversed(range(1, len(data))):
ans[i] = self.f(ans[2 * i], ans[2 * i + 1])
return ans
def seg_query(self, data, l, r):
l += len(data) >> 1
r += len(data) >> 1
val = data[l]
l += 1
while l < r:
if l & 1:
val = self.f(val, data[l])
l += 1
if r & 1:
val = self.f(val, data[r - 1])
l >>= 1
r >>= 1
return val
def __call__(self, u,v):
if u == v:
return self.data[u]
if self.depth[u] < self.depth[v]:
u,v = v,u
val = self.data[u]
u = self.P[u]
uhld = self.hld_P[u]
vhld = self.hld_P[v]
while uhld != vhld:
if self.depth[uhld] >= self.depth[vhld]:
val = self.f(self.prefix_values[u], val)
u = self.P[uhld]
uhld = self.hld_P[u]
else:
val = self.f(self.prefix_values[v], val)
v = self.P[vhld]
vhld = self.hld_P[v]
if self.depth[u] < self.depth[v]:
u,v = v,u
return self.f(
self.seg_query(self.seg_values[uhld],
self.depth[v] - self.depth[uhld],
self.depth[u] - self.depth[uhld] + 1)
, val)
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
q = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
def f(A, B):
ans = []
A = list(A)
B = list(B)
goal = min(10, len(A) + len(B))
while len(ans) < goal:
if A and (not B or A[-1] < B[-1]):
ans.append(A.pop())
else:
ans.append(B.pop())
ans.reverse()
return ans
C = inp[ii:ii + m]; ii += m
data = [[] for _ in range(n)]
for i in range(m):
if len(data[C[i] - 1]) < 10:
data[C[i] - 1].append(i + 1)
for d in data:
d.reverse()
hld = Hld(coupl, data, f)
out = []
for _ in range(q):
v = inp[ii] - 1; ii += 1
u = inp[ii] - 1; ii += 1
a = inp[ii]; ii += 1
ans = list(hld(v, u))
ans.append(min(len(ans), a))
out.append(' '.join(str(x) for x in ans[-1:~a-1:-1]))
print '\n'.join(out)
|
1444926600
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["6\n216"]
|
33e751f5716cbd666be36ab8f5e3977e
|
NoteIn the first example, all possible passwords are: "3377", "3737", "3773", "7337", "7373", "7733".
|
Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i.βe. these sequences should meet all constraints on Monocarp's password).
|
For each testcase, print one integerΒ β the number of different $$$4$$$-digit sequences that meet the constraints.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$)Β β the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 8$$$)Β β the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots a_n$$$ ($$$0 \le a_i \le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \dots, a_n$$$ are given in ascending order.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800
|
train_088.jsonl
|
4ffe899806a0a1d099398ac023fba041
|
256 megabytes
|
["2\n\n8\n\n0 1 2 4 5 6 8 9\n\n1\n\n8"]
|
PASSED
|
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
alen = 10 - n
ans = int(6 * alen * (alen-1) /2)
print(ans)
|
1666017300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"]
|
6983823efdc512f8759203460cd6bb4c
|
NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$
|
The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$Β β the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints.
|
For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.
|
Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$)Β β the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$)Β β the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$)Β β the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,200
|
train_001.jsonl
|
8d6737fd38ee0c5e10373391e7b6c34c
|
256 megabytes
|
["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"]
|
PASSED
|
def listtostring(L):
t=''
for i in range(0,len(L)):
t+=L[i]
return t
t=int(input())
for i in range(0,t):
n=int(input())
L=list(map(int,input().split()))
if(max(L)==0):
print("a")
for i in range(0,n):
print(chr(97+(i+1)%26))
else:
M=['a' for j in range (1+max(L))]
print(listtostring(M))
k=0
for i in range(0,n):
if(M[L[i]]=='a'):
M[L[i]]='b'
else:
M[L[i]]='a'
print(listtostring(M))
|
1595601300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["baabcaa"]
|
501b60c4dc465b8a60fd567b208ea1e3
|
NoteThe sample is described in problem statement.
|
You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1β=β3,βr1β=β6,βk1β=β1 then the answer is abbacaa. If after that we would process the query l2β=β1,βr2β=β4,βk2β=β2 then we would get the string baabcaa.
|
Print the resulting string s after processing all m queries.
|
The first line of the input contains the string s (1ββ€β|s|ββ€β10β000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1ββ€βmββ€β300)Β β the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1ββ€βliββ€βriββ€β|s|,β1ββ€βkiββ€β1β000β000)Β β the description of the i-th query.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,300
|
train_002.jsonl
|
1ca4a06fc21a96eb6d5ead571587f45e
|
256 megabytes
|
["abacaba\n2\n3 6 1\n1 4 2"]
|
PASSED
|
s = input()
n = int(input())
for i in range(n):
l, r, k = map(int, input().split())
k = k % (r - l + 1)
s = s[:l - 1] + s[r - k:r] + s[l - 1:r - k] + s[r:]
print(s)
|
1447426800
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["2\n1\n0", "1\n1\n1\n1\n2"]
|
e3ec343143419592e73d4be13bcf1cb5
|
NoteLet's consider the first sample. The figure above shows the first sample. Vertex 1 and vertex 2 are connected by color 1 and 2. Vertex 3 and vertex 4 are connected by color 3. Vertex 1 and vertex 4 are not connected by any single color.
|
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers β ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
|
For each query, print the answer in a separate line.
|
The first line of the input contains space-separated two integers β n and m (2ββ€βnββ€β100,β1ββ€βmββ€β100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers β ai, bi (1ββ€βaiβ<βbiββ€βn) and ci (1ββ€βciββ€βm). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if iββ βj, (ai,βbi,βci)ββ β(aj,βbj,βcj). The next line contains a integer β q (1ββ€βqββ€β100), denoting the number of the queries. Then follows q lines, containing space-separated two integers β ui and vi (1ββ€βui,βviββ€βn). It is guaranteed that uiββ βvi.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,400
|
train_010.jsonl
|
d57150c686abc0bf12ea6e99f17ce1a9
|
256 megabytes
|
["4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4"]
|
PASSED
|
n, m = map(int, raw_input().split(' '))
mp = [[set() for j in range(0, n)] for i in range(0, n)]
for i in range(0, m):
a, b, c = map(int, raw_input().split(' '))
a -= 1
b -= 1
if c not in mp[a][b]:
mp[a][b].add(c)
mp[b][a].add(c)
# print mp
for k in range(0, n):
for i in range(0, n):
for j in range(0, n):
mp[i][j] |= (mp[i][k]&mp[k][j])
# print mp
q = int(raw_input())
for i in range(0, q):
u, v = map(int, raw_input().split(' '))
u -= 1
v -= 1
print len(mp[u][v]) if mp[u][v] else 0
|
1421586000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\n4 1 4 4 1\n4 5 5 5 1\n4 5 1 5 4\n1 5 5 5 4\n1 4 4 1 4", "NO", "YES\n4 1\n4 1\n1 4", "YES\n4 4 4 1 4 1 4 1 4\n1 5 5 5 5 5 4 10 1\n4 5 1 4 1 5 4 4 4\n4 5 1 5 5 0 5 5 1\n4 5 1 5 4 5 1 5 4\n4 5 1 5 5 5 4 5 1\n1 5 4 4 1 1 4 5 1\n4 5 5 5 5 5 5 5 4\n1 1 1 1 4 4 1 1 4"]
|
acbcf0b55f204a12d861936c8a60a8b0
|
NoteIt can be shown that no such grid exists for the second test.
|
Alice has an empty grid with $$$n$$$ rows and $$$m$$$ columns. Some of the cells are marked, and no marked cells are adjacent to the edge of the grid. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: every unmarked cell contains either the number $$$1$$$ or $$$4$$$; every marked cell contains the sum of the numbers in all unmarked cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is $$$0$$$); every marked cell contains a multiple of $$$5$$$. Alice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists.
|
Output "'NO" if no suitable grid exists. Otherwise, output "'YES"'. Then output $$$n$$$ lines of $$$m$$$ space-separated integersΒ β the integers in the grid.
|
The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$)Β β the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.' or 'X'Β β an unmarked and a marked cell, respectively. No marked cells are adjacent to the edge of the grid.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,700
|
train_089.jsonl
|
a0bbcec601504cc976dcc1f8718a493f
|
256 megabytes
|
["5 5\n.....\n.XXX.\n.X.X.\n.XXX.\n.....", "5 5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....", "3 2\n..\n..\n..", "9 9\n.........\n.XXXXX.X.\n.X...X...\n.X.XXXXX.\n.X.X.X.X.\n.X.XXX.X.\n.X.....X.\n.XXXXXXX.\n........."]
|
PASSED
|
#!/usr/bin/env python3
import sys
import getpass # not available on codechef
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline # to read input quickly
# import io, os # if all integers, otherwise need to post process
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import scipy
M9 = 10**9 + 7 # 998244353
yes, no = "YES", "NO"
d4 = [(1,0),(0,1),(-1,0),(0,-1)]
# d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
# d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout
MAXINT = sys.maxsize
# if testing locally, print to terminal with a different color
OFFLINE_TEST = getpass.getuser() == "hkmac"
# OFFLINE_TEST = False # codechef does not allow getpass
def log(*args):
if OFFLINE_TEST:
print('\033[36m', *args, '\033[0m', file=sys.stderr)
def solve(*args):
# screen input
if OFFLINE_TEST:
log("----- solving ------")
log(*args)
log("----- ------- ------")
return solve_(*args)
def read_matrix(nrows):
return [list(map(int,input().split())) for _ in range(nrows)]
def read_matrix_and_flatten(nrows):
return [int(x) for i in range(nrows) for x in input().split()]
def read_strings(nrows):
return [input().strip() for _ in range(nrows)]
def minus_one(arr):
return [x-1 for x in arr]
def minus_one_matrix(mrr):
return [[x-1 for x in row] for row in mrr]
# ---------------------------- template ends here ----------------------------
def isBipartite(edges) -> bool:
g = defaultdict(set)
for cur,nex in edges:
g[cur].add(nex)
g[nex].add(cur)
colored = {} # and visited
for start in g:
if start in colored:
continue
stack = [(start,True)]
colored[start] = True
while stack:
cur, color = stack.pop()
for nex in g[cur]:
if nex in colored:
if colored[nex] == color:
return False
continue
stack.append((nex, not color))
colored[nex] = not color
return True, colored
def solve_(arr,h,w):
# your solution here
res = [[1 for _ in row] for row in arr]
edges = []
diamonds = {}
for x,row in enumerate(arr):
for y,cell in enumerate(row):
if cell == 1:
adj = []
for dx,dy in d4:
xx,yy = x+dx, y+dy
if 0 <= xx < h and 0 <= yy < w:
if arr[xx][yy] == 0:
adj.append((xx,yy))
if len(adj)%2 != 0:
return -1
if len(adj) == 2:
edges.append(adj)
if len(adj) == 4:
adj[0],adj[2]=adj[2],adj[0]
diamonds[x,y] = adj
edges.append(adj[:2])
edges.append(adj[2:])
res[x][y] = len(adj)//2 * 5
is_bipartite, colored = isBipartite(edges)
if not is_bipartite:
return -1
#log(edges)
#log(diamonds)
#log(colored)
for (x,y), c in colored.items():
if c:
res[x][y] = 4
else:
res[x][y] = 1
return res
for case_num in [0]: # no loop over test case
# for case_num in range(100): # if the number of test cases is specified
# for case_num in range(int(input())):
# read line as an integer
# k = int(input())
# read line as a string
# srr = input().strip()
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
h,w = list(map(int,input().split()))
# arr = list(map(int,input().split()))
# arr = minus_one(arr)
# read multiple rows
arr = read_strings(h) # and return as a list of str
# mrr = read_matrix(k) # and return as a list of list of int
# arr = read_matrix(k) # and return as a list of list of int
# mrr = minus_one_matrix(mrr)
arr = [[1 if c == "X" else 0 for c in row] for row in arr]
res = solve(arr,h,w) # include input here
# print length if applicable
# print(len(res))
log("res", res)
if res == -1:
print(no)
continue
print(yes)
# parse result
# res = " ".join(str(x) for x in res)
# res = "\n".join(str(x) for x in res)
res = "\n".join(" ".join(str(x) for x in row) for row in res)
# print result
# print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required
print(res)
|
1630852500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["4.500000000\n-12.500000000\n4.000000000\n18.666666667"]
|
159b9c743d6d8792548645b9f7be2753
|
NoteIn the first test case, the array is $$$[3, 1, 2]$$$. These are all the possible ways to split this array: $$$a = [3]$$$, $$$b = [1,2]$$$, so the value of $$$f(a) + f(b) = 3 + 1.5 = 4.5$$$. $$$a = [3,1]$$$, $$$b = [2]$$$, so the value of $$$f(a) + f(b) = 2 + 2 = 4$$$. $$$a = [3,2]$$$, $$$b = [1]$$$, so the value of $$$f(a) + f(b) = 2.5 + 1 = 3.5$$$. Therefore, the maximum possible value $$$4.5$$$.In the second test case, the array is $$$[-7, -6, -6]$$$. These are all the possible ways to split this array: $$$a = [-7]$$$, $$$b = [-6,-6]$$$, so the value of $$$f(a) + f(b) = (-7) + (-6) = -13$$$. $$$a = [-7,-6]$$$, $$$b = [-6]$$$, so the value of $$$f(a) + f(b) = (-6.5) + (-6) = -12.5$$$. Therefore, the maximum possible value $$$-12.5$$$.
|
Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.
|
For each test case, print a single value β the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)β the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800
|
train_095.jsonl
|
b3c025660f3879b5dfa615df43e3e4a3
|
256 megabytes
|
["4\n3\n3 1 2\n3\n-7 -6 -6\n3\n2 2 2\n4\n17 3 5 -3"]
|
PASSED
|
#!/usr/bin/env python3
import io
import os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def printd(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
print(*args, **kwargs)
pass
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
def solve_(iter, cnt):
if cnt == 0:
return
iter()
solve(iter, cnt - 1)
def solve(iter, cnt):
for _ in range(cnt):
iter()
def solve_iter():
n = oint()
a = sorted(rint())
print(a[n-1] + sum(a[:n-1])/(n-1))
solve(solve_iter, oint())
|
1628519700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["11", "13"]
|
48f2c0307a29056a5e0fcc26af98f6dc
|
NoteIn the first test case, we can travel in order $$$1\to 3\to 2\to 1$$$. The flight $$$1\to 3$$$ costs $$$\max(c_1,a_3-a_1)=\max(9,4-1)=9$$$. The flight $$$3\to 2$$$ costs $$$\max(c_3, a_2-a_3)=\max(1,2-4)=1$$$. The flight $$$2\to 1$$$ costs $$$\max(c_2,a_1-a_2)=\max(1,1-2)=1$$$. The total cost is $$$11$$$, and we cannot do better.
|
There are $$$n$$$ cities numbered from $$$1$$$ to $$$n$$$, and city $$$i$$$ has beauty $$$a_i$$$.A salesman wants to start at city $$$1$$$, visit every city exactly once, and return to city $$$1$$$.For all $$$i\ne j$$$, a flight from city $$$i$$$ to city $$$j$$$ costs $$$\max(c_i,a_j-a_i)$$$ dollars, where $$$c_i$$$ is the price floor enforced by city $$$i$$$. Note that there is no absolute value. Find the minimum total cost for the salesman to complete his trip.
|
Output a single integer β the minimum total cost.
|
The first line contains a single integer $$$n$$$ ($$$2\le n\le 10^5$$$) β the number of cities. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$c_i$$$ ($$$0\le a_i,c_i\le 10^9$$$) β the beauty and price floor of the $$$i$$$-th city.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200
|
train_100.jsonl
|
1d71f192585523677bdbb9cf2930c754
|
256 megabytes
|
["3\n1 9\n2 1\n4 1", "6\n4 2\n8 4\n3 0\n2 3\n7 1\n0 1"]
|
PASSED
|
import sys,os,io
input = sys.stdin.readline # for strings
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # for non-strings
PI = 3.141592653589793238460
INF = float('inf')
MOD = 1000000007
# MOD = 998244353
def bin32(num):
return '{0:032b}'.format(num)
def add(x,y):
return (x+y)%MOD
def sub(x,y):
return (x-y+MOD)%MOD
def mul(x,y):
return (x*y)%MOD
def gcd(x,y):
if y == 0:
return x
return gcd(y,x%y)
def lcm(x,y):
return (x*y)//gcd(x,y)
def power(x,y):
res = 1
x%=MOD
while y!=0:
if y&1 :
res = mul(res,x)
y>>=1
x = mul(x,x)
return res
def mod_inv(n):
return power(n,MOD-2)
def prob(p,q):
return mul(p,power(q,MOD-2))
def ii():
return int(input())
def li():
return [int(i) for i in input().split()]
def ls():
return [i for i in input().split()]
import bisect
# ========= SEGMENT TREE ==========
class SegmentTree:
def __init__(self, data, default=INF, func=min):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size + 1
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
n = ii()
store = [0 for i in range(n)]
lol = []
for i in range(n):
store[i] = li()
store[i].append(i)
store.sort()
# print(store)
lol = [store[i][0] for i in range(n)]
dp = [INF for i in range(n)]
total = 0
for i in store:
total+= i[1]
dp[-1] = total
storedp = [INF for i in range(n)]
storedp[-1] = dp[-1] + store[-1][0]
st = SegmentTree(dp)
for i in range(n-2,-1,-1):
a = store[i][0]
c = store[i][1]
node = store[i][2]
# print(lol , a + c)
j = bisect.bisect_right(lol , a + c,i + 1, n)
x = INF
y = INF
if j -1 > i and j-1 < n:
x = st.query(i + 1 , j-1)
if j < n:
y = storedp[j]
# print(j ,x , y)
dp[i] = min(x , y - (a + c))
storedp[i] = dp[i] + store[i][0]
st.__setitem__(i , dp[i])
print(dp[0])
|
1617460500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES", "NO"]
|
46d734178b3acaddf2ee3706f04d603d
| null |
Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.
|
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
|
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800
|
train_014.jsonl
|
f45d591916dee8954a941956a72b17b5
|
256 megabytes
|
["on codeforces \nbeta round is running\n a rustling of keys", "how many gallons\nof edo s rain did you drink\n cuckoo"]
|
PASSED
|
phr1, phr2, phr3 = raw_input(), raw_input(), raw_input()
if sum([phr1.count(k) for k in "aeiou"]) == 5 and sum([phr2.count(k) for k in "aeiou"]) == 7 and sum([phr3.count(k) for k in "aeiou"]) == 5:
print "YES"
else:
print "NO"
|
1303916400
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1", "2", "3"]
|
d436c7a3b7f07c9f026d00bdf677908d
| null |
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x),β...,βyn(x) of the given type as function s(x)β=βy1(x)β+β...β+βyn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
|
Print a single number β the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
|
The first line contains integer n (1ββ€βnββ€β105) β the number of functions. Each of the following n lines contains two space-separated integer numbers ki,βbi (β-β109ββ€βki,βbiββ€β109) that determine the i-th function.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900
|
train_027.jsonl
|
2f125ba738b3b397eea01f4af64e0cef
|
256 megabytes
|
["1\n1 0", "3\n1 0\n0 2\n-1 1", "3\n-2 -4\n1 7\n-5 1"]
|
PASSED
|
from sys import stdin, stdout
from decimal import Decimal
n = int(stdin.readline())
visit = []
for i in range(n):
k, b = map(Decimal, stdin.readline().split())
if not k:
continue
visit.append(-b/k)
visit.sort()
if len(visit):
ans = 1
else:
ans = 0
e = Decimal(10) ** Decimal(-10)
for i in range(1, len(visit)):
if visit[i] != visit[i - 1]:
ans += 1
stdout.write(str(ans))
|
1339342200
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nabb"]
|
591846c93bd221b732c4645e50fae617
| null |
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
|
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
|
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) β the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) β the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) β the permutation $$$q$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100
|
train_002.jsonl
|
87d0231268cbbbdd3643788cae9742d5
|
256 megabytes
|
["3 2\n1 2 3\n1 3 2"]
|
PASSED
|
# adapted some python code from https://www.geeksforgeeks.org/strongly-connected-components/
from collections import defaultdict, deque
#This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = defaultdict(list) # default dictionary to store graph
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self,v,visited):
'generate all nodes in one partition'
answer = []
nodes_to_visit = deque()
nodes_to_visit.append(v)
while len(nodes_to_visit)>0:
v = nodes_to_visit.popleft()
# Mark the current node as visited and print it
visited[v]= True
answer.append(v)
#Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i]==False:
nodes_to_visit.appendleft(i)
return answer
def fillOrder(self,v,visited, stack):
# # Mark the current node as visited
# visited[v]= True
# #Recur for all the vertices adjacent to this vertex
# for i in self.graph[v]:
# if visited[i]==False:
# self.fillOrder(i, visited, stack)
# stack = stack.append(v)
ext_stack = deque()
nodes = deque()
nodes.append(v)
while len(nodes)>0:
v = nodes.popleft()
visited[v]=True
for i in self.graph[v]:
if visited[i] == False:
nodes.appendleft(i)
ext_stack.append(v)
while len(ext_stack)>0:
stack.append(ext_stack.pop())
# Function that returns reverse (or transpose) of this graph
def getTranspose(self):
g = Graph(self.V)
# Recur for all the vertices adjacent to this vertex
for i in self.graph:
for j in self.graph[i]:
g.addEdge(j,i)
return g
# The main function that finds and prints all strongly
# connected components
def printSCCs(self):
'generate all components of graph (generator of lists)'
stack = []
# Mark all the vertices as not visited (For first DFS)
visited =[False]*(self.V)
# Fill vertices in stack according to their finishing
# times
for i in range(self.V):
if visited[i]==False:
self.fillOrder(i, visited, stack)
# Create a reversed graph
gr = self.getTranspose()
# Mark all the vertices as not visited (For second DFS)
visited =[False]*(self.V)
# Now process all vertices in order defined by Stack
while stack:
i = stack.pop()
if visited[i]==False:
yield list(gr.DFSUtil(i, visited))
n,k = map(int, raw_input().split())
p = [x-1 for x in map(int, raw_input().split())]
q = [x-1 for x in map(int, raw_input().split())]
import sys
# Create a graph given in the above diagram
g = Graph(n)
for i in xrange(n-1):
g.addEdge(p[i], p[i+1])
g.addEdge(q[i], q[i+1])
def next_letter(letter):
if letter < 'z':
return chr(ord(letter)+1)
else:
return letter
partition = sorted(map(sorted, list(g.printSCCs())))
inverse = [None] * n
for i,part in enumerate(partition):
for j in part:
inverse[j] = i
if len(partition) < k:
print 'NO'
else:
print 'YES'
answer = [None] * n
# for eveyrthing in the component containing p[0], give it the letter 'a'
letter = 'a'
for u in xrange(n):
if answer[p[u]] is None:
i = inverse[p[u]]
for j in partition[i]:
answer[j] = letter
letter = next_letter(letter)
print ''.join(answer)
|
1567175700
|
[
"strings",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["0", "2\n2 1", "-1"]
|
8e6e50d43ed246234d763271f4ae655a
|
NoteA path is called simple if all huts on it are pairwise different.
|
After Santa Claus and his assistant Elf delivered all the presents and made all the wishes come true, they returned to the North Pole and found out that it is all covered with snow. Both of them were quite tired and they decided only to remove the snow from the roads connecting huts. The North Pole has n huts connected with m roads. One can go along the roads in both directions. The Elf offered to split: Santa Claus will clear up the wide roads and the Elf will tread out the narrow roads. For each road they decided who will clear it: Santa Claus or the Elf. To minimize the efforts they decided to clear the road so as to fulfill both those conditions: between any two huts should exist exactly one simple path along the cleared roads; Santa Claus and the Elf should clear the same number of roads. At this point Santa Claus and his assistant Elf wondered which roads should they clear up?
|
Print "-1" without the quotes if it is impossible to choose the roads that will be cleared by the given rule. Otherwise print in the first line how many roads should be cleared and in the second line print the numbers of those roads (the roads are numbered from 1 in the order of occurrence in the input). It is allowed to print the numbers of the roads in any order. Each number should be printed exactly once. As you print the numbers, separate them with spaces.
|
The first input line contains two positive integers n and m (1ββ€βnββ€β103, 1ββ€βmββ€β105) β the number of huts and the number of roads. Then follow m lines, each of them contains a road description: the numbers of huts it connects β x and y (1ββ€βx,βyββ€βn) and the person responsible for clearing out this road ("S" β for the Elf or "M" for Santa Claus). It is possible to go on each road in both directions. Note that there can be more than one road between two huts and a road can begin and end in the same hut.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,300
|
train_058.jsonl
|
2dc225de4a762f3eb54243fc8a087d55
|
256 megabytes
|
["1 2\n1 1 S\n1 1 M", "3 3\n1 2 S\n1 3 M\n2 3 S", "5 6\n1 1 S\n1 2 M\n1 3 S\n1 4 M\n1 5 M\n2 2 S"]
|
PASSED
|
class DSU(object):
def __init__(self, n):
self.pnt = [-1] * n
def find(self, x):
pnt = self.pnt
if pnt[x] == -1:
return x
pnt[x] = self.find(pnt[x])
return pnt[x]
def join(self, u, v):
pnt = self.pnt
u = self.find(u)
v = self.find(v)
if u != v:
pnt[v] = u
return True
return False
def same(self, u, v):
u = self.find(u)
v = self.find(v)
return u == v
def main():
n, m = map(int, raw_input().split())
e1 = []
e2 = []
for i in range(m):
u, v, t = raw_input().split()
u = int(u) - 1
v = int(v) - 1
if t == 'S':
e1.append((u, v, i + 1))
else:
e2.append((u, v, i + 1))
if n % 2 == 0:
print-1
return
dsu1 = DSU(n)
for u, v, i in e2:
dsu1.join(u, v)
dsu2 = DSU(n)
ans = []
for u, v, i in e1:
if not dsu1.same(u, v):
dsu1.join(u, v)
dsu2.join(u, v)
ans.append(i)
half = (n - 1) / 2
for u, v, i in e1:
if len(ans) < half and dsu2.join(u, v):
ans.append(i)
if len(ans) != half:
print -1
return
for u, v, i in e2:
if len(ans) < half * 2 and dsu2.join(u, v):
ans.append(i)
print len(ans)
for i in ans:
print i,
print
main()
|
1326034800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["YES\nYES\nYES\nNO"]
|
840a4e16454290471faa5a27a3c795d9
|
NoteThe first example is mentioned in the problem statement.In the second example, one can build the tower by flipping the top dice from the previous tower.In the third example, one can use a single die that has $$$5$$$ on top.The fourth example is impossible.
|
Bob is playing with $$$6$$$-sided dice. A net of such standard cube is shown below.He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.For example, the number of visible pips on the tower below is $$$29$$$ β the number visible on the top is $$$1$$$, from the south $$$5$$$ and $$$3$$$, from the west $$$4$$$ and $$$2$$$, from the north $$$2$$$ and $$$4$$$ and from the east $$$3$$$ and $$$5$$$.The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.Bob also has $$$t$$$ favourite integers $$$x_i$$$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $$$x_i$$$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
|
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of favourite integers of Bob. The second line contains $$$t$$$ space-separated integers $$$x_i$$$ ($$$1 \leq x_i \leq 10^{18}$$$)Β β Bob's favourite integers.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,000
|
train_011.jsonl
|
5d0382c76da8c25e3c51261afa016214
|
256 megabytes
|
["4\n29 34 19 38"]
|
PASSED
|
n=int(input())
l=[int(x) for x in input().split()]
for i in l:
if(i>14):
k=i%14
if(k>0 and k<=6):
print("YES")
else:
print("NO")
else:
print("NO")
|
1576595100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["10012\n9"]
|
6db42771fdd582578194c7b69a4ef575
|
NoteThe first testcase of the example is already explained in the statement.In the second testcase, there is only one possible reduction: the first and the second digits.
|
You are given a decimal representation of an integer $$$x$$$ without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in $$$x$$$ and replace them with their sum without leading zeros (if the sum is $$$0$$$, it's represented as a single $$$0$$$).For example, if $$$x = 10057$$$, the possible reductions are: choose the first and the second digits $$$1$$$ and $$$0$$$, replace them with $$$1+0=1$$$; the result is $$$1057$$$; choose the second and the third digits $$$0$$$ and $$$0$$$, replace them with $$$0+0=0$$$; the result is also $$$1057$$$; choose the third and the fourth digits $$$0$$$ and $$$5$$$, replace them with $$$0+5=5$$$; the result is still $$$1057$$$; choose the fourth and the fifth digits $$$5$$$ and $$$7$$$, replace them with $$$5+7=12$$$; the result is $$$10012$$$. What's the largest number that can be obtained?
|
For each testcase, print a single integerΒ β the largest number that can be obtained after the reduction is applied exactly once. The number should not contain leading zeros.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of testcases. Each testcase consists of a single integer $$$x$$$ ($$$10 \le x < 10^{200000}$$$). $$$x$$$ doesn't contain leading zeros. The total length of the decimal representations of $$$x$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100
|
train_087.jsonl
|
b2b7c626f5b48e117c1a75dda2c04e9d
|
256 megabytes
|
["2\n10057\n90"]
|
PASSED
|
'''
# Submitted By Ala3rjMo7@gmail.com
Don't Copy This Code, Try To Solve It By Yourself
'''
# Problem Name = "Minor Reduction"
# Class: B
def Solve():
lst=[]
for t in range(int(input())):
n=input()[::-1]
lst.append(n)
for num in lst:
e=True
for i in range(len(num)-1):
z=int(num[i])+int(num[i+1])
if z > 9:
e=False
break
z=str(z)[::-1]
if e:
num=num[::-1]
print(str(int(num[0])+int(num[1]))+num[2:])
else:
ans=(num[:i]+z+num[i+2:])[::-1]
print(ans)
if __name__ == "__main__":
Solve()
|
1642343700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["1", "40", "54"]
|
3634a3367a1f05d1b3e8e4369e8427fb
|
NoteFor the first example, $$$t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$$$, so $$$\gcd(t)=1$$$.For the second example, $$$t=\{120,40,80,120,240,80\}$$$, and it's not hard to see that $$$\gcd(t)=40$$$.
|
For the multiset of positive integers $$$s=\{s_1,s_2,\dots,s_k\}$$$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $$$s$$$ as follow: $$$\gcd(s)$$$ is the maximum positive integer $$$x$$$, such that all integers in $$$s$$$ are divisible on $$$x$$$. $$$\textrm{lcm}(s)$$$ is the minimum positive integer $$$x$$$, that divisible on all integers from $$$s$$$.For example, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ and $$$\textrm{lcm}(\{4,6\})=12$$$. Note that for any positive integer $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.Orac has a sequence $$$a$$$ with length $$$n$$$. He come up with the multiset $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$$$, and asked you to find the value of $$$\gcd(t)$$$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.
|
Print one integer: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$$$.
|
The first line contains one integer $$$n\ (2\le n\le 100\,000)$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600
|
train_000.jsonl
|
a0c26afcf00079d2cc95ca1f63f598ea
|
256 megabytes
|
["2\n1 1", "4\n10 24 40 80", "10\n540 648 810 648 720 540 594 864 972 648"]
|
PASSED
|
def gcd(a,b):
while b: a,b=b,a%b
return a
def rwh_primes2(n):
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
primes=rwh_primes2(200000)
def f(n,a):
g=reduce(gcd,a); g2=1
for i in xrange(len(a)): a[i]/=g
for p in primes:
min1=min2=1000
for j in a:
u=1; t=0; up=p
while j%up==0: u,up=up,up*p; t+=1
if t<min2:
if t<min1: min1,min2=t,min1
else: min2=t
if min1==min2==0: break
g2*=(p**min2)
return g2*g
n=int(raw_input())
a=map(int,raw_input().split())
print f(n,a)
|
1589286900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["2", "1"]
|
0d212ea4fc9f03fdd682289fca9b517e
|
NoteIn the first test case, there are two good partitions $$$13+5$$$ and $$$1+3+5$$$.In the second test case, there is one good partition $$$1+0+0+0+0$$$.
|
Vasya owns three big integers β $$$a, l, r$$$. Let's define a partition of $$$x$$$ such a sequence of strings $$$s_1, s_2, \dots, s_k$$$ that $$$s_1 + s_2 + \dots + s_k = x$$$, where $$$+$$$ is a concatanation of strings. $$$s_i$$$ is the $$$i$$$-th element of the partition. For example, number $$$12345$$$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of $$$a$$$ beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number $$$a$$$, which has each of $$$s_i$$$ satisfy the condition $$$l \le s_i \le r$$$. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number $$$a$$$ such that they match all the given requirements. The result can be rather big, so print it modulo $$$998244353$$$.
|
Print a single integer β the amount of partitions of number $$$a$$$ such that they match all the given requirements modulo $$$998244353$$$.
|
The first line contains a single integer $$$a~(1 \le a \le 10^{1000000})$$$. The second line contains a single integer $$$l~(0 \le l \le 10^{1000000})$$$. The third line contains a single integer $$$r~(0 \le r \le 10^{1000000})$$$. It is guaranteed that $$$l \le r$$$. It is also guaranteed that numbers $$$a, l, r$$$ contain no leading zeros.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,600
|
train_000.jsonl
|
8fa49b400f05cc20ce305f47184cd1c2
|
256 megabytes
|
["135\n1\n15", "10000\n0\n9"]
|
PASSED
|
def kmp(pat,text,t):
s=pat+"?"+text;
#z[i] es el tamaΓ±o del prefijo mas largo de, formado por una subcadena s[i:...]
z=[0 for i in range(len(s))]
L=0;R=0;n=len(s);
for i in range(1,len(s)):
if i>R:
L=R=i
while R<n and s[R-L]==s[R]:
R+=1
z[i]=R-L
R-=1
elif z[i-L]+i<=R:
z[i]=z[i-L]
else:
L=i
while R<n and s[R-L]==s[R]:
R+=1
z[i]=R-L
R-=1
for i in range(len(pat)+1,len(z)):
dp[t][i-(len(pat)+1)]=z[i]%len(pat)
from sys import stdin
mod=998244353
a=stdin.readline().strip()
l=stdin.readline().strip()
r=stdin.readline().strip()
x=len(l)
y=len(r)
n=len(a)
dp=[[0 for i in range(len(a))]for j in range(2)]
ans=[0 for i in range(len(a)+1)]
ans[-1]=1
kmp(l,a,0)
kmp(r,a,1)
auxl=x-1
auxr=y-1
acum=[0 for i in range(n+2)]
acum[n]=1
for i in range(n-1,-1,-1):
if a[i]=="0":
if l[0]=="0":
ans[i]=ans[i+1]
acum[i]=(acum[i+1]+ans[i])%mod
continue
if auxl>=n:
acum[i]=(acum[i+1]+ans[i])%mod
continue
if auxl!=auxr:
if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]]:
ans[i]=(ans[i]+ans[i+auxl+1])%mod
if (auxr+i)<n and a[dp[1][i]+i]<=r[dp[1][i]]:
ans[i]=(ans[i]+ans[i+auxr+1])%mod
else:
if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]] and a[dp[1][i]+i]<=r[dp[1][i]]:
ans[i]=(ans[i]+ans[i+auxl+1])%mod
lim1=auxl+i+2
lim2=min(auxr+i+1,n+1)
if lim1<lim2:
ans[i]=(ans[i]+acum[lim1]-acum[lim2])%mod
acum[i]=(acum[i+1]+ans[i])%mod
print(ans[0]%mod)
|
1537454700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["13\n0\n68\n0\n74"]
|
7f9853be7ac857bb3c4eb17e554ad3f1
| null |
You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word "hello". Determine how long it will take to print the word $$$s$$$.
|
Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.
|
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)Β β the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboardΒ β a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 800
|
train_108.jsonl
|
836b9894e221f19e58fa751c335a7986
|
256 megabytes
|
["5\nabcdefghijklmnopqrstuvwxyz\nhello\nabcdefghijklmnopqrstuvwxyz\ni\nabcdefghijklmnopqrstuvwxyz\ncodeforces\nqwertyuiopasdfghjklzxcvbnm\nqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\nqwertyuiopasdfghjklzxcvbnm\nabacaba"]
|
PASSED
|
t = int(input())
for j in range(t):
letters = str(input())
s = str(input())
dictiony = {}
calculating = []
word = []
sum = 0
for m in s:
word.append(m)
for i in letters:
dictiony[i] = letters.index(i)
for k in word:
calculating.append(dictiony.get(k))
n = 0
while n != (len(word)-1) and len(s) > 0:
calc = abs(calculating[n + 1] - calculating[n])
sum += calc
n += 1
print(sum)
|
1635863700
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["11\n8\n35\n0\n200\n4"]
|
ef2b90d5b1073430795704a7df748ac3
|
NoteFor the second test case, one can show that the best pair is ("abb","bef"), which has difference equal to $$$8$$$, which can be obtained in the following way: change the first character of the first string to 'b' in one move, change the second character of the second string to 'b' in $$$3$$$ moves and change the third character of the second string to 'b' in $$$4$$$ moves, thus making in total $$$1 + 3 + 4 = 8$$$ moves.For the third test case, there is only one possible pair and it can be shown that the minimum amount of moves necessary to make the strings equal is $$$35$$$.For the fourth test case, there is a pair of strings which is already equal, so the answer is $$$0$$$.
|
You are given $$$n$$$ words of equal length $$$m$$$, consisting of lowercase Latin alphabet letters. The $$$i$$$-th word is denoted $$$s_i$$$.In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example: you can change 'e' to 'd' or to 'f'; 'a' can only be changed to 'b'; 'z' can only be changed to 'y'. The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is $$$1 + 10 + 0 + 0 = 11$$$.Find the minimum difference of $$$s_i$$$ and $$$s_j$$$ such that $$$(i < j)$$$. In other words, find the minimum difference over all possible pairs of the $$$n$$$ words.
|
For each test case, print a single integer β the minimum difference over all possible pairs of the given strings.
|
The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 50$$$, $$$1 \leq m \leq 8$$$) β the number of strings and their length respectively. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$m$$$, consisting of lowercase Latin letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 800
|
train_106.jsonl
|
0e9539720db50e4607ffb1c99d44c206
|
256 megabytes
|
["6\n\n2 4\n\nbest\n\ncost\n\n6 3\n\nabb\n\nzba\n\nbef\n\ncdu\n\nooo\n\nzzz\n\n2 7\n\naaabbbc\n\nbbaezfe\n\n3 2\n\nab\n\nab\n\nab\n\n2 8\n\naaaaaaaa\n\nzzzzzzzz\n\n3 1\n\na\n\nu\n\ny"]
|
PASSED
|
for i in range(int(input())):
n,m=map(int,input().split())
o=[]
ls=[]
for i in range(n):
a=str(input())
s=[]
for j in a:
s+=[ord(j)-96]
o+=[s]
mi = (2**31)-1
for j in range(len(o)):
for k in range(len(o)):
if(j!=k):
pq=[]
for a,b in zip(o[j],o[k]):
pq.append(abs(a-b))
gd=sum(pq)
mi=min(gd,mi)
print(mi)
|
1652193900
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds
|
["2\n1\n2"]
|
aab052bf49da6528641f655342fa4848
| null |
Polycarp was gifted an array $$$a$$$ of length $$$n$$$. Polycarp considers an array beautiful if there exists a number $$$C$$$, such that each number in the array occurs either zero or $$$C$$$ times. Polycarp wants to remove some elements from the array $$$a$$$ to make it beautiful.For example, if $$$n=6$$$ and $$$a = [1, 3, 2, 1, 4, 2]$$$, then the following options are possible to make the array $$$a$$$ array beautiful: Polycarp removes elements at positions $$$2$$$ and $$$5$$$, array $$$a$$$ becomes equal to $$$[1, 2, 1, 2]$$$; Polycarp removes elements at positions $$$1$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[3, 2, 1, 4]$$$; Polycarp removes elements at positions $$$1, 2$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[2, 1, 4]$$$; Help Polycarp determine the minimum number of elements to remove from the array $$$a$$$ to make it beautiful.
|
For each test case, output one integerΒ β the minimum number of elements that Polycarp has to remove from the array $$$a$$$ to make it beautiful.
|
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 consists of one integer $$$n$$$ ($$$1 \le n \le 2 \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 \le a_i \le 10^9$$$)Β β array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500
|
train_098.jsonl
|
82792d9090de522418aae5355a424ac5
|
256 megabytes
|
["3\n6\n1 3 2 1 4 2\n4\n100 100 4 100\n8\n1 2 3 3 3 2 6 6"]
|
PASSED
|
from collections import Counter
for _ in range(int(input())):
n = int(input())
l = list(map(int , input().split()))
occ = []
occ = list( Counter(l).values() )
occ.sort()
size = len(occ)
behind = [0]*size
s = 0
i = 0
while i < size:
cur = occ[i]
add = 0
while i < size and cur == occ[i]:
behind[i] = s
add += occ[i]
i += 1
s += add
sum_ahead = [0]*size
ahead_sum = 0
i = size-1
while i >= 0:
freq = size-1-i
cur_ans = ahead_sum - freq*occ[i]
sum_add = 0
cur = occ[i]
while i>=0 and cur == occ[i]:
sum_add += occ[i]
sum_ahead[i] = cur_ans
i -= 1
ahead_sum += sum_add
ans = float('inf')
for i in range(size):
ans = min( ans , sum_ahead[i] + behind[i])
print(ans)
|
1613486100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["YES", "NO"]
|
16a1c5dbe8549313bae6bca630047502
|
NoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
|
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
|
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
|
The first line contains two integers n and m (1ββ€βn,βmββ€β1000)Β β the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." β an empty cell; "*" β a cell with road works; "S" β the cell where Igor's home is located; "T" β the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,600
|
train_010.jsonl
|
29be230384cdd1cb1f6c32390c7be17a
|
256 megabytes
|
["5 5\n..S..\n****.\nT....\n****.\n.....", "5 5\nS....\n****.\n.....\n.****\n..T.."]
|
PASSED
|
n,m=map(int,raw_input().split())
N=range(n)
M=range(m)
D=(0,1,2,3)
g=[raw_input() for _ in range(n)]
I=1<<20
v=[[[I]*4 for _ in M] for _ in N]
q=[]
for i in N:
for j in M:
if 'S'==g[i][j]:
for d in D:
q+=[(i,j,d)]
v[i][j][d]=0
if 'T'==g[i][j]:
x,y=i,j
dr=[-1,0,1,0]
dc=[0,1,0,-1]
while q:
i,j,k=q.pop()
for d in D:
a,b=i+dr[d],j+dc[d]
if 0<=a<n and 0<=b<m and g[a][b]!='*':
l=v[i][j][k]+(k!=d)
if l<v[a][b][d]:
v[a][b][d]=l
if v[a][b][d]<3:
if a==x and b==y:
print 'YES'
exit(0)
else:
q+=[(a,b,d)]
print 'NO'
|
1492965900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nNO\nYES\nYES\nNO"]
|
a4c82fffb31bc7e42870fd84e043e815
|
NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers.
|
You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer β "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,100
|
train_002.jsonl
|
875e3c1bdfd197a06af7a67499826260
|
256 megabytes
|
["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"]
|
PASSED
|
t=int(input())
for i in range(t):
n,x=[int(y) for y in input().split()]
if (n%2!=x%2 or x**2>n):
print('NO')
else:
print('YES')
|
1584974100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1 3 2", "2 1 3 4", "1"]
|
1cfd0e6504bba7db9ec79e2f243b99b4
|
NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one.
|
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.
|
Print n numbersΒ β the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.
|
The first line contains a single integer nΒ β the number of items (1ββ€βnββ€β105). The second line contains n numbers a1,βa2,β...,βan (1ββ€βaiββ€β105)Β β the initial inventory numbers of the items.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200
|
train_024.jsonl
|
ae2d1466a74a85886d64d0eb045d3ed0
|
256 megabytes
|
["3\n1 3 2", "4\n2 2 3 3", "1\n2"]
|
PASSED
|
n = int(input())
l = list(map(int,input().split()))
d = {}
for i in range(n):
if l[i] in d:
d[l[i]] += 1
else:
d[l[i]] = 1
notpre_ = []
for i in range(1,n+1):
if i in d:
continue
else:
notpre_.append(i)
k = 0
for i in range(len(notpre_)):
for j in range(k,len(l)):
if d[l[j]] > 1 or l[j] > n:
d[l[j]] = d[l[j]] - 1
l[j] = notpre_[i]
d[l[j]] = 1
break
k = j
print(*l)
|
1439224200
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3", "2"]
|
15fa49860e978d3b3fb7a20bf9f8aa86
|
NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.
|
And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0,β0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following: during one run the minibus makes n stops, the i-th stop is in point (xi,β0) coordinates of all the stops are different the minibus drives at a constant speed, equal to vb it can be assumed the passengers get on and off the minibus at a bus stop momentarily Student can get off the minibus only at a bus stop Student will have to get off the minibus at a terminal stop, if he does not get off earlier the University, where the exam will be held, is in point (xu,βyu) Student can run from a bus stop to the University at a constant speed vs as long as needed a distance between two points can be calculated according to the following formula: Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.
|
In the only line output the answer to the problem β index of the optimum bus stop.
|
The first line contains three integer numbers: 2ββ€βnββ€β100, 1ββ€βvb,βvsββ€β1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xnββ€β105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200
|
train_013.jsonl
|
3fa2ad458ee94f7720ea0214ce25d7d9
|
64 megabytes
|
["4 5 2\n0 2 4 6\n4 1", "2 1 1\n0 100000\n100000 100000"]
|
PASSED
|
from math import sqrt
n, v1, v2 = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
x1, y1 = [int(i) for i in input().split()]
minim = x[1] / v1 + sqrt((x1-x[1])**2 + (y1)**2) / v2 #ΠΡΠ΅ΠΌΡ, Π΅ΡΠ»ΠΈ ΡΡΡΠ΄Π΅Π½ Π²ΡΠΉΠ΄Π΅Ρ Π½Π° ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΎΡΡΠ°Π½ΠΎΠ²ΠΊΠ΅ ΠΈ ΠΏΠΎΠ±Π΅ΠΆΠΈΡ (Π΅ΡΠ»ΠΈ ΠΎΠ½ Π±ΡΡΡΡΠ΅Π΅ Π°Π²ΡΠΎΠ±ΡΡΠ°)
res = 2
for i in range(2, n):
t = x[i] / v1 + sqrt((x1-x[i])**2 + (y1)**2) / v2
if t < minim:
minim = t
res = i + 1
elif t == minim and sqrt((x1-x[res-1])**2 + (y1)**2) > sqrt((x1-x[i])**2 + (y1)**2):
res = i+1
print(res)
|
1270983600
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["-1", "4\n1 2\n2 3\n3 4\n4 5"]
|
ed040061e0e9fd41a7cd05bbd8ad32dd
|
NoteIn the first sample case, no graph can fulfill PolandBall's requirements.In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5.
|
PolandBall has an undirected simple graph consisting of n vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red. Colorfulness of the graph is a value min(dr,βdw), where dr is the diameter of the red subgraph and dw is the diameter of white subgraph. The diameter of a graph is a largest value d such that shortest path between some pair of vertices in it is equal to d. If the graph is not connected, we consider its diameter to be -1.PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to k. Can you help him and find any graph which satisfies PolandBall's requests?
|
If it's impossible to find a suitable graph, print -1. Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output mΒ β the number of red edges in your graph. Then, you should output m lines, each containing two integers ai and bi, (1ββ€βai,βbiββ€βn, aiββ βbi) which means that there is an undirected red edge between vertices ai and bi. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order. Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed.
|
The only one input line contains two integers n and k (2ββ€βnββ€β1000, 1ββ€βkββ€β1000), representing graph's size and sought colorfulness.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400
|
train_070.jsonl
|
d8787e711f89604b5400f7bc796d4018
|
256 megabytes
|
["4 1", "5 2"]
|
PASSED
|
n, k = map(int, input().split())
if n < 4:
print(-1)
elif k == 1:
print(-1)
elif k > 3:
print(-1)
elif n == 4 and k == 2:
print(-1)
elif k == 2:
print(n - 1)
for i in range(n - 1):
print(i + 1, i + 2)
elif k == 3:
print(n - 1)
print(1, 2)
print(2, 3)
for i in range(4, n + 1):
print(3, i)
|
1484499900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1 2 5 3 4"]
|
a464c3bd13fe9358c2419b17981522f6
|
NoteHere is the illustration for the first test: Please note that the angle between $$$A_1$$$, $$$A_2$$$ and $$$A_5$$$, centered at $$$A_2$$$, is treated as $$$0$$$ degrees. However, angle between $$$A_1$$$, $$$A_5$$$ and $$$A_2$$$, centered at $$$A_5$$$, is treated as $$$180$$$ degrees.
|
Nezzar loves the game osu!.osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points $$$A,B,C$$$ listed in order, the angle between these three points, centered at $$$B$$$, is strictly less than $$$90$$$ degrees. Points $$$A,B,C$$$ on the left have angle less than $$$90$$$ degrees, so they can be three consecutive points of a nice beatmap; Points $$$A',B',C'$$$ on the right have angle greater or equal to $$$90$$$ degrees, so they cannot be three consecutive points of a nice beatmap. Now Nezzar has a beatmap of $$$n$$$ distinct points $$$A_1,A_2,\ldots,A_n$$$. Nezzar would like to reorder these $$$n$$$ points so that the resulting beatmap is nice.Formally, you are required to find a permutation $$$p_1,p_2,\ldots,p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that beatmap $$$A_{p_1},A_{p_2},\ldots,A_{p_n}$$$ is nice. If it is impossible, you should determine it.
|
If there is no solution, print $$$-1$$$. Otherwise, print $$$n$$$ integers, representing a valid permutation $$$p$$$. If there are multiple possible answers, you can print any.
|
The first line contains a single integer $$$n$$$ ($$$3 \le n \le 5000$$$). Then $$$n$$$ lines follow, $$$i$$$-th of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$) β coordinates of point $$$A_i$$$. It is guaranteed that all points are distinct.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,200
|
train_088.jsonl
|
7a471d68ea06013392c9305361869f9b
|
512 megabytes
|
["5\n0 0\n5 0\n4 2\n2 1\n3 0"]
|
PASSED
|
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def MI(): return map(int, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
inf = 10**16
md = 10**9+7
# md = 998244353
n = II()
xy = LLI(n)
ans = [0, 1]
def vec(i, j):
x0, y0 = xy[i]
x1, y1 = xy[j]
return x1-x0, y1-y0
def less90(i, j, k):
v1 = vec(j, i)
v2 = vec(j, k)
return v1[0]*v2[0]+v1[1]*v2[1] > 0
for i in range(2, n):
ans.append(i)
j = len(ans)
while j > 2:
if less90(ans[j-3], ans[j-2], ans[j-1]): break
ans[j-1], ans[j-2] = ans[j-2], ans[j-1]
j -= 1
print(" ".join(str(i+1) for i in ans))
|
1611844500
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["12\n12\n0"]
|
4af206ae108a483bdb643dc24e4bedba
|
NoteIn the first test case, a possible sequence of moves that uses the minimum number of moves required is shown below. $$$$$$(0,0) \to (1,0) \to (1,1) \to (1, 2) \to (0,2) \to (-1,2) \to (-1,1) \to (-1,0) \to (-1,-1) \to (-1,-2) \to (0,-2) \to (0,-1) \to (0,0)$$$$$$ In the second test case, a possible sequence of moves that uses the minimum number of moves required is shown below. $$$$$$(0,0) \to (0,1) \to (0,2) \to (-1, 2) \to (-2,2) \to (-3,2) \to (-3,1) \to (-3,0) \to (-3,-1) \to (-2,-1) \to (-1,-1) \to (0,-1) \to (0,0)$$$$$$ In the third test case, we can collect all boxes without making any moves.
|
You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).More formally, if you are standing at the point $$$(x, y)$$$, you can: go left, and move to $$$(x - 1, y)$$$, or go right, and move to $$$(x + 1, y)$$$, or go up, and move to $$$(x, y + 1)$$$, or go down, and move to $$$(x, y - 1)$$$. There are $$$n$$$ boxes on this plane. The $$$i$$$-th box has coordinates $$$(x_i,y_i)$$$. It is guaranteed that the boxes are either on the $$$x$$$-axis or the $$$y$$$-axis. That is, either $$$x_i=0$$$ or $$$y_i=0$$$.You can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to start and finish at the point $$$(0,0)$$$.
|
For each test case output a single integer β the minimum number of moves required.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) β the number of boxes. The $$$i$$$-th line of the following $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-100 \le x_i, y_i \le 100$$$) β the coordinate of the $$$i$$$-th box. It is guaranteed that either $$$x_i=0$$$ or $$$y_i=0$$$. Do note that the sum of $$$n$$$ over all test cases is not bounded.
|
standard output
|
standard input
|
Python 2
|
Python
| 800
|
train_088.jsonl
|
55d443b20df5b6227b919f1537897d0b
|
256 megabytes
|
["3\n\n4\n\n0 -2\n\n1 0\n\n-1 0\n\n0 2\n\n3\n\n0 2\n\n-3 0\n\n0 -1\n\n1\n\n0 0"]
|
PASSED
|
import sys
raw_input = iter(sys.stdin.read().splitlines()).next
def solution():
n = int(raw_input())
points = [map(int, raw_input().split()) for _ in xrange(n)]
return 2*((max(max(x for x, _ in points), 0)-min(min(x for x, _ in points), 0))+\
(max(max(y for _, y in points), 0)-min(min(y for _, y in points), 0)))
for case in xrange(int(raw_input())):
print '%s' % solution()
|
1659796500
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["3\n3\n15\n15\n332103349\n99224487"]
|
81efc64bba6d5a667e453260b83640e9
|
NoteIn the first test case, the robot has the opportunity to clean the dirty cell every second. Using the geometric distribution, we can find out that with the success rate of $$$25\%$$$, the expected number of tries to clear the dirty cell is $$$\frac 1 {0.25} = 4$$$. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is $$$3$$$. Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes. In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example. Illustration for the second example. The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result.
|
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell. After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability $$$\frac p {100}$$$ only, and not performed with probability $$$1 - \frac p {100}$$$. The cleaning or not cleaning outcomes are independent each second.Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the expected time for the robot to do its job.It can be shown that the answer can be expressed as an irreducible fraction $$$\frac x y$$$, where $$$x$$$ and $$$y$$$ are integers and $$$y \not \equiv 0 \pmod{10^9 + 7} $$$. Output the integer equal to $$$x \cdot y^{-1} \bmod (10^9 + 7)$$$. In other words, output such an integer $$$a$$$ that $$$0 \le a < 10^9 + 7$$$ and $$$a \cdot y \equiv x \pmod {10^9 + 7}$$$.
|
For each test case, print a single integer β the expected time for the robot to clean the dirty cell, modulo $$$10^9 + 7$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. A test case consists of only one line, containing $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, $$$c_d$$$, and $$$p$$$ ($$$4 \le n \cdot m \le 10^5$$$, $$$n, m \ge 2$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$, $$$1 \le p \le 99$$$)Β β the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300
|
train_106.jsonl
|
c74a21d33761d54b09b23d24f8972064
|
256 megabytes
|
["6\n2 2 1 1 2 1 25\n3 3 1 2 2 2 25\n10 10 1 1 10 10 75\n10 10 10 10 1 1 75\n5 5 1 3 2 2 10\n97 98 3 5 41 43 50"]
|
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())):
# def solve():
# n, m, rb, cb, rd, cd = list(map(int, input().split(' ')))
# dr = dc = 1
# ans = 0
# if rb == rd or cb == cd:
# print(0)
# return
# while rb != rd and cb != cd:
# if dr == dc == 1:
# while rb != rd and cb != cd and 1 <= rb < n and 1 <= cb < m:
# rb += 1
# cb += 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == n:
# dr = -1
# if cb == m:
# dc = -1
# elif dr == 1 and dc == -1:
# while rb != rd and cb != cd and 1 <= rb < n and 1 < cb <= m:
# rb += 1
# cb -= 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == n:
# dr = -1
# if cb == 1:
# dc = 1
# elif dr == -1 and dc == 1:
# while rb != rd and cb != cd and 1 < rb <= n and 1 <= cb < m:
# rb -= 1
# cb += 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == 1:
# dr = 1
# if cb == m:
# dc = -1
# else:
# while rb != rd and cb != cd and 1 < rb <= n and 1 < cb <= m:
# rb -= 1
# cb -= 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == 1:
# dr = 1
# if cb == 1:
# dc = 1
# solve()
# for _ in range(int(input())):
# n = int(input())
# a = [list(map(int, input().split(' '))) for _ in range(n)]
# a.sort(key = lambda x : x[1] - x[0])
# vis = set()
# for i in range(n):
# l, r = a[i]
# for i in range(l, r + 1):
# if i not in vis:
# print(l, r, i)
# vis.add(i)
# print()
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# def check(mid):
# b = a[:]
# for i in range(n - 1, 1, -1):
# if b[i] < mid:
# return False
# r = min(a[i], b[i] - mid)
# r //= 3
# b[i] -= 3 * r
# b[i - 1] += r
# b[i - 2] += 2 * r
# return min(b) >= mid
# l, r = 1, 10 ** 9
# while l <= r:
# mid = (l + r) // 2
# if check(mid):
# l = mid + 1
# else:
# r = mid - 1
# print(r)
mod = 10 ** 9 + 7
for _ in range(int(input())):
def solve():
n, m, rb, cb, rd, cd, p = list(map(int, input().split(' ')))
dr = dc = 1
ans = 0
tmp = []
vis = set()
if rb == n:
dr = -1
if cb == m:
dc = -1
if rb == rd or cb == cd:
tmp.append(0)
vis.add((rb, cb, dr, dc))
ok = True
while ok:
if dr == dc == 1:
while 1 <= rb < n and 1 <= cb < m:
rb += 1
cb += 1
ans += 1
if rb == n:
dr = -1
if cb == m:
dc = -1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
elif dr == 1 and dc == -1:
while 1 <= rb < n and 1 < cb <= m:
rb += 1
cb -= 1
ans += 1
if rb == n:
dr = -1
if cb == 1:
dc = 1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
elif dr == -1 and dc == 1:
while 1 < rb <= n and 1 <= cb < m:
rb -= 1
cb += 1
ans += 1
if rb == 1:
dr = 1
if cb == m:
dc = -1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
else:
while 1 < rb <= n and 1 < cb <= m:
rb -= 1
cb -= 1
ans += 1
if rb == 1:
dr = 1
if cb == 1:
dc = 1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
l = len(tmp)
res = 0
p = p * pow(100, mod - 2, mod) % mod
q = (1 - p) % mod
power = [1] * 100005
for i in range(1, 100005):
power[i] = power[i - 1] * q % mod
for i in range(l):
res += tmp[i] * p * power[i] * pow(1 - power[l], mod - 2, mod) + T * p * power[i + l] * pow((1 - power[l]) * (1 - power[l]) % mod, mod - 2, mod)
res %= mod
# print(tmp,T)
# print(l, T)
# print(tmp[-100:])
print(res % mod)
solve()
|
1640698500
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
3 seconds
|
["5\n1 2 4 11 13", "-1", "-1", "3\n9 11 17", "4\n2 2 2 2"]
|
3a305e2cc38ffd3dc98f21209e83b68d
|
NoteIn the first example, $$$1 \times 2 \times 4 \times 11 \times 13 = 1144$$$, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.In the fourth example, $$$9 \times 11 \times 17 = 1683$$$, which ends with the digit 3. In the fifth example, $$$2 \times 2 \times 2 \times 2 = 16$$$, which ends with the digit 6.
|
Diana loves playing with numbers. She's got $$$n$$$ cards with positive integer numbers $$$a_i$$$ written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers $$$a_i$$$ written on them.Diana is happy when the product of the numbers ends with her favorite digit $$$d$$$. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is $$$d$$$. Please, help her.
|
On the first line, print the number of chosen cards $$$k$$$ ($$$1\le k\le n$$$). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit $$$d$$$, print the single line with $$$-1$$$.
|
The first line contains the integers $$$n$$$ and $$$d$$$ ($$$1\le n\le 10^5$$$, $$$0\le d\le 9$$$). The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1\le a_i\le 1000$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100
|
train_099.jsonl
|
416770810b56faf50d5436b7b20451ec
|
512 megabytes
|
["6 4\n4 11 8 2 1 13", "3 1\n2 4 6", "5 7\n1 3 1 5 3", "6 3\n8 9 4 17 11 5", "5 6\n2 2 2 2 2"]
|
PASSED
|
S_133 = [
(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 1, 0),
(0, 2, 0),
(0, 3, 0),
(1, 0, 0),
(1, 0, 1),
(1, 0, 2),
(1, 0, 3),
(1, 1, 0),
(1, 2, 0),
(1, 3, 0),
]
def pow_mod10(b, p):
if p == 0:
return 1
return pow(b, 4 + p % 4, 10)
def solve(a, d):
nums_by_units = []
for i in range(10):
nums_by_units.append([])
overall_p_mod = 1
odd_prod_mod = 1
for x in a:
r = x % 10
nums_by_units[r].append(x)
overall_p_mod = (overall_p_mod * r) % 10
if r % 2 == 1 and r != 5:
odd_prod_mod = (odd_prod_mod * r) % 10
for i in range(10):
nums_by_units[i].sort()
if d == overall_p_mod:
return a
if d == 0:
if d != overall_p_mod:
return []
return a
if d == 5:
if len(nums_by_units[5]) == 0:
return []
return sum([nums_by_units[r] for r in [1, 3, 5, 7, 9]], [])
if d in [1, 3, 7, 9]:
if all(len(nums_by_units[r]) == 0 for r in [1, 3, 7, 9]):
return []
if d == odd_prod_mod:
return sum([nums_by_units[r] for r in [1, 3, 7, 9]], [])
f = [0] * 10
f[0] = len(nums_by_units[0])
f[5] = len(nums_by_units[5])
if d % 2 == 1:
f[6] = len(nums_by_units[6])
f428_set = [(len(nums_by_units[4]), len(nums_by_units[2]), len(nums_by_units[8]))]
else:
f[6] = 0
f428_set = S_133[:]
f937_set = S_133[:]
min_f = None
min_removed_prod = None
p_mod_init = pow_mod10(6, len(nums_by_units[6]) - f[6])
I = [4, 2, 8, 9, 3, 7]
for f[4], f[2], f[8] in f428_set:
for f[9], f[3], f[7] in f937_set:
if all(f[i] <= len(nums_by_units[i]) for i in I):
p_mod = p_mod_init
removed_prod = 1
for i in I:
if d % 2 == 0 or i % 2 == 1:
p_mod = (p_mod * pow_mod10(i, len(nums_by_units[i]) - f[i])) % 10
for j in range(f[i]):
removed_prod *= nums_by_units[i][j]
if p_mod == d and (min_removed_prod is None or min_removed_prod > removed_prod):
min_removed_prod = removed_prod
min_f = f[:]
if min_removed_prod == 1:
break
if min_f:
return sum([nums_by_units[i][min_f[i]:] for i in range(10)], [])
return []
if __name__ == "__main__":
n, d = map(int, input().split())
a = [*map(int, input().split())]
ans = solve(a, d)
if not ans:
print(-1)
else:
print(len(ans))
print(*ans)
|
1617523500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["1 1 1\n1 1 3\n1 1 4\n2 1 3\n3 1 5\n4 3 12\n1 1 4"]
|
67c748999e681fa6f60165f411e5149d
| null |
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columnsΒ β from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cellΒ β left, right, down or up, respectively.The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move. If the robot moves beyond the edge of the board, it falls and breaks. If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).
|
For each test case, output three integers $$$r$$$, $$$c$$$ and $$$d$$$ ($$$1 \le r \le n$$$; $$$1 \le c \le m$$$; $$$d \ge 0$$$), which denote that the robot should start moving from cell $$$(r, c)$$$ to make the maximum number of moves $$$d$$$. If there are several answers, output any of them.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β the number of test cases in the test. Each test case's description is preceded by a blank line. Next is a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2000$$$; $$$1 \le m \le 2000$$$)Β β the height and width of the board. This line followed by $$$n$$$ lines, the $$$i$$$-th of which describes the $$$i$$$-th line of the board. Each of them is exactly $$$m$$$ letters long and consists of symbols 'L', 'R', 'D' and 'U'. It is guaranteed that the sum of sizes of all boards in the input does not exceed $$$4\cdot10^6$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300
|
train_108.jsonl
|
8123388e4691d6309a183e2ce73440ca
|
256 megabytes
|
["7\n\n1 1\nR\n\n1 3\nRRL\n\n2 2\nDL\nRU\n\n2 2\nUD\nRU\n\n3 2\nDL\nUL\nRU\n\n4 4\nRRRD\nRUUD\nURUD\nULLR\n\n4 4\nDDLU\nRDDU\nUUUU\nRDLD"]
|
PASSED
|
''' F. Robot on the Board 2
https://codeforces.com/contest/1607/problem/F
'''
import io, os, sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str
output = sys.stdout.write
from collections import deque
def solve(R, C, NEXT):
N = R*C
# max_dist[r][c] = max moves if start from cell (r, c)
max_dist = [-1]*N
# visited = [False]*N
# probe from unvisited cell (r, c)
# stop when fall off or revisit a cell
# when stop, update max_dist for all cells visited in this pass
def dfs(x):
chain = deque([x])
while True:
x = NEXT[x]
if x == -1 or max_dist[x] > -1: break
max_dist[x] = 0
chain.append(x)
add = max_dist[x] if x != -1 else 0 # > 0 if revisit a cell from previous passes
cycle_len = 0 # > 0 if revisit a cell from this pass
M = len(chain)
for i, px in enumerate(chain):
if px == x:
cycle_len = M - i
if cycle_len == 0:
max_dist[px] = M - i + add
else:
max_dist[px] = cycle_len
for x in range(N):
if max_dist[x] != -1: continue
dfs(x)
mx_x, mx_d = None, -1
for x in range(N):
if max_dist[x] > mx_d:
mx_x, mx_d = x, max_dist[x]
r, c = divmod(mx_x, C)
return r, c, mx_d
def main():
T = int(input())
for _ in range(T):
_ = input()
R, C = list(map(int, input().split()))
# next move
NEXT = [-1]*(R*C)
nr, nc = -1, -1
for r in range(R):
row = input().decode().strip()
for c, arrow in enumerate(row):
if arrow == 'U': nr, nc = r-1, c
if arrow == 'D': nr, nc = r+1, c
if arrow == 'L': nr, nc = r, c-1
if arrow == 'R': nr, nc = r, c+1
if not (0 <= nr < R and 0 <= nc < C): continue
NEXT[r*C + c] = nr*C + nc
r, c, d = solve(R, C, NEXT)
output(f'{r+1} {c+1} {d}\n')
if __name__ == '__main__':
main()
|
1635863700
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n1 2 4 3", "0\n4 5 6 3 2 1", "3\n2 8 4 6 7 1 9 3 10 5"]
|
0560658d84cbf91c0d86eea4be92a4d9
|
NoteIn the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers β this permutation is lexicographically minimal among all suitable. In the second example Ivan does not need to change anything because his array already is a permutation.
|
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal β compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xiβ<βyi, where i is the first index in which the permutations x and y differ.Determine the array Ivan will obtain after performing all the changes.
|
In the first line print q β the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.
|
The first line contains an single integer n (2ββ€βnββ€β200β000) β the number of elements in Ivan's array. The second line contains a sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€βn) β the description of Ivan's array.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500
|
train_009.jsonl
|
d17bcd0f4836ae66918693521aecd5c4
|
256 megabytes
|
["4\n3 2 2 3", "6\n4 5 6 3 2 1", "10\n6 8 4 6 7 1 6 3 4 5"]
|
PASSED
|
from collections import Counter
def readints():
return [int(item) for item in input().strip().split()]
class Solver:
def main(self):
n = readints()[0]
a = readints()
c = Counter(a)
skipped = set()
to_be_added = sorted(set(range(1, n+1)) - set(c.keys()))
changes = 0
for i in range(n):
if c[a[i]] > 1:
if a[i] < to_be_added[changes] and a[i] not in skipped:
skipped.add(a[i])
else:
c[a[i]] -= 1
a[i] = to_be_added[changes]
changes += 1
print(changes)
print(' '.join(map(str, a)))
Solver().main()
|
1506335700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5", "3", "5"]
|
0efd4b05b3e2e3bc80c93d37508a5197
|
NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.
|
You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it: Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.
|
Print a single integerΒ β the maximum possible median after the operations.
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$)Β β the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,400
|
train_008.jsonl
|
c8e44d772bafdb88a779bd2e6b7c7eb9
|
256 megabytes
|
["3 2\n1 3 5", "5 5\n1 2 1 1 1", "7 7\n4 1 2 4 3 4 4"]
|
PASSED
|
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
from sys import stdin, stdout
#N = int(input())
#s = input()
N,K = [int(x) for x in stdin.readline().split()]
arr = [int(x) for x in stdin.readline().split()]
arr.sort()
half = N//2
s = sum(arr[half:])
bound = s + K
res = 0
for i in range(N-1,(N//2)-1,-1):
if bound//(i-half+1)>arr[i]:
res = max(res,bound//(i-half+1))
if i!=N-1 and res>arr[i+1]:
res = arr[i+1]
break
else:
bound -= arr[i]
print(res)
|
1564936500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 1 4 4\n-1\n-1\n2 \n-1"]
|
024d7b1d5f7401080560174003456037
|
NoteIn the first test case, player $$$1$$$ and player $$$4$$$ won $$$x$$$ times, player $$$2$$$ and player $$$3$$$ won $$$y$$$ times.In the second, third, and fifth test cases, no valid result exists.
|
There is a badminton championship in which $$$n$$$ players take part. The players are numbered from $$$1$$$ to $$$n$$$. The championship proceeds as follows: player $$$1$$$ and player $$$2$$$ play a game, then the winner and player $$$3$$$ play a game, and then the winner and player $$$4$$$ play a game, and so on. So, $$$n-1$$$ games are played, and the winner of the last game becomes the champion. There are no draws in the games.You want to find out the result of championship. Currently, you only know the following information: Each player has either won $$$x$$$ games or $$$y$$$ games in the championship. Given $$$n$$$, $$$x$$$, and $$$y$$$, find out if there is a result that matches this information.
|
Print the answer for each test case, one per line. If there is no result that matches the given information about $$$n$$$, $$$x$$$, $$$y$$$, print $$$-1$$$. Otherwise, print $$$n-1$$$ space separated integers, where the $$$i$$$-th integer is the player number of the winner of the $$$i$$$-th game. If there are multiple valid results, print any.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$)Β β the number of test cases. The only line of each test case contains three integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$2 \le n \le 10^5$$$, $$$0 \le x, y < n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 900
|
train_104.jsonl
|
e565a45e0b972d86d79c95ef92a1011f
|
256 megabytes
|
["5\n\n5 2 0\n\n8 1 2\n\n3 0 0\n\n2 0 1\n\n6 3 0"]
|
PASSED
|
T = int( input())
for t in range(T) :
n, x, y = map( int, input().split() )
if x == 0 and y == 0 : print(-1)
elif min(x, y) != 0 or max(x, y) >= n : print(-1)
elif (n-1) % max(x, y) and max(x, y) != 1 : print(-1)
else :
j = max(x, y); i = j+2
ans = " 1" * j; ans = ans.lstrip()
while i-1 < n :
ans += (" "+str(i)) * j
i += j
print(ans)
|
1663598100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["Yes", "Yes", "No"]
|
2b346d5a578031de4d19edb4f8f2626c
|
NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$.
|
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$.
|
Output "Yes" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and "No" (without quotes) otherwise. You can print each letter in any case (upper or lower).
|
The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000
|
train_002.jsonl
|
b8374405a2a1df3eb37947d8b85d15ad
|
256 megabytes
|
["a\nu", "abc\nukm", "akm\nua"]
|
PASSED
|
s1 = input()
s2 = input()
c=0
v = ['a','e','i','o','u']
if len(s1)==len(s2):
i=0
while(i<len(s1)):
if (s1[i] in v and s2[i] not in v) or s1[i] not in v and s2[i] in v:
c=1
i+=1
if c==1:
print("No")
else:
print("Yes")
else:
print("No")
|
1549208100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["0 1 2", "0 1 2 3 4", "0 1 2 1 2 3 3"]
|
d465aec304757dff34a770f7877dd940
|
NoteIn the first sample case desired sequences are:1:β1; m1β=β0;2:β1,β2; m2β=β1;3:β1,β3; m3β=β|3β-β1|β=β2.In the second sample case the sequence for any intersection 1β<βi is always 1,βi and miβ=β|1β-βi|.In the third sample caseΒ β consider the following intersection sequences:1:β1; m1β=β0;2:β1,β2; m2β=β|2β-β1|β=β1;3:β1,β4,β3; m3β=β1β+β|4β-β3|β=β2;4:β1,β4; m4β=β1;5:β1,β4,β5; m5β=β1β+β|4β-β5|β=β2;6:β1,β4,β6; m6β=β1β+β|4β-β6|β=β3;7:β1,β4,β5,β7; m7β=β1β+β|4β-β5|β+β1β=β3.
|
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |iβ-βj| units of energy. The total energy spent by Mike to visit a sequence of intersections p1β=β1,βp2,β...,βpk is equal to units of energy.Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (iββ€βaiββ€βaiβ+β1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1β=β1,βp2,β...,βpk then for each 1ββ€βiβ<βk satisfying piβ+β1β=βapi and apiββ βpi Mike will spend only 1 unit of energy instead of |piβ-βpiβ+β1| walking from the intersection pi to intersection piβ+β1. For example, if Mike chooses a sequence p1β=β1,βp2β=βap1,βp3β=βap2,β...,βpkβ=βapkβ-β1, he spends exactly kβ-β1 units of total energy walking around them.Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1ββ€βiββ€βn Mike is interested in finding minimum possible total energy of some sequence p1β=β1,βp2,β...,βpkβ=βi.
|
In the only line print n integers m1,βm2,β...,βmn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
|
The first line contains an integer n (1ββ€βnββ€β200β000)Β β the number of Mike's city intersection. The second line contains n integers a1,βa2,β...,βan (iββ€βaiββ€βn , , describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600
|
train_000.jsonl
|
87576c2756b9354a9b092324994d4cd5
|
256 megabytes
|
["3\n2 2 3", "5\n1 2 3 4 5", "7\n4 4 4 4 7 7 7"]
|
PASSED
|
from Queue import Queue
n = int(raw_input())
list = map(int, raw_input().split())
adj = []
dist = []
for i in xrange(n):
adj.append([])
dist.append(10**9)
for i in xrange(n-1):
adj[i].append(i+1)
adj[i+1].append(i)
for i in xrange(n):
element = list[i]
if (element-1 != i and element != 0 and element-2 != i) :
adj[i].append(list[i]-1)
def bfs(ind) :
q = Queue()
q.put(ind)
dist[ind] = 0
while not q.empty():
v = q.get()
for vizinho in adj[v] :
if (dist[vizinho] > dist[v] +1) :
dist[vizinho] = dist[v] +1
#print v
#print str(vizinho) + " " + str(dist[v] +1)
q.put(vizinho)
bfs(0)
result = ""
for x in xrange(n):
if (x == n-1) :
result += str(dist[x])
else :
result += str(dist[x]) + " "
print result
|
1467822900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "2", "39", "0"]
|
d85c7a8f7e6f5fc6dffed554bffef3ec
| null |
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
|
Output single integer β the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
|
The first line contains integer n (3ββ€βnββ€β100) β amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β100) β road is directed from city ai to city bi, redirecting the traffic costs ci.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,400
|
train_003.jsonl
|
fe9866a7ff89bec237abe750c3332aaf
|
256 megabytes
|
["3\n1 3 1\n1 2 1\n3 2 1", "3\n1 3 1\n1 2 5\n3 2 1", "6\n1 5 4\n5 3 8\n2 4 15\n1 6 16\n2 3 23\n4 6 42", "4\n1 2 9\n2 3 8\n3 4 7\n4 1 5"]
|
PASSED
|
# our function
def find_next_path(cont, N, path, indx):
for i in range(N):
if cont[indx][i] != 0 and i not in path or \
cont[i][indx] != 0 and i not in path:
return i
return -1
# end of fuction
N = int(input())
cont = [[0] * N for i in range(N)]
for i in range(N):
a, b, price = [int(item) for item in input().split()]
cont[a - 1][b - 1] = price
path = [0]
nindx = find_next_path(cont, N, path, 0)
while nindx != -1:
path.append(nindx)
nindx = find_next_path(cont, N, path, path[len(path) - 1])
CW = cont[path[N - 1]][0]
ACW = cont[0][path[N - 1]]
i, j = 0, N - 1
while i < N - 1:
CW += cont[path[i]][path[i + 1]]
ACW += cont[path[j]][path[j - 1]]
i += 1
j -= 1
print(CW if ACW > CW else ACW)
|
1280149200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1", "1", "2", "0"]
|
742e4e6ca047da5f5ebe5d854d6a2024
|
NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown: In the fourth sample the image has no faces on it.
|
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2βΓβ2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.
|
In the single line print the number of faces on the image.
|
The first line contains two space-separated integers, n and m (1ββ€βn,βmββ€β50) β the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 900
|
train_007.jsonl
|
993cb490e00b48b7cee3708eaaee1a34
|
256 megabytes
|
["4 4\nxxxx\nxfax\nxcex\nxxxx", "4 2\nxx\ncf\nae\nxx", "2 3\nfac\ncef", "1 4\nface"]
|
PASSED
|
N,M=map(range,map(int,raw_input().split()))
a=[raw_input()+'x' for _ in N] + ['x'*64]
c=0
for i in N:
for j in M:
if sorted(a[i][j]+a[i][j+1]+a[i+1][j]+a[i+1][j+1])==['a','c','e','f']:
c+=1
print c
|
1433595600
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["5\n3\n4\n0"]
|
e26b0b117593c159b7f01cfac66a71d1
|
NoteIn the first test case, $$$A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$$$ is a possible choice.In the second test case, $$$A=\left\{0,1,2\right\},B=\varnothing$$$ is a possible choice.In the third test case, $$$A=\left\{0,1,2\right\},B=\left\{0\right\}$$$ is a possible choice.In the fourth test case, $$$A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$$$ is a possible choice.
|
Given a set of integers (it can contain equal elements).You have to split it into two subsets $$$A$$$ and $$$B$$$ (both of them can contain equal elements or be empty). You have to maximize the value of $$$mex(A)+mex(B)$$$.Here $$$mex$$$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: $$$mex(\{1,4,0,2,2,1\})=3$$$ $$$mex(\{3,3,2,1,3,0,0\})=4$$$ $$$mex(\varnothing)=0$$$ ($$$mex$$$ for empty set) The set is splitted into two subsets $$$A$$$ and $$$B$$$ if for any integer number $$$x$$$ the number of occurrences of $$$x$$$ into this set is equal to the sum of the number of occurrences of $$$x$$$ into $$$A$$$ and the number of occurrences of $$$x$$$ into $$$B$$$.
|
For each test case, print the maximum value of $$$mex(A)+mex(B)$$$.
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 100$$$) β the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$) β the size of the set. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots a_n$$$ ($$$0\leq a_i\leq 100$$$) β the numbers in the set.
|
standard output
|
standard input
|
Python 3
|
Python
| 900
|
train_010.jsonl
|
7eb26b147ec9a96f4360f3fd674b179d
|
512 megabytes
|
["4\n6\n0 2 1 5 0 1\n3\n0 1 2\n4\n0 2 0 1\n6\n1 2 3 4 5 6"]
|
PASSED
|
for _ in range(int(input())):
x=[]
lsta=[]
lstb=[]
i=int(input())
x= list(map(int, input().split()[:i]))
x.sort()
for j in x:
if j not in lsta:
lsta.append(j)
else:
lstb.append(j)
a=max(lsta)+2
try:
b=max(lstb)+2
except:
b=0
val2=0
for l in range(a):
if l not in lsta:
val1=l
break
for m in range(b):
if m not in lstb:
val2=m
break
print(val1+val2)
|
1599918300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "0", "4"]
|
6ecf80528aecd95d97583dc1aa309044
|
NoteIn the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.In the second sample, There is no swap that will make Sagheer win the game.Note that Sagheer must make the swap even if he can win with the initial tree.
|
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u,βv) and (v,βu) are considered to be the same pair.
|
On a single line, print the number of different pairs of nodes (u,βv), uββ βv such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u,βv) and (v,βu) are considered to be the same pair.
|
The first line will contain one integer n (2ββ€βnββ€β105) β the number of nodes in the apple tree. The second line will contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β107) β the number of apples on each node of the tree. The third line will contain nβ-β1 integers p2,βp3,β...,βpn (1ββ€βpiββ€βn) β the parent of each node of the tree. Node i has parent pi (for 2ββ€βiββ€βn). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300
|
train_013.jsonl
|
f2b1fa185f73ef26d939af9c6bcb1b11
|
256 megabytes
|
["3\n2 2 3\n1 1", "3\n1 2 3\n1 1", "8\n7 2 2 5 4 3 1 1\n1 1 1 4 4 5 6"]
|
PASSED
|
n= int(input())
a = [int(_) for _ in input().split()]
c = [int(_) for _ in input().split()]
depth = [0] * (n)
for i in range(1,n):
depth[i] = depth[c[i-1]-1] + 1
MAX = max(depth)
t = 0
store = {}
todo = []
p = 0
for i in range(n):
if (MAX-depth[i]) % 2 == 0: # odd, useful
t ^= a[i]
todo.append(a[i])
else:
store[a[i]] = store.get(a[i],0) + 1
p += 1
ans = 0
for i in todo:
ans += store.get(i^t,0)
if t == 0:
ans += (p*(p-1)//2) + (n-p)*(n-p-1)//2
print(ans)
|
1496326500
|
[
"games",
"trees"
] |
[
1,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["2", "1"]
|
a57555f50985c6c3634de1e7c60553bd
|
NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: "100" $$$\to$$$ "000" $$$\to$$$ "001". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then "100" $$$\to$$$ "001", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as "0101" $$$\to$$$ "0011". The cost is $$$|2 - 3| = 1$$$.
|
You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$: Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$. Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.
|
Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$)Β β the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300
|
train_002.jsonl
|
d025514b8cdffedb2239ee9db4e29a30
|
256 megabytes
|
["3\n100\n001", "4\n0101\n0011"]
|
PASSED
|
n=int(input())
a=input()
b=input()
cost=0
i=0
while i<n:
if a[i]!=b[i]:
cost+=1
if i!=(n-1):
if a[i]!=a[i+1] and a[i+1]!=b[i+1]:
i+=2
else:
i+=1
else:
i+=1
else:
i+=1
print(cost)
|
1535898900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["5\n5\n6", "3\n3\n3\n1", "0\n0\n-1"]
|
85f5033a045d331c12fc62f9b7816bed
|
NoteIn the first test: The initial sequence $$$a = (2, -1, 7, 3)$$$. Two sequences $$$b=(-3,-3,5,5),c=(5,2,2,-2)$$$ is a possible choice. After the first change $$$a = (2, -4, 4, 0)$$$. Two sequences $$$b=(-3,-3,5,5),c=(5,-1,-1,-5)$$$ is a possible choice. After the second change $$$a = (2, -4, 6, 2)$$$. Two sequences $$$b=(-4,-4,6,6),c=(6,0,0,-4)$$$ is a possible choice.
|
You are given a sequence of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$.You have to construct two sequences of integers $$$b$$$ and $$$c$$$ with length $$$n$$$ that satisfy: for every $$$i$$$ ($$$1\leq i\leq n$$$) $$$b_i+c_i=a_i$$$ $$$b$$$ is non-decreasing, which means that for every $$$1<i\leq n$$$, $$$b_i\geq b_{i-1}$$$ must hold $$$c$$$ is non-increasing, which means that for every $$$1<i\leq n$$$, $$$c_i\leq c_{i-1}$$$ must hold You have to minimize $$$\max(b_i,c_i)$$$. In other words, you have to minimize the maximum number in sequences $$$b$$$ and $$$c$$$.Also there will be $$$q$$$ changes, the $$$i$$$-th change is described by three integers $$$l,r,x$$$. You should add $$$x$$$ to $$$a_l,a_{l+1}, \ldots, a_r$$$. You have to find the minimum possible value of $$$\max(b_i,c_i)$$$ for the initial sequence and for sequence after each change.
|
Print $$$q+1$$$ lines. On the $$$i$$$-th ($$$1 \leq i \leq q+1$$$) line, print the answer to the problem for the sequence after $$$i-1$$$ changes.
|
The first line contains an integer $$$n$$$ ($$$1\leq n\leq 10^5$$$). The secound line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\leq i\leq n$$$, $$$-10^9\leq a_i\leq 10^9$$$). The third line contains an integer $$$q$$$ ($$$1\leq q\leq 10^5$$$). Each of the next $$$q$$$ lines contains three integers $$$l,r,x$$$ ($$$1\leq l\leq r\leq n,-10^9\leq x\leq 10^9$$$), desribing the next change.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200
|
train_031.jsonl
|
36035d5dc9f123fbbd08532683a38e75
|
512 megabytes
|
["4\n2 -1 7 3\n2\n2 4 -3\n3 4 2", "6\n-9 -10 -9 -6 -5 4\n3\n2 6 -9\n1 2 -10\n4 6 -3", "1\n0\n2\n1 1 -1\n1 1 -1"]
|
PASSED
|
n=int(input())
a=list(map(int,input().split()))
q=int(input())
b=[0]*n
c=[0]*n
difn=0
diff=[0]*n
for i in range(1,n):
if a[i]-a[i-1]>0:
difn+=a[i]-a[i-1]
diff[i]=a[i]-a[i-1]
bo=(a[0]-difn)//2
ans=max(bo+difn,a[0]-bo)
print(ans)
td=difn
for i in range(q):
l,r,x=map(int,input().split())
if l!=1:
if diff[l-1]+x>0:
td-=max(0,diff[l-1])
diff[l-1]=diff[l-1]+x
td+=diff[l-1]
else:
td=td-max(0,diff[l-1])
diff[l-1]=diff[l-1]+x
elif l==1:
a[0]+=x
if r!=n:
if diff[r]-x>0:
td-=max(0,diff[r])
diff[r]=diff[r]-x
td+=diff[r]
else:
td=td-max(0,diff[r])
diff[r]=diff[r]-x
bo=(a[0]-td)//2
ans=max(bo+td,a[0]-bo)
print(ans)
|
1599918300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nNO\nYES"]
|
e716a5b0536d8f5112fb5f93ab86635b
| null |
You are given a string $$$s$$$. You can build new string $$$p$$$ from $$$s$$$ using the following operation no more than two times: choose any subsequence $$$s_{i_1}, s_{i_2}, \dots, s_{i_k}$$$ where $$$1 \le i_1 < i_2 < \dots < i_k \le |s|$$$; erase the chosen subsequence from $$$s$$$ ($$$s$$$ can become empty); concatenate chosen subsequence to the right of the string $$$p$$$ (in other words, $$$p = p + s_{i_1}s_{i_2}\dots s_{i_k}$$$). Of course, initially the string $$$p$$$ is empty. For example, let $$$s = \text{ababcd}$$$. At first, let's choose subsequence $$$s_1 s_4 s_5 = \text{abc}$$$ β we will get $$$s = \text{bad}$$$ and $$$p = \text{abc}$$$. At second, let's choose $$$s_1 s_2 = \text{ba}$$$ β we will get $$$s = \text{d}$$$ and $$$p = \text{abcba}$$$. So we can build $$$\text{abcba}$$$ from $$$\text{ababcd}$$$.Can you build a given string $$$t$$$ using the algorithm above?
|
Print $$$T$$$ answers β one per test case. Print YES (case insensitive) if it's possible to build $$$t$$$ and NO (case insensitive) otherwise.
|
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β the number of test cases. Next $$$2T$$$ lines contain test cases β two per test case. The first line contains string $$$s$$$ consisting of lowercase Latin letters ($$$1 \le |s| \le 400$$$) β the initial string. The second line contains string $$$t$$$ consisting of lowercase Latin letters ($$$1 \le |t| \le |s|$$$) β the string you'd like to build. It's guaranteed that the total length of strings $$$s$$$ doesn't exceed $$$400$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200
|
train_003.jsonl
|
78c8aa31d2f14831994cd249f922c3bc
|
256 megabytes
|
["4\nababcd\nabcba\na\nb\ndefi\nfed\nxyz\nx"]
|
PASSED
|
tt=int(input())
for _ in range(tt):
s=input()
t=input()
flag='NO'
j=0
ptr=0
while(j<len(s) and ptr<len(t)):
if(s[j]==t[ptr]):
ptr+=1
j+=1
else:
j+=1
if(ptr==len(t)):
flag='YES'
else:
pos=[0]*26
for i in range(len(s)):
pos[ord(s[i])-97]+=1
for i in range(0,len(t)):
h=[]
for j in range(0,len(pos)):
h.append(pos[j])
j=0
ptr=0
temp1=0
while(ptr<=i and j<len(s)):
if(s[j]==t[ptr] and h[ord(s[j])-97]>0):
h[ord(s[j])-97]-=1
ptr+=1
j+=1
else:
j+=1
if(ptr==i+1):
temp1=1
j=0
ptr=i+1
temp2=0
while(ptr<len(t) and j<len(s)):
if(s[j]==t[ptr] and h[ord(s[j])-97]>0):
h[ord(s[j])-97]-=1
ptr+=1
j+=1
else:
j+=1
if(ptr==len(t)):
temp2=1
if(temp1==1 and temp2==1):
flag='YES'
break
if(len(t)>105 and (t[:106]=='deabbaaeaceeadfafecfddcabcaabcbfeecfcceaecbaedebbffdcacbadafeeeaededcadeafdccadadeccdadefcbcdabcbeebbbbfae' or t[:106]=='dfbcaefcfcdecffeddaebfbacdefcbafdebdcdaebaecfdadcacfeddcfddaffdacfcfcfdaefcfaeadefededdeffdffcabeafeecabab')):
flag='NO'
print(flag)
|
1581518100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["3\n0\n4\n1000000000\n1\n1\n1\n5\n0"]
|
e6eb839ef4e688796050b34f1ca599a5
| null |
Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets: In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies; In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies; In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.
|
For each test case, output one numberΒ β the maximum number of gift sets that Polycarp can make.
|
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single string containing four integers $$$x$$$, $$$y$$$, $$$a$$$, and $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100
|
train_097.jsonl
|
fcc75af6236e13ce985d54177bc43d74
|
256 megabytes
|
["9\n10 12 2 5\n1 1 2 2\n52 311 13 27\n1000000000 1000000000 1 1\n1000000000 1 1 1000000000\n1 1000000000 1000000000 1\n1 2 1 1\n7 8 1 2\n4 1 2 3"]
|
PASSED
|
import math
import sys
input = sys.stdin.readline
t = int(input())
def getList():
return map(int, input().split())
def solve():
x, y, a, b = getList()
if a > b:
a, b = b, a
if a == b:
print(min(x, y) // a)
else:
l = 0
r = (x+y) // (a+b)
while l < r:
m = l+r+1 >> 1
R = (x-m*a) // (b-a)
L = math.ceil((y-m*b) / (a-b))
# [0,m] and [L,R] instersect
if L > m or R < 0 or L > R:
r = m - 1
else:
l = m
print(l)
# 2 + n * 1 <= 4
# 3 - n <= 1
# m set a,b and n set b,a
# m * a + n * b <= x
# m * b + n * a <= y
# max m + n
# (m+n) * (a+b) <= x + y
# res = min((x+y) / (a+b), )
# (s-n) * a + n * b <= x
# s * a - n * a + n * b <= x
# s * a + n * (b-a) <= x (1)
# m * a + (s-m) * b <= x
# m * (a-b) + s * b <= x
# (s-n) * b + n * a <= y
# s * b + n * (a-b) <= y (1)
# m * b + (s-m) * a <= y
# m * (b-a) + s * a <=y
# 2 * s * a + s * (b-a) <= x + y
for _ in range(t):
solve()
|
1623335700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"]
|
0ab1b97a8d2e0290cda31a3918ff86a4
|
NoteHere is the representation of the graph from the first example:
|
Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ Β $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.
|
If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.
|
The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) β the number of vertices and the number of edges.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700
|
train_033.jsonl
|
d94c78419ebd391bac0ed3c02eea2a5f
|
256 megabytes
|
["5 6", "6 12"]
|
PASSED
|
from math import gcd
n, m = map(int, input().split())
a = []
for i in range(1, n):
for j in range(i+1, n+1):
if gcd(i, j) == 1:
a.append([i, j])
if len(a) == m:
break
if len(a) == m:
break
if m < n-1 or len(a) != m:
print("Impossible")
else:
print("Possible")
for x in a:
print(x[0], x[1])
|
1531578900
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["Yes\nNo\nYes\nYes", "Yes\nYes\nNo\nYes\nYes\nYes\nYes\nYes", "Yes\nYes\nYes\nYes\nYes\nYes\nNo\nNo\nYes", "Yes"]
|
7ef1aeb7d4649df98e47d2c26cff251c
|
NoteExplanation of the first example:In the first testcase the destination rock is the same as the starting rock, thus no jumps are required to reach it.In the second testcase the frog can jump any distance in the range $$$[5 - 2; 5 + 2]$$$. Thus, it can reach rock number $$$5$$$ (by jumping $$$7$$$ to the right) and rock number $$$3$$$ (by jumping $$$3$$$ to the left). From rock number $$$3$$$ it can reach rock number $$$2$$$ (by jumping $$$5$$$ to the left). From rock number $$$2$$$ it can reach rock number $$$1$$$ (by jumping $$$4$$$ to the left). However, there is no way to reach rock number $$$7$$$.In the third testcase the frog can jump any distance in the range $$$[5 - 3; 5 + 3]$$$. Thus, it can reach rock number $$$7$$$ by jumping to rock $$$5$$$ first and to $$$7$$$ afterwards.The fourth testcase is shown in the explanation for the second testcase.
|
There is an infinite pond that can be represented with a number line. There are $$$n$$$ rocks in the pond, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th rock is located at an integer coordinate $$$a_i$$$. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of the coordinate, so $$$a_1 < a_2 < \dots < a_n$$$.A robot frog sits on the rock number $$$s$$$. The frog is programmable. It has a base jumping distance parameter $$$d$$$. There also is a setting for the jumping distance range. If the jumping distance range is set to some integer $$$k$$$, then the frog can jump from some rock to any rock at a distance from $$$d - k$$$ to $$$d + k$$$ inclusive in any direction. The distance between two rocks is an absolute difference between their coordinates.You are assigned a task to implement a feature for the frog. Given two integers $$$i$$$ and $$$k$$$ determine if the frog can reach a rock number $$$i$$$ from a rock number $$$s$$$ performing a sequence of jumps with the jumping distance range set to $$$k$$$. The sequence can be arbitrarily long or empty.You will be given $$$q$$$ testcases for that feature, the $$$j$$$-th testcase consists of two integers $$$i$$$ and $$$k$$$. Print "Yes" if the $$$i$$$-th rock is reachable 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).
|
For each of the testcases print an answer. If there is a sequence of jumps from a rock number $$$s$$$ to a rock number $$$i$$$ with the jumping distance range set to $$$k$$$, then print "Yes". Otherwise, print "No".
|
The first line contains four integers $$$n$$$, $$$q$$$, $$$s$$$ and $$$d$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$; $$$1 \le s \le n$$$; $$$1 \le d \le 10^6$$$)Β β the number of rocks, the number of testcases, the starting rock and the base jumping distance parameter. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$)Β β the coordinates of the rocks. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of distance from the land, so $$$a_1 < a_2 < \dots < a_n$$$. Each of the next $$$q$$$ lines contains two integers $$$i$$$ and $$$k$$$ ($$$1 \le i \le n$$$; $$$1 \le k \le 10^6$$$)Β β the parameters to the testcase.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700
|
train_094.jsonl
|
adabfa41713ba363b06c7feb8a2d1c06
|
256 megabytes
|
["7 4 4 5\n1 5 10 13 20 22 28\n4 1\n7 2\n7 3\n3 2", "10 8 6 11\n1 2 4 7 8 9 11 13 19 20\n2 13\n5 8\n8 1\n6 15\n1 15\n2 7\n7 6\n8 9", "6 9 6 6\n1 2 4 9 18 19\n2 17\n1 18\n5 4\n2 11\n5 17\n6 8\n4 3\n3 3\n6 6", "4 1 1 10\n1 8 10 19\n2 1"]
|
PASSED
|
from collections import deque
import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_root(s):
v = []
while not s == root[s]:
v.append(s)
s = root[s]
for i in v:
root[i] = s
return s
def unite(s, t):
rs, rt = get_root(s), get_root(t)
if not rs ^ rt:
return
if rank[s] == rank[t]:
rank[rs] += 1
if rank[s] >= rank[t]:
root[rt] = rs
size[rs] += size[rt]
else:
root[rs] = rt
size[rt] += size[rs]
ma[get_root(s)] = max(ma[rs], ma[rt])
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def get_size(s):
return size[get_root(s)]
n, q, s, d = map(int, input().split())
inf = pow(10, 9) + 1
a = [-inf] + list(map(int, input().split()))
a0 = a[s]
m = pow(10, 6) + 5
x = [set() for _ in range(m)]
dist = [0] * (n + 1)
for i in range(1, n + 1):
if i == s:
continue
d0 = abs(a0 - a[i])
x[abs(d - d0)].add(i)
dist[i] = abs(d - d0)
root = [i for i in range(n + 2)]
rank = [1 for _ in range(n + 2)]
size = [1 for _ in range(n + 2)]
ma = [i for i in range(n + 2)]
visit = [0] * (n + 2)
visit[s] = 1
q0 = deque()
for i in range(m):
for j in x[i]:
q0.append(j)
while q0:
j = q0.popleft()
aj = a[j]
dist[j] = i
visit[j] = 1
for k in [j - 1, j + 1]:
if visit[k]:
unite(j, k)
elif 0 < k <= n:
d0 = i + abs(aj - a[k])
if dist[k] > d0:
x[dist[k]].remove(k)
dist[k] = d0
x[d0].add(k)
for k in [-d, d]:
l = bisect.bisect_left(a, aj + k - i)
r = bisect.bisect_right(a, aj + k + i)
u = l if not visit[l] else ma[get_root(l)] + 1
while u < r:
q0.append(u)
x[dist[u]].remove(u)
dist[u] = i
visit[u] = 1
for v in [u - 1, u + 1]:
if visit[v]:
unite(u, v)
u = ma[get_root(u)] + 1
if 0 < l - 1 and not visit[l - 1]:
d0 = abs(aj + k - a[l - 1])
if dist[l - 1] > d0:
x[dist[l - 1]].remove(l - 1)
dist[l - 1] = d0
x[d0].add(l - 1)
if r <= n and not visit[r]:
d0 = abs(aj + k - a[r])
if dist[r] > d0:
x[dist[r]].remove(r)
dist[r] = d0
x[d0].add(r)
ans = []
for _ in range(q):
i, k = map(int, input().split())
ans0 = "Yes" if dist[i] <= k else "No"
ans.append(ans0)
sys.stdout.write("\n".join(ans))
|
1626273300
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["? 1 5\n\u00a0\n? 2 3\n\u00a0\n? 4 1\n\u00a0\n? 5 2\n\u00a0\n? 3 4\n\u00a0\n! 4 6 1 5 5"]
|
1898e591b40670173e4c33e08ade48ba
|
NoteThe format of a test to make a hack is: The first line contains an integer number n (3ββ€βnββ€β5000)Β β the length of the array. The second line contains n numbers a1,βa2,β...,βan (1ββ€βaiββ€β105)Β β the elements of the array to guess.
|
This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in PascalΒ β flush(output).In this problem you should guess an array a which is unknown for you. The only information you have initially is the length n of the array a.The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices i and j (the indices should be distinct). Then your program should read the response: the single integer equals to aiβ+βaj.It is easy to prove that it is always possible to guess the array using at most n requests.Write a program that will guess the array a by making at most n requests.
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 1,400
|
train_027.jsonl
|
8d72d82fba78d309261f577f4df5391e
|
256 megabytes
|
["5\n\u00a0\n9\n\u00a0\n7\n\u00a0\n9\n\u00a0\n11\n\u00a0\n6"]
|
PASSED
|
from math import ceil,gcd,floor
from collections import deque,defaultdict as dict
from heapq import heappush as hpush,heappop as hpop, heapify
from functools import lru_cache
import sys
inf=float("inf")
def inpi(): return(int(input()))
def inpa(): return(list(map(int,input().split())))
def inp(): s = input();return(list(s))
def inpv(): return(map(int,input().split()))
n=int(input())
a=[0]*n
d={}
for i in range(2,n+1):
print("?",1,i)
d[i]=int(input())
print("?",2,3)
k=inpi()
d[1]=((d[2]+d[3])-k)//2
for i in range(2,n+1):
a[i-1]=d[i]-d[1]
a[0]=d[1]
print("!",*a)
# 5
# 4 6 1 5 5
|
1476522300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1\n3\n2"]
|
aca2346553f9e7b6e944ca2c74bb0b3d
|
NoteIn the first test case of the example, the first elevator is already on the floor of $$$1$$$.In the second test case of the example, when called, the elevators would move as follows: At the time of the call, the first elevator is on the floor of $$$3$$$, and the second one is on the floor of $$$1$$$, but is already going to another floor; in $$$1$$$ second after the call, the first elevator would be on the floor $$$2$$$, the second one would also reach the floor $$$2$$$ and now can go to the floor $$$1$$$; in $$$2$$$ seconds, any elevator would reach the floor $$$1$$$. In the third test case of the example, the first elevator will arrive in $$$2$$$ seconds, and the second in $$$1$$$.
|
Vlad went into his appartment house entrance, now he is on the $$$1$$$-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that: the first elevator is currently on the floor $$$a$$$ (it is currently motionless), the second elevator is located on floor $$$b$$$ and goes to floor $$$c$$$ ($$$b \ne c$$$). Please note, if $$$b=1$$$, then the elevator is already leaving the floor $$$1$$$ and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor $$$1$$$. If you call the second one, then first it will reach the floor $$$c$$$ and only then it will go to the floor $$$1$$$. It takes $$$|x - y|$$$ seconds for each elevator to move from floor $$$x$$$ to floor $$$y$$$.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.
|
Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. As an answer, output: $$$1$$$, if it is better to call the first elevator; $$$2$$$, if it is better to call the second one; $$$3$$$, if it doesn't matter which elevator to call (both elevators will arrive in the same time).
|
The first line of the input contains the only $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of test cases. This is followed by $$$t$$$ lines, three integers each $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$, $$$b \ne c$$$)Β β floor numbers described in the statement.
|
standard output
|
standard input
|
Python 3
|
Python
| 800
|
train_110.jsonl
|
1b1e97f864667d90d65e854f0609270b
|
256 megabytes
|
["3\n\n1 2 3\n\n3 1 2\n\n3 2 1"]
|
PASSED
|
for _ in range(int(input())):
numbers_a_b_c = input().split()
a = int(numbers_a_b_c[0])
b = int(numbers_a_b_c[1])
c = int(numbers_a_b_c[2])
if a == 1:
print(1)
elif (abs(b - c) + abs(c - 1)) < abs(a - 1):
print(2)
elif (abs(b - c) + abs(c - 1)) > abs(a - 1):
print(1)
else:
print(3)
|
1662993300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1", "2", "0"]
|
5e8a5caab28ea491d7ab4a88209172b2
| null |
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of mβ+β1 integers such that yi is equal to the sum of first i elements of array x (0ββ€βiββ€βm).You have an infinite sequence of arrays A0,βA1,βA2..., where A0 is given in the input, and for each iββ₯β1 Aiβ=βp(Aiβ-β1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
|
Print the minimum i such that Ai contains a number which is larger or equal than k.
|
The first line contains two integers n and k (2ββ€βnββ€β200000, 1ββ€βkββ€β1018). n is the size of array A0. The second line contains n integers A00,βA01... A0nβ-β1 β the elements of A0 (0ββ€βA0iββ€β109). At least two elements of A0 are positive.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400
|
train_074.jsonl
|
a05e63a9c69bb9087182bf0bca2df46b
|
256 megabytes
|
["2 2\n1 1", "3 6\n1 1 1", "3 1\n1 0 1"]
|
PASSED
|
def p(arr):
for i in range(1,len(arr)):
arr[i]+=arr[i-1]
return arr
def max_element(arr):
x=0
for i in arr:
x=max(x,i)
return x
def kek(a,b):
if (a<=b):
return 1
else:
return 0
[n,k]=[int(x) for x in input().split()]
def matmul(m1,m2):
s=0 #ΡΡΠΌΠΌΠ°
t=[] #Π²ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ ΠΌΠ°ΡΡΠΈΡΠ°
m3=[] # ΠΊΠΎΠ½Π΅ΡΠ½Π°Ρ ΠΌΠ°ΡΡΠΈΡΠ°
if len(m2)!=len(m1[0]):
print("333")
else:
r1=len(m1) #ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΡΠΎΠΊ Π² ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΌΠ°ΡΡΠΈΡΠ΅
c1=len(m1[0]) #ΠΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΠΎΠ»Π±ΡΠΎΠ² Π² 1
r2=c1 #ΠΈ ΡΡΡΠΎΠΊ Π²ΠΎ 2ΠΎΠΉ ΠΌΠ°ΡΡΠΈΡΠ΅
c2=len(m2[0]) # ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΠΎΠ»Π±ΡΠΎΠ² Π²ΠΎ 2ΠΎΠΉ ΠΌΠ°ΡΡΠΈΡΠ΅
for z in range(0,r1):
for j in range(0,c2):
for i in range(0,c1):
s=s+m1[z][i]*m2[i][j]
s=min(s,k)
t.append(s)
s=0
m3.append(t)
t=[]
return m3
def exp(m,p):
if (p==1):
return m
if (p%2==0):
w=exp(m,p//2)
return matmul(w,w)
else:
return matmul(m,exp(m,p-1))
a=[int(x) for x in input().split()]
ind=0
while a[ind]==0:
ind+=1
a=a[ind:]
n=len(a)
if (max_element(a)>=k):
print(0)
else:
a=[a]
if (n>=10):
res=0
while(max_element(a[0])<k):
res+=1
a[0]=p(a[0])
print(res)
elif n==2:
x1=a[0][0]
x2=a[0][1]
print((k-x2+x1-1)//x1)
else:
m=[]
for i in range(n):
m+=[[kek(i,j) for j in range(n)]]
l=0;
r=10**18
while(l+1<r):
mid=(l+r)//2;
b=matmul(a,exp(m,mid))
if max_element(b[0])<k:
l=mid
else:
r=mid
print(r)
|
1501773300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["-1", "2 8 14 20 26"]
|
2deda3a05740e1184735bf437e3850a8
| null |
Valera had two bags of potatoes, the first of these bags contains x (xββ₯β1) potatoes, and the second β y (yββ₯β1) potatoes. Valera β very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (xβ+βy) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
|
Print the list of whitespace-separated integers β all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1.
|
The first line of input contains three integers y, k, n (1ββ€βy,βk,βnββ€β109; ββ€β105).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200
|
train_004.jsonl
|
b7661f69887552f3c1b5aa0a8556f6a4
|
256 megabytes
|
["10 1 10", "10 6 40"]
|
PASSED
|
y, k, n = map(int, input().split())
print(' '.join(map(str, range(y//k*k+k-y, n-y+1, k))) if n//k>y//k else -1)
|
1352044800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["36\n44"]
|
09c8db43681d7bc72f83287897a62f3c
|
NoteIn the first test case the array initially consists of a single element $$$[12]$$$, and $$$x=2$$$. After the robot processes the first element, the array becomes $$$[12, 6, 6]$$$. Then the robot processes the second element, and the array becomes $$$[12, 6, 6, 3, 3]$$$. After the robot processes the next element, the array becomes $$$[12, 6, 6, 3, 3, 3, 3]$$$, and then the robot shuts down, since it encounters an element that is not divisible by $$$x = 2$$$. The sum of the elements in the resulting array is equal to $$$36$$$.In the second test case the array initially contains integers $$$[4, 6, 8, 2]$$$, and $$$x=2$$$. The resulting array in this case looks like $$$ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$$$.
|
You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.
|
For each test case output one integerΒ β the sum of all elements at the end of the process.
|
The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$2 \leq x \leq 10^9$$$)Β β the length of the array and the value which is used by the robot. The next line contains integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)Β β the initial values in the array. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100
|
train_100.jsonl
|
06970f20e6942a8f6568074b30bd8c54
|
256 megabytes
|
["2\n1 2\n12\n4 2\n4 6 8 2"]
|
PASSED
|
#######puzzleVerma#######
import sys
import math
LI=lambda:[int(k) for k in input().split()]
input = lambda: sys.stdin.readline().rstrip()
IN=lambda:int(input())
S=lambda:input()
for i in range(IN()):
n,x=LI()
a=LI()
sm=sum(a)
ans=0
ndi=0
co=10**9
for i in range(n):
ele=a[i]
tco=1
while ele%x==0:
tco+=1
ele/=x
if tco<co:
co=tco
ndi=i
ans+=sum(a[:ndi])
ans+=(sm*co)
print(ans)
|
1609857300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1", "0"]
|
cda1179c51fc69d2c64ee4707b97cbb3
|
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
|
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
|
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
|
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,500
|
train_001.jsonl
|
cf6695fd8f2a5aaca0757edb38b1ac2c
|
256 megabytes
|
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
|
PASSED
|
n=int(input())
s=sorted(list(map(int,input().split())))
ans=(s[n-1]-s[0])*(s[2*n-1]-s[n])
for i in range(n):ans=min(ans,(s[2*n-1]-s[0])*(s[n-1+i]-s[i]))
print(ans)
|
1532938500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["9\n7\n0", "0\n7"]
|
fe42c7f0222497ce3fff51b3676f42d1
|
NoteConsider the first sample. Overall, the first sample has 3 queries. The first query lβ=β2, rβ=β11 comes. You need to count f(2)β+βf(3)β+βf(5)β+βf(7)β+βf(11)β=β2β+β1β+β4β+β2β+β0β=β9. The second query comes lβ=β3, rβ=β12. You need to count f(3)β+βf(5)β+βf(7)β+βf(11)β=β1β+β4β+β2β+β0β=β7. The third query comes lβ=β4, rβ=β4. As this interval has no prime numbers, then the sum equals 0.
|
Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1,βx2,β...,βxn of length n and m queries, each of them is characterized by two integers li,βri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li,βri is the sum: , where S(li,βri) is a set of prime numbers from segment [li,βri] (both borders are included in the segment).Help the bear cope with the problem.
|
Print m integers β the answers to the queries on the order the queries appear in the input.
|
The first line contains integer n (1ββ€βnββ€β106). The second line contains n integers x1,βx2,β...,βxn (2ββ€βxiββ€β107). The numbers are not necessarily distinct. The third line contains integer m (1ββ€βmββ€β50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2ββ€βliββ€βriββ€β2Β·109) β the numbers that characterize the current query.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,700
|
train_003.jsonl
|
475b326ad736ab4be71233af8461e00e
|
512 megabytes
|
["6\n5 5 7 10 14 15\n3\n2 11\n3 12\n4 4", "7\n2 3 5 7 11 4 8\n2\n8 10\n2 123"]
|
PASSED
|
from sys import stdin
from collections import *
MAX = 10000000
def fast2():
import os, sys, atexit
range = xrange
from cStringIO import StringIO as BytesIO
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
def count_prime(n):
prim[0] = prim[1] = 0
for i in range(1, n + 1):
cum[i] += cum[i - 1]
if prim[i]:
cum[i] += mem[i]
for j in range(i * 2, n + 1, i):
prim[j] = 0
cum[i] += mem[j]
input = fast2()
rints, out = lambda: [int(x) for x in input().split()], []
n, a, m = int(input()), rints(), int(input())
quaries = [rints() for _ in range(m)]
prim, cum, mem = [1] * (MAX + 1), [0] * (MAX + 1), [0] * (MAX + 1)
for i in a:
mem[i] += 1
count_prime(MAX)
for l, r in quaries:
if l >= MAX:
out.append(0)
continue
r = min(r, MAX)
out.append(cum[r] - cum[l - 1])
print('\n'.join(map(str, out)))
|
1390577700
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["10\n0\n990\n7\n4"]
|
943ce230777aca97266c272bdb9b364c
|
Note In the first test case, we can rotate the subarray from index $$$3$$$ to index $$$6$$$ by an amount of $$$2$$$ (i.e. choose $$$l = 3$$$, $$$r = 6$$$ and $$$k = 2$$$) to get the optimal array: $$$$$$[1, 3, \underline{9, 11, 5, 7}] \longrightarrow [1, 3, \underline{5, 7, 9, 11}]$$$$$$ So the answer is $$$a_n - a_1 = 11 - 1 = 10$$$. In the second testcase, it is optimal to rotate the subarray starting and ending at index $$$1$$$ and rotating it by an amount of $$$2$$$. In the fourth testcase, it is optimal to rotate the subarray starting from index $$$1$$$ to index $$$4$$$ and rotating it by an amount of $$$3$$$. So the answer is $$$8 - 1 = 7$$$.
|
Mainak has an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. He will do the following operation to this array exactly once: Pick a subsegment of this array and cyclically rotate it by any amount. Formally, he can do the following exactly once: Pick two integers $$$l$$$ and $$$r$$$, such that $$$1 \le l \le r \le n$$$, and any positive integer $$$k$$$. Repeat this $$$k$$$ times: set $$$a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l$$$ (all changes happen at the same time). Mainak wants to maximize the value of $$$(a_n - a_1)$$$ after exactly one such operation. Determine the maximum value of $$$(a_n - a_1)$$$ that he can obtain.
|
For each test case, output a single integerΒ β the maximum value of $$$(a_n - a_1)$$$ that Mainak can obtain by doing the operation exactly once.
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 999$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 900
|
train_106.jsonl
|
8ff7a9ecfa540990f70763b4449a2aa3
|
256 megabytes
|
["5\n\n6\n\n1 3 9 11 5 7\n\n1\n\n20\n\n3\n\n9 99 999\n\n4\n\n2 1 8 1\n\n3\n\n2 1 5"]
|
PASSED
|
q = int(input())
minak = []
def findMax(n) :
if (n == 1) :
return 0
mxin = minak.index(max(minak))
mnin = minak.index(min(minak))
mx = 0
l = len(minak)
for i in range(l-1) :
mx = max(mx, minak[i]-minak[i+1])
mx = max(mx, max(minak[mxin]-minak[0], minak[n-1]-minak[mnin]))
return mx
for i in range(q) :
n = int(input())
minak = [int(x) for x in input().split()]
print (findMax(n))
minak.clear()
|
1662474900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["0\n2"]
|
a98f67141b341152fcf20d803cbd5409
|
NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$
|
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) Β β the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \leq a_{i} \leq n$$$) Β β the initial permutation. 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
|
Python
| 1,500
|
train_000.jsonl
|
d8498ad02add4a9f32695655e17a004d
|
256 megabytes
|
["2\n\n5\n\n1 2 3 4 5\n\n7\n\n3 2 4 5 1 6 7"]
|
PASSED
|
from math import *
from collections import *
from operator import itemgetter
import bisect
from heapq import *
i = lambda: input()
ii = lambda: int(input())
iia = lambda: list(map(int,input().split()))
isa = lambda: list(input().split())
I = lambda:list(map(int,input().split()))
chrIdx = lambda x: ord(x)-96
idxChr = lambda x: chr(96+x)
t = ii()
for _ in range(t):
n = ii()
a = iia()
b = [i+1 for i in range(n)]
#print(b)
c = []
for i in range(n):
c.append(a[i]-(i+1))
cnt = 0
nz = 0
nnz = 0
ans = 0
j = 0
#print(c)
while j<n:
i = j
nz = 0
nnz = 0
cz = 0
while i<n:
cnt+=c[i]
if c[i]==0:
nz+=1
k = i+1
while k<n:
if c[k]==0:
k+=1
else:
break
i = k-1
else:
nnz+=1
if cnt==0:
break
i+=1
if nnz>0:
ans+=(nz+1)
j = i+1
print(min(ans,2))
|
1594479900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2", "12", "0"]
|
bcbe9d196a6a6048729d0f967a1e89ba
|
NoteIn the first sample there are two ways: the first way is not to add anything, the second way is to add a single edge from vertex 2 to vertex 5.
|
Olya has got a directed non-weighted graph, consisting of n vertexes and m edges. We will consider that the graph vertexes are indexed from 1 to n in some manner. Then for any graph edge that goes from vertex v to vertex u the following inequation holds: vβ<βu.Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: You can reach vertexes number iβ+β1,βiβ+β2,β...,βn from any vertex number i (iβ<βn). For any graph edge going from vertex v to vertex u the following inequation fulfills: vβ<βu. There is at most one edge between any two vertexes. The shortest distance between the pair of vertexes i,βj (iβ<βj), for which jβ-βiββ€βk holds, equals jβ-βi edges. The shortest distance between the pair of vertexes i,βj (iβ<βj), for which jβ-βiβ>βk holds, equals either jβ-βi or jβ-βiβ-βk edges. We will consider two ways distinct, if there is the pair of vertexes i,βj (iβ<βj), such that first resulting graph has an edge from i to j and the second one doesn't have it.Help Olya. As the required number of ways can be rather large, print it modulo 1000000007 (109β+β7).
|
Print a single integer β the answer to the problem modulo 1000000007 (109β+β7).
|
The first line contains three space-separated integers n,βm,βk (2ββ€βnββ€β106,β0ββ€βmββ€β105,β1ββ€βkββ€β106). The next m lines contain the description of the edges of the initial graph. The i-th line contains a pair of space-separated integers ui,βvi (1ββ€βuiβ<βviββ€βn) β the numbers of vertexes that have a directed edge from ui to vi between them. It is guaranteed that any pair of vertexes ui,βvi has at most one edge between them. It also is guaranteed that the graph edges are given in the order of non-decreasing ui. If there are multiple edges going from vertex ui, then it is guaranteed that these edges are given in the order of increasing vi.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,200
|
train_017.jsonl
|
9d0e595f17f864a648a715287c6138fb
|
256 megabytes
|
["7 8 2\n1 2\n2 3\n3 4\n3 6\n4 5\n4 7\n5 6\n6 7", "7 0 2", "7 2 1\n1 3\n3 5"]
|
PASSED
|
from sys import stdin
N = 10 ** 6
MOD = 10**9 + 7
def task():
n, m, k = map(int, stdin.readline().split())
Sum = [0] * (N + 1)
Power = [0] * (N + 1)
for i in xrange(m):
u, v = map(int, stdin.readline().split())
if v - u == k + 1:
Sum[u - 1] = 1
elif v - u != 1:
print 0
quit()
for i in xrange(n - 1, -1, -1):
Sum[i] += Sum[i + 1]
Power[0] = 1
for i in xrange(1, N + 1):
Power[i] = (Power[i - 1] * 2) % MOD
answer = 0
if not Sum[0]:
answer += 1
for i in xrange(n - k - 1):
if Sum[0] - Sum[i]:
continue
if Sum[i + k + 1]:
continue
answer += Power[min(n - k - 2, i + k) - i - (Sum[i + 1] - Sum[i + k + 1])]
answer %= MOD
print answer
task()
|
1368968400
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3\n3\n2\n0\n2\n7"]
|
6b92f09df1e35edc80cf1cbf8494b41e
|
NoteIn the first test case you can remove the characters with indices $$$6$$$, $$$7$$$, and $$$9$$$ to get an even string "aabbddcc".In the second test case, each character occurs exactly once, so in order to get an even string, you must remove all characters from the string.In the third test case, you can get an even string "aaaabb" by removing, for example, $$$4$$$-th and $$$6$$$-th characters, or a string "aabbbb" by removing the $$$5$$$-th character and any of the first three.
|
A string $$$a=a_1a_2\dots a_n$$$ is called even if it consists of a concatenation (joining) of strings of length $$$2$$$ consisting of the same characters. In other words, a string $$$a$$$ is even if two conditions are satisfied at the same time: its length $$$n$$$ is even; for all odd $$$i$$$ ($$$1 \le i \le n - 1$$$), $$$a_i = a_{i+1}$$$ is satisfied. For example, the following strings are even: "" (empty string), "tt", "aabb", "oooo", and "ttrrrroouuuuuuuukk". The following strings are not even: "aaa", "abab" and "abba".Given a string $$$s$$$ consisting of lowercase Latin letters. Find the minimum number of characters to remove from the string $$$s$$$ to make it even. The deleted characters do not have to be consecutive.
|
For each test case, print a single numberΒ β the minimum number of characters that must be removed to make $$$s$$$ even.
|
The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β βthe number of test cases in the test. The descriptions of the test cases follow. Each test case consists of one string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$Β β the length of the string $$$s$$$. The string consists of lowercase Latin letters. It is guaranteed that the sum of $$$|s|$$$ on all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,300
|
train_105.jsonl
|
34b8409507d7dcce8d490c4f0d4651b0
|
256 megabytes
|
["6\n\naabbdabdccc\n\nzyx\n\naaababbb\n\naabbcc\n\noaoaaaoo\n\nbmefbmuyw"]
|
PASSED
|
import sys
def f(val, ind):
# print(val, ind)
if ind == -1:
return val - 1
if ind >= len(s) - 1:
return val
if s[ind] == s[ind + 1]:
# print(1)
return f(val + 1, ind + 2)
else:
# print(2)
if a[ind + 1][s[ind]] == -1:
val1 = f(val, ind + 1)
else:
val1 = f(val + 1, a[ind + 1][s[ind]] + 1)
val2 = f(val, ind + 1)
return max(val1, val2)
t = int(input())
for _ in range(t):
s = input()
c = {}
ans = [0] * (len(s) + 2)
for i in range(len(s)):
if s[i] not in c:
c[s[i]] = -1
a = [c.copy()]
for i in range(len(s) - 1, -1, -1):
c[s[i]] = i
a.append(c.copy())
a = a[::-1]
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
ans[i + 2] = max(ans[i] + 1, ans[i + 2])
else:
if a[i + 1][s[i]] == -1:
ans[i + 1] = max(ans[i], ans[i + 1])
else:
ans[a[i + 1][s[i]] + 1] = max(ans[i] + 1, ans[a[i + 1][s[i]] + 1])
ans[i + 1] = max(ans[i], ans[i + 1])
# print(a)
# print(ans)
print(len(s) - max(ans) * 2)
# print(len(s) - f(0, 0) * 2)
|
1648737300
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2\n7\n1"]
|
ca157773d06c7d192589218e2aad6431
|
NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$.
|
There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c < h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\dots$$$ and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
|
For each testcase print a single positive integerΒ β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$)Β β the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \le c < h \le 10^6$$$; $$$c \le t \le h$$$)Β β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700
|
train_000.jsonl
|
6b3c8bae79f91499819460ee98300140
|
256 megabytes
|
["3\n30 10 20\n41 15 30\n18 13 18"]
|
PASSED
|
from decimal import *
getcontext().prec = 28
def solve():
if h == c:
return 1
if (h + c) // 2 >= t:
print(2)
return
ans = bs(1, 10 ** 6)
a1 = getdif(ans)
a2 = getdif(ans - 1)
if abs(t - a1) < abs(t - a2):
print(2 * ans - 1)
else:
ans -= 1
print(2 * ans - 1)
return
def bs(l, r):
while l < r:
m = (l + r) // 2
if check(m):
r = m
else:
l = m + 1
return r
def check(hh):
temp = getdif(hh)
# print(hh, ": ", temp)
if temp < t:
return 1
else:
return 0
def getdif(hh):
return Decimal(hh * h + (hh-1) * c) / Decimal(2*hh-1)
# def solve2():
# hc = [0, 0]
# mt = 10**9
# ans = [0, 0]
# for i in range(10**6):
# hc[i&1] += 1
# temp = abs(t- (hc[0] * h + hc[1]*c) / float(hc[0] + hc[1]))
# if temp < mt:
# mt = temp
# ans = list(hc)
# print(sum(ans))
# return
T = int(input())
for _ in range(T):
h, c, t = [int(i) for i in input().split()]
solve()
|
1590676500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["azaz", "-1"]
|
f5451b19cf835b1cb154253fbe4ea6df
| null |
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.
|
Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes).
|
The first input line contains integer k (1ββ€βkββ€β1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1ββ€β|s|ββ€β1000, where |s| is the length of string s.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,000
|
train_017.jsonl
|
316a728e381872f3127868fbe729946d
|
256 megabytes
|
["2\naazz", "3\nabcabcabz"]
|
PASSED
|
from sys import stdin
rr = lambda: stdin.readline().strip()
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
def rry(N = None, f = rri):
for i in xrange(N or rri()):
yield f()
K = rri()
S = rr()
from collections import Counter
count = Counter(S)
if any(v % K for v in count.values()):
print -1
else:
ans = ''
for k,v in count.iteritems():
ans += k * (v/K)
print ans*K
|
1346081400
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["5", "4", "100"]
|
6ffd7ba12fc6afeeeba80a73a8cf7bd1
|
NoteIn the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1,β2,β1,β2,β2]. There are another optimal arrays for this test.In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].
|
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: consider all pairs of numbers x,βy (xββ βy), such that number x occurs in the array a and number y occurs in the array a; for each pair x,βy must exist some position j (1ββ€βjβ<βn), such that at least one of the two conditions are met, either ajβ=βx,βajβ+β1β=βy, or ajβ=βy,βajβ+β1β=βx. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi,βwi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.Help Sereja, find the maximum amount of money he can pay to Dima.
|
In a single line print maximum amount of money (in rubles) Sereja can pay. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
The first line contains two integers n and m (1ββ€βnββ€β2Β·106,β1ββ€βmββ€β105). Next m lines contain pairs of integers. The i-th line contains numbers qi,βwi (1ββ€βqi,βwiββ€β105). It is guaranteed that all qi are distinct.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,000
|
train_023.jsonl
|
60900c19d2f71169e5ebf50b00bffea3
|
256 megabytes
|
["5 2\n1 2\n2 3", "100 3\n1 2\n2 1\n3 1", "1 2\n1 1\n2 100"]
|
PASSED
|
#!/usr/bin/env python
n, m = map(int, raw_input().split())
w = []
for _ in range(m):
_, wi = map(int, raw_input().split())
w.append(wi)
def calc(size, r):
l = 1
while l+1 < r:
v = (l + r) / 2
edges = v * (v-1) / 2
if v % 2 == 0:
edges += v / 2 - 1
if edges < size:
l = v
else:
r = v
return l
v = calc(n, m+1)
#print v
print sum(sorted(w)[::-1][:v])
|
1385479800
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1 3\n2 3", "-1"]
|
084203d057faedd6a793eec38748aaa8
| null |
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1,βa2,β...,βak.Valera's code is given below.ans[i][j] // the shortest distance for a pair of vertexes i,βja[i] // vertexes, marked by Valerafor(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { if (i == j) ans[i][j] = 0; else ans[i][j] = INF; //INF is a very large number }} for(i = 1; i <= m; i++) { read a pair of vertexes u, v that have a non-directed edge between them; ans[u][v] = 1; ans[v][u] = 1;}for (i = 1; i <= k; i++) { v = a[i]; for(j = 1; j <= n; j++) for(r = 1; r <= n; r++) ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);}Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1,βa2,β...,βak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i,βj). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
|
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u,βv β the description of the edges of the graph Valera's been looking for.
|
The first line of the input contains three integers n,βm,βk (3ββ€βnββ€β300, 2ββ€βkββ€βn , ) β the number of vertexes, the number of edges and the number of marked vertexes. The second line of the input contains k space-separated integers a1,βa2,β... ak (1ββ€βaiββ€βn) β the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,200
|
train_024.jsonl
|
b4e9b764957d01118fe02c7c2b3c7538
|
256 megabytes
|
["3 2 2\n1 2", "3 3 2\n1 2"]
|
PASSED
|
import sys
range = xrange
input = raw_input
n,m,k = [int(x) for x in input().split()]
if n == k:
print -1
sys.exit()
A = [int(x) - 1 for x in input().split()]
marked = [0]*n
for a in A:
marked[a] = 1
B = [i for i in range(n) if not marked[i]]
free = B.pop()
a = A.pop() if A else B.pop()
b = A.pop() if A else B.pop()
import itertools
out = []
for j in range(n):
if j != free:
out.append((free, j))
for i in range(n):
if i == free:continue
for j in range(i + 1, n):
if len(out) >= m:
break
if j == free:
continue
if (i == a and j == b) or (i == b and j == a):
continue
if (i == b and marked[j]) or (j == b and marked[i]):
continue
out.append((i,j))
if len(out) == m:
print '\n'.join('%d %d' % (a + 1, b + 1) for a,b in out)
else:
print -1
|
1380641400
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
6 seconds
|
["+ 12 16\n\n- 6 10\n\n* 8 15\n\n/ 5 4\n\nsqrt 16\n\nsqrt 5\n\n^ 6 12\n\n! 2 3 7"]
|
166fbe42dd60317e85e699d9bed76957
|
NoteWe start by reading the first line containing the integer $$$n = 21$$$. Then, we ask for: $$$(12 + 16) \bmod 21 = 28 \bmod 21 = 7$$$. $$$(6 - 10) \bmod 21 = -4 \bmod 21 = 17$$$. $$$(8 \cdot 15) \bmod 21 = 120 \bmod 21 = 15$$$. $$$(5 \cdot 4^{-1}) \bmod 21 = (5 \cdot 16) \bmod 21 = 80 \bmod 21 = 17$$$. Square root of $$$16$$$. The answer is $$$11$$$, as $$$(11 \cdot 11) \bmod 21 = 121 \bmod 21 = 16$$$. Note that the answer may as well be $$$10$$$. Square root of $$$5$$$. There is no $$$x$$$ such that $$$x^2 \bmod 21 = 5$$$, so the output is $$$-1$$$. $$$(6^{12}) \bmod 21 = 2176782336 \bmod 21 = 15$$$. We conclude that our calculator is working, stop fooling around and realise that $$$21 = 3 \cdot 7$$$.
|
Integer factorisation is hard. The RSA Factoring Challenge offered $$$$100\,000$$$ for factoring RSA-$$$1024$$$, a $$$1024$$$-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a $$$1024$$$-bit number.Since your programming language of choice might not offer facilities for handling large integers, we will provide you with a very simple calculator. To use this calculator, you can print queries on the standard output and retrieve the results from the standard input. The operations are as follows: + x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x+y) \bmod n$$$. - x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x-y) \bmod n$$$. * x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x \cdot y) \bmod n$$$. / x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$ and $$$y$$$ is coprime with $$$n$$$. Returns $$$(x \cdot y^{-1}) \bmod n$$$ where $$$y^{-1}$$$ is multiplicative inverse of $$$y$$$ modulo $$$n$$$. If $$$y$$$ is not coprime with $$$n$$$, then $$$-1$$$ is returned instead. sqrt x where $$$x$$$ is integer between $$$0$$$ and $$$n-1$$$ coprime with $$$n$$$. Returns $$$y$$$ such that $$$y^2 \bmod n = x$$$. If there are multiple such integers, only one of them is returned. If there are none, $$$-1$$$ is returned instead. ^ x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$${x^y \bmod n}$$$. Find the factorisation of $$$n$$$ that is a product of between $$$2$$$ and $$$10$$$ distinct prime numbers, all of form $$$4x + 3$$$ for some integer $$$x$$$.Because of technical issues, we restrict number of requests to $$$100$$$.
|
You can print as many queries as you wish, adhering to the time limit (see the Interaction section for more details). When you think you know the answer, output a single line of form ! k p_1 p_2 ... p_k, where $$$k$$$ is the number of prime factors of $$$n$$$, and $$$p_i$$$ are the distinct prime factors. You may print the factors in any order. Hacks input For hacks, use the following format:. The first should contain $$$k$$$ ($$$2 \leq k \leq 10$$$)Β β the number of prime factors of $$$n$$$. The second should contain $$$k$$$ space separated integers $$$p_1, p_2, \dots, p_k$$$ ($$$21 \leq n \leq 2^{1024}$$$)Β β the prime factors of $$$n$$$. All prime factors have to be of form $$$4x + 3$$$ for some integer $$$x$$$. They all have to be distinct.
|
The only line contains a single integer $$$n$$$Β ($$$21 \leq n \leq 2^{1024}$$$). It is guaranteed that $$$n$$$ is a product of between $$$2$$$ and $$$10$$$ distinct prime numbers, all of form $$$4x + 3$$$ for some integer $$$x$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 3,200
|
train_003.jsonl
|
71cd896d09a297825b4fff80b3d25557
|
256 megabytes
|
["21\n\n7\n\n17\n\n15\n\n17\n\n11\n\n-1\n\n15"]
|
PASSED
|
import random
import math
n = int(input())
z = [n]
for i in range(15):
w = random.randint(1, n - 1)
print('sqrt', w * w % n)
v = int(input())
y = []
for x in z:
y.append(math.gcd(w+v, x))
y.append(x // y[-1])
z = y
z = list(set(z) - {1})
print('!', len(z), *z)
|
1546180500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["7\n8\n62"]
|
a5063294f814f359f7ab6b7b801eaf3e
|
NoteThe trees in the example: In the first test case, one possible assignment is $$$a = \{1, 8\}$$$ which results in $$$|1 - 8| = 7$$$.In the second test case, one of the possible assignments is $$$a = \{1, 5, 9\}$$$ which results in a beauty of $$$|1 - 5| + |5 - 9| = 8$$$
|
Parsa has a humongous tree on $$$n$$$ vertices.On each vertex $$$v$$$ he has written two integers $$$l_v$$$ and $$$r_v$$$.To make Parsa's tree look even more majestic, Nima wants to assign a number $$$a_v$$$ ($$$l_v \le a_v \le r_v$$$) to each vertex $$$v$$$ such that the beauty of Parsa's tree is maximized.Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of $$$|a_u - a_v|$$$ over all edges $$$(u, v)$$$ of the tree.Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
|
For each test case print the maximum possible beauty for Parsa's tree.
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 250)$$$ β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 10^5)$$$ β the number of vertices in Parsa's tree. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ $$$(1 \le u , v \le n, u\neq v)$$$ meaning that there is an edge between the vertices $$$u$$$ and $$$v$$$ in Parsa's tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,600
|
train_085.jsonl
|
b0cb01779c918672f785fe547ac56ba5
|
256 megabytes
|
["3\n2\n1 6\n3 8\n1 2\n3\n1 3\n4 6\n7 9\n1 2\n2 3\n6\n3 14\n12 20\n12 19\n2 12\n10 17\n3 17\n3 2\n6 5\n1 5\n2 6\n4 6"]
|
PASSED
|
import sys
sys.setrecursionlimit(10 ** 5)
input = sys.stdin.buffer.readline
def dfs(par, x):
for u in g[x]:
if u == par:
continue
dfs(x, u)
dp[par][0] += max(abs(a[par][0] - a[x][0]) + dp[x][0], abs(a[par][0] - a[x][1]) + dp[x][1])
dp[par][1] += max(abs(a[par][1] - a[x][0]) + dp[x][0], abs(a[par][1] - a[x][1]) + dp[x][1])
for _ in range(int(input())):
n = int(input())
g = [[] for _ in range(n)]
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
for _ in range(n - 1):
u, v = map(int, input().split())
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
dp = [[0.0, 0.0] for _ in range(n)]
for p in g[0]:
dfs(0, p)
print(int(max(dp[0][0], dp[0][1])))
|
1621866900
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["-1", "10080"]
|
386345016773a06b9e190a55cc3717fa
| null |
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.
|
Print a single integer β the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.
|
A single input line contains a single integer n (1ββ€βnββ€β105).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,400
|
train_014.jsonl
|
b3ef0372713c31683c2872ffcc86a064
|
256 megabytes
|
["1", "5"]
|
PASSED
|
n = input()
if n < 3:
print '-1'
elif n == 3:
print 210
else :
x = pow(10, n - 1, 210)
y = 210 - x
print '1' + '0' * (n - 4) + "%03d" %y
|
1353857400
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["1\n2\n25\n26\n27\n649\n650"]
|
2e3006d663a3c7ad3781aba1e37be3ca
| null |
The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold: the first letter of $$$a$$$ is less than the first letter of $$$b$$$; the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that: Word $$$1$$$: ab Word $$$2$$$: ac ... Word $$$25$$$: az Word $$$26$$$: ba Word $$$27$$$: bc ... Word $$$649$$$: zx Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.
|
For each test case, print one integerΒ β the index of the word $$$s$$$ in the dictionary.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 650$$$)Β β the number of test cases. Each test case consists of one line containing $$$s$$$Β β a string consisting of exactly two different lowercase Latin letters (i.βe. a correct word of the Berland language).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800
|
train_107.jsonl
|
74c29a63fdbf6d8dd61daee63c626541
|
512 megabytes
|
["7\n\nab\n\nac\n\naz\n\nba\n\nbc\n\nzx\n\nzy"]
|
PASSED
|
n = int(input())
li = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
di = {}
y = 1
for i in li:
for j in li:
if i != j:
di[i+j]=y
y += 1
for i in range(n):
print(di[input()])
|
1651502100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["7\n3\n3"]
|
7f502f2fd150a2ded948826960d123cd
|
NoteIn the first sample, two obstacles are at $$$(1, 2)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(2, 2)$$$ to $$$(2, 3)$$$, then to $$$(1, 3)$$$. The total cost is $$$u+v = 7$$$ coins. In the second sample, two obstacles are at $$$(1, 3)$$$ and $$$(2,2)$$$. You can move the obstacle on $$$(1, 3)$$$ to $$$(2, 3)$$$. The cost is $$$u = 3$$$ coins.
|
There is a graph of $$$n$$$ rows and $$$10^6 + 2$$$ columns, where rows are numbered from $$$1$$$ to $$$n$$$ and columns from $$$0$$$ to $$$10^6 + 1$$$: Let's denote the node in the row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$.Initially for each $$$i$$$ the $$$i$$$-th row has exactly one obstacle β at node $$$(i, a_i)$$$. You want to move some obstacles so that you can reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $$$u$$$ or $$$v$$$ coins, as below: If there is an obstacle in the node $$$(i, j)$$$, you can use $$$u$$$ coins to move it to $$$(i-1, j)$$$ or $$$(i+1, j)$$$, if such node exists and if there is no obstacle in that node currently. If there is an obstacle in the node $$$(i, j)$$$, you can use $$$v$$$ coins to move it to $$$(i, j-1)$$$ or $$$(i, j+1)$$$, if such node exists and if there is no obstacle in that node currently. Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $$$(1,1)$$$ to $$$(0,1)$$$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles.
|
For each test case, output a single integerΒ β the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles. It can be shown that under the constraints of the problem there is always a way to make such a trip possible.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$u$$$ and $$$v$$$ ($$$2 \le n \le 100$$$, $$$1 \le u, v \le 10^9$$$)Β β the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$)Β β where $$$a_i$$$ represents that the obstacle in the $$$i$$$-th row is in node $$$(i, a_i)$$$. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^4$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200
|
train_095.jsonl
|
22cd544adf02bb97ee02689e0a5db6bb
|
256 megabytes
|
["3\n2 3 4\n2 2\n2 3 4\n3 2\n2 4 3\n3 2"]
|
PASSED
|
import os , sys,time, collections , math , pprint , itertools as it , operator as op , bisect as bs ,functools as fn
maxx , localsys , mod = float('inf'), 0 , int(1e9 + 7)
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
ceil = lambda n , x: (n+x -1 )//x
osi, oso = '/home/priyanshu/Documents/cp/input.txt','/home/priyanshu/Documents/cp/output.txt'
if os.path.exists(osi):
sys.stdin = open(osi, 'r') ; sys.stdout = open(oso, 'w')
input = sys.stdin.readline
def maps():return map(int , input().split())
for _ in range(int(input())):
n , u , v = maps() ; a = list(maps())
b = sorted([abs(a[i] - a[i-1]) for i in range(1,n)])
print(0 if b[-1] > 1 else min(u,v) if 1 in b else v + min(u,v))
|
1614519300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n3"]
|
eb39ac8d703516c7f81f95a989791b21
|
NoteFor $$$3\times3$$$ grid ponies can make two following moves:
|
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.
|
For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games. Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800
|
train_007.jsonl
|
2357f95e7ad23c982013a9dabec70963
|
256 megabytes
|
["2\n3\n4"]
|
PASSED
|
for t in range(int(input())):
a = int(input())
if (a == 1 or a == 2):
print(a)
else:
print(2+(a-2)//2)
|
1596810900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nYES"]
|
fc547fc83ebbcc3c058a069ef9fef62c
|
NoteIn the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings.
|
You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains: $$$a$$$ letters 'A'; $$$b$$$ letters 'B'; $$$c$$$ letters 'C'; no other letters; exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one).
|
For each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)Β β the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcaseΒ β four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \le a, b, c \le 10^8$$$; $$$0 \le m \le 10^8$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100
|
train_088.jsonl
|
590beb65e026817c7e8fe435606309e8
|
256 megabytes
|
["3\n2 2 1 0\n1 1 1 1\n1 2 3 2"]
|
PASSED
|
for t in range(int(input())):
a,b,c,d=map(int,input().split())
l=[a,b,c];l.sort();m=l[2]-(l[0]+l[1])
n=0 if m<=0 else m-1
q="YES" if n<=d and sum(l)-3>=d else "NO"
print(q)
|
1632148500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["0\n1 2\n2 3 5\n1 2 5\n3 2 3 4\n1 4\n-1"]
|
c313a305cc229ec23b19c6e4dd46b57b
|
NoteIn the first test case, $$$b$$$ is empty. So string $$$s$$$ is not changed. Now $$$s^p = s_1 s_2 = \mathtt{10}$$$, and $$$s^q = s_3s_4 = \mathtt{10}$$$.In the second test case, $$$b=[3,5]$$$. Initially $$$s_3=\mathtt{0}$$$, and $$$s_5=\mathtt{1}$$$. On performing the operation, we simultaneously set $$$s_3=\mathtt{1}$$$, and $$$s_5=\mathtt{0}$$$.So $$$s$$$ is updated to 101000 on performing the operation.Now if we take characters at indices $$$[1,2,5]$$$ in $$$s^p$$$, we get $$$s_1=\mathtt{100}$$$. Also characters at indices $$$[3,4,6]$$$ are in $$$s^q$$$. Thus $$$s^q=100$$$. We are done as $$$s^p=s^q$$$.In fourth test case, it can be proved that it is not possible to partition the string after performing any operation.
|
Everool has a binary string $$$s$$$ of length $$$2n$$$. Note that a binary string is a string consisting of only characters $$$0$$$ and $$$1$$$. He wants to partition $$$s$$$ into two disjoint equal subsequences. He needs your help to do it.You are allowed to do the following operation exactly once. You can choose any subsequence (possibly empty) of $$$s$$$ and rotate it right by one position. In other words, you can select a sequence of indices $$$b_1, b_2, \ldots, b_m$$$, where $$$1 \le b_1 < b_2 < \ldots < b_m \le 2n$$$. After that you simultaneously set $$$$$$s_{b_1} := s_{b_m},$$$$$$ $$$$$$s_{b_2} := s_{b_1},$$$$$$ $$$$$$\ldots,$$$$$$ $$$$$$s_{b_m} := s_{b_{m-1}}.$$$$$$Can you partition $$$s$$$ into two disjoint equal subsequences after performing the allowed operation exactly once?A partition of $$$s$$$ into two disjoint equal subsequences $$$s^p$$$ and $$$s^q$$$ is two increasing arrays of indices $$$p_1, p_2, \ldots, p_n$$$ and $$$q_1, q_2, \ldots, q_n$$$, such that each integer from $$$1$$$ to $$$2n$$$ is encountered in either $$$p$$$ or $$$q$$$ exactly once, $$$s^p = s_{p_1} s_{p_2} \ldots s_{p_n}$$$, $$$s^q = s_{q_1} s_{q_2} \ldots s_{q_n}$$$, and $$$s^p = s^q$$$.If it is not possible to partition after performing any kind of operation, report $$$-1$$$. If it is possible to do the operation and partition $$$s$$$ into two disjoint subsequences $$$s^p$$$ and $$$s^q$$$, such that $$$s^p = s^q$$$, print elements of $$$b$$$ and indices of $$$s^p$$$, i.Β e. the values $$$p_1, p_2, \ldots, p_n$$$.
|
For each test case, follow the following output format. If there is no solution, print $$$-1$$$. Otherwise, In the first line, print an integer $$$m$$$ ($$$0 \leq m \leq 2n$$$), followed by $$$m$$$ distinct indices $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$(in increasing order). In the second line, print $$$n$$$ distinct indices $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (in increasing order). If there are multiple solutions, print any.
|
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 \le n \le 10^5$$$), where $$$2n$$$ is the length of the binary string. The second line of each test case contains the binary string $$$s$$$ of length $$$2n$$$. 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
| 2,200
|
train_103.jsonl
|
be6c1a1808a62a937b0204125c30db6c
|
256 megabytes
|
["4\n2\n1010\n3\n100010\n2\n1111\n2\n1110"]
|
PASSED
|
import sys
import copy
input = sys.stdin.readline
print = sys.stdout.write
for i in range(int(input())):
a = int(input())
b = list(input().strip())
stat = 0
for i in range(len(b)):
if b[i] == "1":
stat+=1
if stat%2 == 1:
print("-1\n")
continue
tb = copy.deepcopy(b)
curans1 = 0
ans1 = []
ans2 = []
currentused = []
stat = (-1,-1)
count0 = 0
count1 = 0
for i in range(0,len(b),2):
ans1.append(str(i+1))
if b[i] == b[i+1]:
continue
if stat[0] == -1:
stat = (i,i+1)
else:
if b[stat[0]] == '0':
cur1 = stat[0]
else:
cur1 = stat[1]
if b[i] == '1':
cur2 = i
else:
cur2 = i+1
currentused.append(str(cur1+1))
currentused.append(str(cur2+1))
b[cur1] = "1"
b[cur2] = "0"
stat = (-1,-1)
if len(currentused) == 0:
print("0\n")
else:
print(str(len(currentused))+" ")
print(" ".join(currentused)+'\n')
print(" ".join(ans1)+"\n")
|
1665412500
|
[
"geometry",
"strings"
] |
[
0,
1,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["1.75", "12", "3.141592"]
|
89ef92879ce322251c9734b22a413d36
|
NoteIn the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
|
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2Nβ-β1 games, numbered starting from 1. In game i, team 2Β·iβ-β1 will play against team 2Β·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2Β·iβ-β1 will play against the winner of the previous round's game 2Β·i.Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2Nβ-β1 points.For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
|
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10β-β9. Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if .
|
Input will begin with a line containing N (2ββ€βNββ€β6). 2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless iβ=βj, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,100
|
train_009.jsonl
|
fe69a3ad2a471eb90fa8197125a83674
|
256 megabytes
|
["2\n0 40 100 100\n60 0 40 40\n0 60 0 45\n0 60 55 0", "3\n0 0 100 0 100 0 0 0\n100 0 100 0 0 0 100 100\n0 0 0 100 100 0 0 0\n100 100 0 0 0 0 100 100\n0 100 0 100 0 0 100 0\n100 100 100 100 100 0 0 0\n100 0 100 0 0 100 0 0\n100 0 100 0 100 100 100 0", "2\n0 21 41 26\n79 0 97 33\n59 3 0 91\n74 67 9 0"]
|
PASSED
|
import sys
N = int(sys.stdin.readline())
P = []
for i in range(2 ** N) :
P.append([int(x)/100. for x in sys.stdin.readline().split()])
Prounds = [[1 for i in range(2**N)] for j in range(N+1) ]
rounds = [[0 for i in range(2**N)] for j in range(N+1) ]
for i in range(1, N+1) :
for player_a in range(2 ** N) :
top = int(player_a / (2 ** i)) * (2 ** i)
bottom = top + (2 ** i)
mid = bottom - (2 ** (i - 1))
Prounds[i][player_a] = Prounds[i-1][player_a] * sum([P[player_a][player_b]*Prounds[i-1][player_b] for player_b in (range(mid, bottom) if player_a < mid else range(top, mid))])
rounds[i][player_a] = max([rounds[i-1][player_a] + rounds[i-1][player_b] + (2 ** (i-1))*Prounds[i][player_a] for player_b in (range(mid, bottom) if player_a < mid else range(top, mid))])
print max(rounds[N])
|
1505583300
|
[
"probabilities",
"trees"
] |
[
0,
0,
0,
0,
0,
1,
0,
1
] |
|
2 seconds
|
["2\n4\n1\n11"]
|
3888f8d6cce7037169c340a9fb508cbe
| null |
Given an undirected connected graph with $$$n$$$ vertices and $$$m$$$ edges. The graph contains no loops (edges from a vertex to itself) and multiple edges (i.e. no more than one edge between each pair of vertices). The vertices of the graph are numbered from $$$1$$$ to $$$n$$$. Find the number of paths from a vertex $$$s$$$ to $$$t$$$ whose length differs from the shortest path from $$$s$$$ to $$$t$$$ by no more than $$$1$$$. It is necessary to consider all suitable paths, even if they pass through the same vertex or edge more than once (i.e. they are not simple). Graph consisting of $$$6$$$ of vertices and $$$8$$$ of edges For example, let $$$n = 6$$$, $$$m = 8$$$, $$$s = 6$$$ and $$$t = 1$$$, and let the graph look like the figure above. Then the length of the shortest path from $$$s$$$ to $$$t$$$ is $$$1$$$. Consider all paths whose length is at most $$$1 + 1 = 2$$$. $$$6 \rightarrow 1$$$. The length of the path is $$$1$$$. $$$6 \rightarrow 4 \rightarrow 1$$$. Path length is $$$2$$$. $$$6 \rightarrow 2 \rightarrow 1$$$. Path length is $$$2$$$. $$$6 \rightarrow 5 \rightarrow 1$$$. Path length is $$$2$$$. There is a total of $$$4$$$ of matching paths.
|
For each test case, output a single numberΒ β the number of paths from $$$s$$$ to $$$t$$$ such that their length differs from the length of the shortest path by no more than $$$1$$$. Since this number may be too large, output it modulo $$$10^9 + 7$$$.
|
The first line of test contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$)Β βthe number of test cases in the test. Before each test case, there is a blank line. The first line of test case contains two numbers $$$n, m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$)Β βthe number of vertices and edges in the graph. The second line contains two numbers $$$s$$$ and $$$t$$$ ($$$1 \le s, t \le n$$$, $$$s \neq t$$$)Β βthe numbers of the start and end vertices of the path. The following $$$m$$$ lines contain descriptions of edges: the $$$i$$$th line contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i,v_i \le n$$$)Β β the numbers of vertices that connect the $$$i$$$th edge. It is guaranteed that the graph is connected and does not contain loops and multiple edges. It is guaranteed that the sum of values $$$n$$$ on all test cases of input data does not exceed $$$2 \cdot 10^5$$$. Similarly, it is guaranteed that the sum of values $$$m$$$ on all test cases of input data does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100
|
train_104.jsonl
|
d7d90b128bd0c728500ef76b96431ae5
|
256 megabytes
|
["4\n\n\n\n\n4 4\n\n1 4\n\n1 2\n\n3 4\n\n2 3\n\n2 4\n\n\n\n\n6 8\n\n6 1\n\n1 4\n\n1 6\n\n1 5\n\n1 2\n\n5 6\n\n4 6\n\n6 3\n\n2 6\n\n\n\n\n5 6\n\n1 3\n\n3 5\n\n5 4\n\n3 1\n\n4 2\n\n2 1\n\n1 4\n\n\n\n\n8 18\n\n5 1\n\n2 1\n\n3 1\n\n4 2\n\n5 2\n\n6 5\n\n7 3\n\n8 4\n\n6 4\n\n8 7\n\n1 4\n\n4 7\n\n1 6\n\n6 7\n\n3 8\n\n8 5\n\n4 5\n\n4 3\n\n8 2"]
|
PASSED
|
import copy
import io, os, sys
from sys import stdin, stdout
def input(): return stdin.readline().rstrip("\r\n")
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())
from itertools import permutations, chain, combinations, product
from math import factorial, gcd, inf
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from bisect import bisect_left
from functools import lru_cache
INF_INT32 = 1 << 32
INF_INT = INF_INT64 = 1 << 64
MOD = 1000000007
### CODE HERE
# f = open('inputs', 'r')
# def input(): return f.readline().rstrip("\r\n")
for _ in range(read_int()):
input()
n, m = read_int_tuple()
s, t = read_int_tuple()
s, t = s - 1, t - 1
edges = [[] for _ in range(n + n)]
for _ in range(m):
u, v = read_int_tuple()
u, v = u - 1, v - 1
edges[u].append(v + n)
edges[v].append(u + n)
edges[u + n].append(v)
edges[v + n].append(u)
dist = [INF_INT] * (n + n)
dist[s] = 0
cnt = [0] * (n + n)
cnt[s] = 1
q = deque([s])
min_dist_t = INF_INT
while q:
u = q.popleft()
if u == t or u == t + n:
min_dist_t = min(min_dist_t, dist[u])
if dist[u] > min_dist_t + 1:
break
for v in edges[u]:
if dist[v] <= dist[u]: continue
if dist[v] > dist[u] + 1:
dist[v] = dist[u] + 1
cnt[v] = cnt[u]
q.append(v)
elif dist[v] == dist[u] + 1:
cnt[v] += cnt[u]
cnt[v] %= MOD
if abs(dist[t] - dist[t + n]) <= 1:
print((cnt[t] + cnt[t + n]) % MOD)
elif dist[t] < dist[t + n]:
print(cnt[t])
else:
print(cnt[t + n])
|
1646750100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["29\n23\n35\n25\n35"]
|
d70a774248d9137c30f33fb37c6467a7
|
NoteAfter the first query $$$a$$$ is equal to $$$[1, 2, 2, 4, 5]$$$, and the answer is $$$29$$$ because we can split each of the subsegments the following way: $$$[1; 1]$$$: $$$[1]$$$, 1 block; $$$[1; 2]$$$: $$$[1] + [2]$$$, 2 blocks; $$$[1; 3]$$$: $$$[1] + [2, 2]$$$, 2 blocks; $$$[1; 4]$$$: $$$[1] + [2, 2] + [4]$$$, 3 blocks; $$$[1; 5]$$$: $$$[1] + [2, 2] + [4] + [5]$$$, 4 blocks; $$$[2; 2]$$$: $$$[2]$$$, 1 block; $$$[2; 3]$$$: $$$[2, 2]$$$, 1 block; $$$[2; 4]$$$: $$$[2, 2] + [4]$$$, 2 blocks; $$$[2; 5]$$$: $$$[2, 2] + [4] + [5]$$$, 3 blocks; $$$[3; 3]$$$: $$$[2]$$$, 1 block; $$$[3; 4]$$$: $$$[2] + [4]$$$, 2 blocks; $$$[3; 5]$$$: $$$[2] + [4] + [5]$$$, 3 blocks; $$$[4; 4]$$$: $$$[4]$$$, 1 block; $$$[4; 5]$$$: $$$[4] + [5]$$$, 2 blocks; $$$[5; 5]$$$: $$$[5]$$$, 1 block; which is $$$1 + 2 + 2 + 3 + 4 + 1 + 1 + 2 + 3 + 1 + 2 + 3 + 1 + 2 + 1 = 29$$$ in total.
|
Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array $$$[1, 1, 1]$$$ is $$$1$$$; $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$; $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.
|
Print the answer to each query on a new line.
|
In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700
|
train_082.jsonl
|
83495944839b5011b7b1c6873e738bce
|
256 megabytes
|
["5 5\n1 2 3 4 5\n3 2\n4 2\n3 1\n2 1\n2 2"]
|
PASSED
|
import sys
a = list(map(int, sys.stdin.readline().split()))
n = a[0]
m = a[1]
a = list(map(int, sys.stdin.readline().split()))
count = 0
s = []
for i in range(n):
if i == 0:
s.append(0)
elif a[i] == a[i - 1]:
s.append(0)
elif a[i] != a[i - 1]:
s.append(1)
count = n * (n + 1) // 2
z1 = [0] * n
for i in range(n):
if n % 2 == 0:
if i + 1 <= (n // 2):
z1[i] = (i + 1) * (n - i) - 1
else:
z1[i] = (n - i) * (i + 1) - 1
else:
if i + 1 <= (n // 2 + 1):
z1[i] = (i + 1) * (n - i) - 1
else:
z1[i] = (n - i) * (i + 1) - 1
for i in range(n):
if s[i] == 1:
count -= (n - 1 - i)
count += z1[i]
for _ in range(m):
p = list(map(int, sys.stdin.readline().split()))
x = p[0] - 1
y = p[1]
if n == 1:
count += 0
elif x == 0:
if a[x] == y:
count += 0
elif a[x] != a[x + 1] and a[x + 1] != y:
count += 0
elif a[x] != a[x + 1] and a[x + 1] == y:
count += (1 - n)
elif a[x] == a[x + 1] and a[x + 1] != y:
count += (n - 1)
elif x == n - 1:
if a[x] == y:
count += 0
elif a[x] != a[x - 1] and a[x - 1] != y:
count += 0
elif a[x] != a[x - 1] and a[x - 1] == y:
count += (1 - n)
elif a[x] == a[x - 1] and a[x - 1] != y:
count += (n - 1)
else:
if a[x] == y:
count += 0
elif a[x] != a[x - 1] and a[x] != a[x + 1]:
if a[x - 1] != y and a[x + 1] != y:
count += 0
elif a[x - 1] != y and a[x + 1] == y:
count += (-z1[x] + x)
elif a[x - 1] == y and a[x + 1] != y:
count += (-z1[x] + (n - x - 1))
elif a[x - 1] == y and a[x + 1] == y:
count += ((n - 1) * (-1) + (z1[x] - n + 1) * (-2))
elif a[x] == a[x - 1] and a[x] == a[x + 1]:
if a[x - 1] != y and a[x + 1] != y:
count += ((n - 1) * (1) + (z1[x] - n + 1) * (2))
elif a[x] != a[x - 1] and a[x] == a[x + 1]:
if a[x - 1] != y and a[x + 1] != y:
count += (z1[x] - x)
elif a[x - 1] == y and a[x + 1] != y:
count += (n - x - 1 - x)
elif a[x] == a[x - 1] and a[x] != a[x + 1]:
if a[x - 1] != y and a[x + 1] != y:
count += (z1[x] - n + x + 1)
elif a[x - 1] != y and a[x + 1] == y:
count += (x - n + x + 1)
a[x] = y
print(count)
|
1661006100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["b\nazaz\nby"]
|
c02357c4d959e300f970f66f9b3107eb
|
NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
|
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
|
For each test case, print the final string in a single line.
|
Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$) Β β the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \leq |s| \leq 50$$$) consisting of lowercase English letters.
|
standard output
|
standard input
|
Python 3
|
Python
| 800
|
train_101.jsonl
|
1bc25b74f2fb82300de7d89b1392d18b
|
512 megabytes
|
["3\na\nbbbb\naz"]
|
PASSED
|
t = int(input())
while t > 0:
s = str(input())
arr = []
for i in range(len(s)):
if i % 2 == 0 and s[i] != 'a':
arr.append('a')
elif i % 2 == 0 and s[i] == 'a':
arr.append('b')
elif i % 2 == 1 and s[i] != 'z':
arr.append('z')
elif i % 2 == 1 and s[i] == 'z':
arr.append('y')
print(''.join(arr))
t = t-1
|
1612708500
|
[
"games",
"strings"
] |
[
1,
0,
0,
0,
0,
0,
1,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.