src_uid stringlengths 32 32 | prob_desc_description stringlengths 63 2.99k | tags stringlengths 6 159 | source_code stringlengths 29 58.4k | lang_cluster stringclasses 1 value | categories listlengths 1 5 | desc_length int64 63 3.13k | code_length int64 29 58.4k | games int64 0 1 | geometry int64 0 1 | graphs int64 0 1 | math int64 0 1 | number theory int64 0 1 | probabilities int64 0 1 | strings int64 0 1 | trees int64 0 1 | labels_dict dict | __index_level_0__ int64 0 4.98k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acb7acc82c52db801f515631dca20eba | You are given an array a consisting of n integers a_1, a_2, \dots, a_n.Your problem is to find such pair of indices i, j (1 \le i < j \le n) that lcm(a_i, a_j) is minimum possible.lcm(x, y) is the least common multiple of x and y (minimum positive number such that both x and y are divisors of this number). | ['number theory', 'greedy', 'math', 'brute force'] | import math
import re
import sys
from collections import defaultdict
def read(type = int):
return type(raw_input())
def read_list(type = int, split = ' ', F = None):
if F:
return map(lambda x: F(type(x)), raw_input().split(split))
return map(type, raw_input().split(split))
def read_list_of_list(N, type = int, split = ' ', F = None):
return [read_list(type, F = F) for _ in xrange(N)]
def solve():
N = read()
A = read_list()
C = {}
X = 3163
E = [1]*X
P = []
p = 2
while p < X:
if E[p]:
P += [p]
x = p
while x<X:
E[x] = 0
x += p
p += 1
LP = len(P)
Cm = {}
CM = {}
M = 1e30
for a in sorted(A):
if a >= M:
break
b = a
D = set([1])
p = 0
while a and p < LP:
while a%P[p]==0:
D.update(set(d*P[p] for d in D))
a /= P[p]
p += 1
if a > 1:
D.update(set(d*a for d in D))
for d in D:
if d not in Cm:
Cm[d] = b
elif d not in CM:
CM[d] = b
if M > Cm[d]*CM[d]/d:
x, y = Cm[d], CM[d]
M = Cm[d] * CM[d] / d
l1 = A.index(x)
if x==y:
l2 = l1 + 1 + A[l1+1:].index(y)
else:
l2 = A.index(y)
l1 += 1
l2 += 1
if l1<l2:
print l1,l2
else:
print l2,l1
solve() | Python | [
"math",
"number theory"
] | 376 | 1,316 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 796 |
8c464cc6c9d012156828f5e3c250ac20 | Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino."See? The clouds are coming." Kanno gazes into the distance."That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is 0.There are n clouds floating in the sky. Each cloud has the same length l. The i-th initially covers the range of (x_i, x_i + l) (endpoints excluded). Initially, it moves at a velocity of v_i, which equals either 1 or -1.Furthermore, no pair of clouds intersect initially, that is, for all 1 \leq i \lt j \leq n, \lvert x_i - x_j \rvert \geq l.With a wind velocity of w, the velocity of the i-th cloud becomes v_i + w. That is, its coordinate increases by v_i + w during each unit of time. Note that the wind can be strong and clouds can change their direction.You are to help Mino count the number of pairs (i, j) (i < j), such that with a proper choice of wind velocity w not exceeding w_\mathrm{max} in absolute value (possibly negative and/or fractional), the i-th and j-th clouds both cover the moon at the same future moment. This w doesn't need to be the same across different pairs. | ['geometry', 'two pointers', 'math', 'sortings', 'binary search'] | def solve(xs, vs, l, wmax):
assert wmax >= 1
assert l >= 1
n = len(xs)
assert len(vs) == n >= 1
poss = [i for i in xrange(n) if vs[i] == +1]
negs = [i for i in xrange(n) if vs[i] == -1]
poss = sorted([-xs[i] for i in poss])
negs = sorted([xs[i] + l for i in negs])
ans = 0
for x1 in poss:
if wmax == 1 and x1 <= 0: continue
lf = max(-x1, (x1 * (1 - wmax)) / (wmax + 1))
if wmax != 1:
lf = max(lf, -x1 * (wmax + 1) / (wmax - 1))
L = -1
R = len(negs)
while R - L > 1:
M = L + R >> 1
if negs[M] <= lf:
L = M
else:
R = M
ans += len(negs) - R
return ans
n, l, wmax = map(int, raw_input().split())
xs = []
vs = []
for i in xrange(n):
x, v = map(int, raw_input().split())
xs.append(x)
vs.append(v)
print solve(xs, vs, l, wmax) | Python | [
"math",
"geometry"
] | 1,452 | 911 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,742 |
a6b6d9ff2ac5c367c00a64a387cc9e36 | Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers (a, b) exist, where 1 \leq a, b \leq n, for which \frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3.In this problem, \operatorname{gcd}(a, b) denotes the greatest common divisor of the numbers a and b, and \operatorname{lcm}(a, b) denotes the smallest common multiple of the numbers a and b. | ['math', 'number theory'] | import math
t = int(input())
for _ in range(t):
n = int(input())
c = 0
c = n + 2*(n//2) + 2*(n//3)
print(c) | Python | [
"math",
"number theory"
] | 454 | 129 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,420 |
915c26f2bc1005d70cc8cc74ce40b9fa | During their training for the ICPC competitions, team "Jee You See" stumbled upon a very basic counting problem. After many "Wrong answer" verdicts, they finally decided to give up and destroy turn-off the PC. Now they want your help in up-solving the problem.You are given 4 integers n, l, r, and z. Count the number of arrays a of length n containing non-negative integers such that: l\le a_1+a_2+\ldots+a_n\le r, and a_1\oplus a_2 \oplus \ldots\oplus a_n=z, where \oplus denotes the bitwise XOR operation. Since the answer can be large, print it modulo 10^9+7. | ['bitmasks', 'combinatorics', 'dp'] | import sys
sys.setrecursionlimit(2000)
# ---------------------------------------- fast io ----------------------------------------
import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ---------------------------------------- fast io ----------------------------------------
mod = 10 ** 9 + 7
comb = [[-1] * (1001) for _ in range(1001)]
def nCi(n, i):
if i == 0:
comb[n][i] = 1
return 1
if n == 0:
comb[n][i] = 0
return 0
if comb[n][i] != -1:
return comb[n][i]
comb[n][i] = (nCi(n - 1, i) + nCi(n - 1, i - 1)) % mod
return comb[n][i]
for i in range(1001):
nCi(1000,i)
def compute(x):
f = [[-1 for _ in range(2001)] for _ in range(61)]
def dfs(idx, k, r):
if k > 2000:
k = 2000
if k < 0:
return 0
if idx == -1:
return 1
if f[idx][k] != -1:
return f[idx][k]
ans = 0
cb = int((z & (1 << idx)) > 0)
for i in range(cb, n + 1, 2):
bcb = int((r & (1 << idx)) > 0)
ans += nCi(n,i) * dfs(idx - 1, 2 * (k - i + bcb), r)
ans %= mod
f[idx][k] = ans
return f[idx][k]
res = dfs(60, 0, x)
return res
n,l,r,z=[int(x) for x in input().split()]
ans = (compute(r) - compute(l - 1) + mod) % mod
print(ans)
| Python | [
"math"
] | 625 | 3,105 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,284 |
6fcd8713af5a108d590bc99da314cded | Let f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3} for x \ge 4.You have given integers n, f_{1}, f_{2}, f_{3}, and c. Find f_{n} \bmod (10^{9}+7). | ['dp', 'number theory', 'math', 'matrices'] | def mat_mul(a, b):
n, m, p = len(a), len(b), len(b[0])
res = [[0]*p for _ in range(n)]
for i in range(n):
for j in range(p):
for k in range(m):
res[i][j] += a[i][k]*b[k][j]
res[i][j] %= 1000000006
return res
def mat_pow(a, n):
if n == 1: return a
if n%2 == 1: return mat_mul(mat_pow(a, n-1), a)
t = mat_pow(a, n//2)
return mat_mul(t, t)
n, f1, f2, f3, c = map(int, input().split())
m1 = [[3, 1000000004, 0, 1000000005, 1], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]]
m2 = [[2], [0], [0], [0], [0]]
t1 = pow(c, mat_mul(mat_pow(m1, n), m2)[-1][0], 1000000007)
m1 = [[0, 0, 1], [1, 0, 1], [0, 1, 1]]
m2 = [[1], [0], [0]]
m3 = mat_mul(mat_pow(m1, n-1), m2)
t2 = pow(f1, m3[0][0], 1000000007)
t3 = pow(f2, m3[1][0], 1000000007)
t4 = pow(f3, m3[2][0], 1000000007)
print(t1*t2*t3*t4%1000000007) | Python | [
"number theory",
"math"
] | 206 | 899 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 20 |
2df2d5368f467e0427b1f6f57192e2ee | A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.Calculate the expected total number of inversions in the resulting valid permutation.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0. Report the value of P \cdot Q^{-1} \pmod {998244353}. | ['dp', 'probabilities', 'math'] | def merge(a,b):
inda=0
indb=0
lena=len(a)
lenb=len(b)
d=[a[-1]+b[-1]+1000]
a+=d
b+=d
c=[]
inversions=0
for i in range(lena+lenb):
if a[inda]<b[indb]:
c.append(a[inda])
inda+=1
else:
c.append(b[indb])
indb+=1
inversions+=lena-inda
return((c,inversions))
def mergesort(a):
if len(a)<=1:
return((a,0))
split=len(a)//2
b=a[:split]
c=a[split:]
d=mergesort(b)
e=mergesort(c)
f=merge(d[0],e[0])
return((f[0],f[1]+d[1]+e[1]))
n=int(input())
a=list(map(int,input().split()))
b=[]
for guy in a:
if guy!=-1:
b.append(guy)
invs=mergesort(b)[1]
negs=len(a)-len(b)
pairs=(negs*(negs-1))//2
used=[0]*n
for guy in a:
if guy!=-1:
used[guy-1]+=1
unused=[0]
for i in range(n-1):
unused.append(unused[-1]+1-used[i])
negsseen=0
mix=0
for i in range(n):
if a[i]==-1:
negsseen+=1
else:
mix+=unused[a[i]-1]*(negs-negsseen)+negsseen*(negs-unused[a[i]-1])
num=invs*2*negs+pairs*negs+mix*2
denom=2*negs
if negs==0:
print(invs%998244353)
else:
for i in range(denom):
if (998244353*i+1)%denom==0:
inv=(998244353*i+1)//denom
break
print((num*inv)%998244353) | Python | [
"math",
"probabilities"
] | 1,101 | 1,283 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 1,574 |
d4ae071cf261ec3d91187a9a7dddcda0 | Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position. The inner area's sectors are denoted as (1,1), (1,2), \dots, (1,n) in clockwise direction. The outer area's sectors are denoted as (2,1), (2,2), \dots, (2,m) in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has q questions.For each question, check if he can move between two given sectors. | ['number theory', 'math'] | import math
n , m, q = map(int, input().split())
l = n // math.gcd(n, m) * m
g = l // math.gcd(n, m)
for i in range(q):
a , b, x, y = map(int, input().split())
b-=1;
y-=1;
b = (l // n * b) if a == 1 else (l // m * b);
y = (l // n * y) if x == 1 else (l // m * y);
if y//g != b//g:
print("NO")
else:
print("YES"); | Python | [
"math",
"number theory"
] | 785 | 324 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 980 |
2e6eafc13ff8dc91e6803deeaf2ecea5 | Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1]. | ['combinatorics', 'number theory', 'bitmasks'] | import sys
mod = 10**9 + 7
def solve():
n = int(input())
a = [int(i) for i in input().split()]
cnt = [0]*(10**5 + 1)
pat = [0]*(10**5 + 1)
for ai in a:
cnt[ai] += 1
for i in range(1, 10**5 + 1):
for j in range(2*i, 10**5 + 1, i):
cnt[i] += cnt[j]
pat[i] = (pow(2, cnt[i], mod) - 1)
for i in range(10**5, 0, -1):
for j in range(2*i, 10**5 + 1, i):
pat[i] = (pat[i] - pat[j]) % mod
ans = pat[1] % mod
print(ans)
if __name__ == '__main__':
solve() | Python | [
"math",
"number theory"
] | 483 | 558 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,724 |
4a50c4147becea13946272230f3dde6d | There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized. | ['constructive algorithms', 'strings'] | from sys import exit
def blokovi(x):
ret = [0]
for i in range(len(x) - 1):
if x[i] != x[i + 1]:
ret.append(i + 1)
return ret + [len(x)]
s = input()
t = input()
ss = blokovi(s)
tt = blokovi(t)
if s[-1] == 'a':
s += 'b'
else:
s += 'a'
if t[-1] == 'a':
t += 'b'
else:
t += 'a'
def greedy(x, y, rev=False):
i, j = len(x) - 1, len(y) - 1
swaps = []
while True:
while i >= 0 and x[i] == 'a':
i -= 1
while j >= 0 and y[j] == 'b':
j -= 1
if i < 0 and j < 0:
break
x, y = y, x
if rev:
swaps.append((j + 1, i + 1))
else:
swaps.append((i + 1, j + 1))
i, j = j, i
return swaps
def solve(x, y):
p = greedy(x, y)
q = greedy(y, x, True)
if len(p) < len(q):
return p
return q
probao = set()
total = len(ss) + len(tt)
sol = solve(s[:-1], t[:-1])
for b, i in enumerate(ss):
for c in range((2 * b + len(tt) - len(ss)) // 2 - 2, (2 * b + len(tt) - len(ss) + 1) // 2 + 3):
if 0 <= c < len(tt):
j = tt[c]
bs = b + len(tt) - c - 1
bt = c + len(ss) - b - 1
if abs(bs - bt) > 2:
continue
proba = (bs, bt, s[i], t[j])
if proba in probao:
continue
probao.add(proba)
s2 = t[:j] + s[i:-1]
t2 = s[:i] + t[j:-1]
if i + j > 0:
if i + j == len(s) + len(t) - 2:
cand = solve(t2, s2)
else:
cand = [(i, j)] + solve(s2, t2)
else:
cand = solve(s2, t2)
if len(cand) < len(sol):
sol = cand
print(len(sol))
for i, j in sol:
print(i, j)
| Python | [
"strings"
] | 432 | 1,806 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,803 |
87d3c1d8d3d1f34664ff32081222117d | You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.The value of a string s is the minimum value among f_i for all i from 1 to k.What is the maximum value the string can have? | ['binary search', 'bitmasks', 'brute force', 'dp', 'strings', 'two pointers'] | import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
n, k = map(int,input().split())
s = input()
def judge(needed):
inf = 2147483647
minstate = [inf]*(1<<k)
minstate[0] = 0
effect = [[inf]*(n+1) for j in range(k)]
for j in range(k):
accu = 0
index = inf
for i in range(n)[::-1]:
if s[i]==ord('?') or s[i]==97+j:
accu += 1
else:
accu = 0
if accu>=needed:
index = i + needed
effect[j][i] = index
# effect[j][i] = min(effect[j][i],inf*inf+inf*inf)
# print(effect)
for state in range(1,1<<k):
minimum = minstate[state]
for j in range(k):
if (1<<j) & state==0: continue
index = minstate[state^(1<<j)]
if index<n:
minimum = min(minimum, effect[j][index])
minstate[state] = minimum
# print(minstate)
if minstate[-1]<=n: return True
return False
front = 0
rear = n//k+1
while front < rear:
mid = (front+rear)//2
flag = judge(mid)
# print(mid,flag)
if flag:
front = mid + 1
else:
rear = mid
print(front-1)
| Python | [
"strings"
] | 724 | 1,334 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,105 |
eea7860e6bbbe5f399b9123ebd663e3e | Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself. | ['number theory', 'greedy', 'math'] | from collections import defaultdict
from math import sqrt
def solve():
n = int(input())
numbers = list(map(int, input().split(" ")))
if n == 1:
print(1)
return
amount = {}
for number in numbers:
if number not in amount:
amount[number] = 1
else:
amount[number] += 1
freq = defaultdict(int)
for key, value in sorted(amount.items()):
if key == 1:
freq[key] += value
continue
freq[key] += value
for j in range(2, int(sqrt(key)) + 1):
if key % j == 0:
freq[j] += value
if key // j != j:
freq[key//j] += value
highest = sorted(freq.items(), key=lambda x:x[1])[-1]
if highest[0] == 1:
print(1)
else:
print(highest[1])
solve() | Python | [
"math",
"number theory"
] | 691 | 848 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 892 |
14593b565193607dff8b6b25bf51a661 | We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting! | ['constructive algorithms', 'number theory', 'greedy', 'math'] | rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
def listprimes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def solve(N, A):
ones = twos = 0
for x in A:
if x == 1: ones += 1
else: twos += 1
primes = listprimes(ones + twos * 2 + 1)
i = 0
cur = 0
ans = []
while ones or twos:
while i < len(primes) and cur + 1 > primes[i]:
i += 1
if i == len(primes):
while ones:
ones -= 1
ans.append(1)
while twos:
twos -= 1
ans.append(2)
break
if ones and twos:
if cur + 2 == primes[i] and not cur + 1 == primes[i]:
twos -= 1
ans.append(2)
cur += 2
i += 1
elif cur + 1 == primes[i]:
ones -= 1
ans.append(1)
cur += 1
i += 1
else:
twos -= 1
ans.append(2)
cur += 2
elif ones:
ones -= 1
ans.append(1)
cur += 1
elif twos:
twos -= 1
ans.append(2)
cur += 2
return ans
from sys import stdout
N = rri()
A = rrm()
stdout.write(" ".join(map(str, solve(N, A))))
stdout.flush()
| Python | [
"number theory",
"math"
] | 615 | 1,527 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,389 |
b6a7e8abc747bdcee74653817085002c | Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its n favorite numbers: a_1, a_2, \ldots, a_n. What is the minimum number of hops Rabbit needs to get from (0,0) to (x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (x_i, y_i) and (x_j, y_j) is \sqrt{(x_i-x_j)^2+(y_i-y_j)^2}.For example, if Rabbit has favorite numbers 1 and 3 he could hop from (0,0) to (4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0) in 2 hops (e.g. (0,0) \rightarrow (2,-\sqrt{5}) \rightarrow (4,0)). Here is a graphic for the first example. Both hops have distance 3, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number a_i and hops with distance equal to a_i in any direction he wants. The same number can be used multiple times. | ['geometry', 'greedy', 'math'] | from math import ceil
for _ in range(int(input())):
n, x = map(int, input().split())
jumps = set(map(int, input().split()))
if x in jumps:
print(1)
continue
jumpmax = max(jumps)
if jumpmax > x:
print(2)
else:
print(ceil(x / jumpmax)) | Python | [
"math",
"geometry"
] | 1,354 | 290 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,930 |
c51e15aeb3f287608a26b85865546e85 | Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum is maximally possible, where A' is already rearranged array. | ['greedy', 'combinatorics', 'number theory', 'math', 'sortings'] | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
bb = list(enumerate(b))
bb = sorted(bb, key = lambda x:x[1])
#print (bb)
a.sort(reverse=True)
c = [0] * n
for i in range(n):
#print (bb[i][0])
c[bb[i][0]] = a[i]
print (*c) | Python | [
"math",
"number theory"
] | 609 | 263 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,685 |
0ed34310c59e3946b1c55b2618218120 | You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is \sum\limits_{i = 1}^{n} dist(i, v) \cdot a_i.Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily. | ['dp', 'dfs and similar', 'trees'] | import sys,math
from collections import defaultdict
from io import BytesIO
sys.stdin = BytesIO(sys.stdin.read())
sys.setrecursionlimit(200200)
input = lambda: sys.stdin.readline().rstrip('\r\n')
n = int(input())
arr = [0] + [int(x) for x in input().split(' ')]
cnts = [0] * (n+1)
sv = set()
dn = defaultdict(set)
for _ in range(n-1):
s,f = map(int, input().split(' '))
dn[s].add(f)
dn[f].add(s)
visited = [False for i in range(n+1)]
cost = [arr[i] for i in range(n+1)]
parent = [0 for i in range(n+1)]
val = 0
def dfs(s, depth):
global val
stack = [(s,depth)]
while stack:
s, depth = stack[-1]
if visited[s]:
stack.pop()
cost[parent[s]]+=cost[s]
continue
else:
visited[s] = True
val += depth * arr[s]
for i in dn[s]:
if not visited[i]:
parent[i] = s
stack.append((i, depth+1))
dfs(1, 0)
max_cost = val
visited = [False for i in range(n+1)]
cost[0] = sum(arr)
def trav(s, some_val):
global max_cost
stack = [(s,some_val)]
while stack:
s, some_val = stack.pop()
visited[s] = True
if some_val>max_cost:
max_cost = some_val
for i in dn[s]:
if not visited[i]:
stack.append((i, some_val+(cost[0]-cost[i])-cost[i] ))
trav(1, val)
print(max_cost)
| Python | [
"graphs",
"trees"
] | 661 | 1,401 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 2,948 |
b69170c8377623beb66db4706a02ffc6 | There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: Alice will get a (a > 0) candies; Betty will get b (b > 0) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. a > b); all the candies will be given to one of two sisters (i.e. a+b=n). Your task is to calculate the number of ways to distribute exactly n candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent n as the sum of n=a+b, where a and b are positive integers and a>b.You have to answer t independent test cases. | ['math'] | from math import ceil
T=int(input())
while T>0:
A=int(input())
B=ceil(A-A/2-1)
print(B)
T-=1 | Python | [
"math"
] | 807 | 116 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 912 |
03d6b61be6ca0ac9dd8259458f41da59 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | ['graphs', 'greedy', 'shortest paths'] | import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
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"
import heapq
def solve():
"""
1. First we calculate shortest path using dijkstra. We
1.1) While comparison of distances, in case of equal shortest paths, -> Maybe we can keep (dist, num_trains_encountered, next_node) in heapq.
choose the one with more train network.
2. All train paths not on shortest path can be eliminated.
"""
n, m, k = map(int, input().split())
adj_list = {x: [] for x in range(n + 1)}
dist = [float("inf")] * (n + 1)
dist[1] = 0
hq = [(0, 1)]
for _ in range(m):
u, v, x = map(int, input().split())
adj_list[u].append((v, x, False))
adj_list[v].append((u, x, False))
for _ in range(k):
v, y = map(int, input().split())
adj_list[1].append((v, y, True))
adj_list[v].append((1, y, True))
visited = [False] * (n + 1)
prev = {}
train_used = [0] * (n + 1)
# Dist, Train found, Next Node.
while hq:
d, node = heapq.heappop(hq)
if visited[node]:
continue
visited[node] = True
for edge in adj_list[node]:
nxt, w, isTrain = edge
if not visited[nxt]:
if d + w < dist[nxt]:
dist[nxt] = d + w
if isTrain:
train_used[nxt] = 1
if d + w == dist[nxt] and train_used[nxt] == 1 and not isTrain:
train_used[nxt] = 0
heapq.heappush(hq, (d + w, nxt))
cout<<k - sum(train_used)<<"\n"
def main():
solve()
if __name__ == "__main__":
main()
| Python | [
"graphs"
] | 733 | 3,548 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,446 |
d17d2fcfb088bf51e9c1f3fce4133a94 | Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, \dots, a_n and challenged him to choose an integer X such that the value \underset{1 \leq i \leq n}{\max} (a_i \oplus X) is minimum possible, where \oplus denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of \underset{1 \leq i \leq n}{\max} (a_i \oplus X). | ['dp', 'greedy', 'bitmasks', 'divide and conquer', 'brute force', 'dfs and similar', 'trees', 'strings'] | t=int(input())
lst=[int(ele) for ele in input().split()]
maxn=max(lst)
n=len(bin(maxn)[2:])
newlst=["0"*(n-len(bin(ele)[2:]))+bin(ele)[2:] for ele in lst]
def catchEvil(lstrino,loc):
count0,count1=[],[]
for ele in lstrino:
if ele[n-1-loc]=='1':
count1.append(ele)
else:
count0.append(ele)
if len(count0)==0:
if loc==0:
return 0
else:
return catchEvil(lstrino,loc-1)
elif len(count1)==0:
if loc==0:
return 0
else:
return catchEvil(lstrino,loc-1)
else:
if loc==0:
return 1
else:
return min(catchEvil(count1,loc-1),catchEvil(count0,loc-1))+(1<<loc)
if n==0:
print(0)
else:
print(int(catchEvil(newlst,n-1)))
| Python | [
"graphs",
"strings",
"trees"
] | 438 | 806 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 1
} | 3,766 |
c083988d20f434d61134f7b376581eb6 | You are given two arrays a and b, each contains n integers.You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i \in [1, n] let c_i := d \cdot a_i + b_i.Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if you choose d optimally? | ['number theory', 'hashing', 'math'] | # @-*- coding: utf-8 -*-
# @Time: 2018-10-21T21:21:26+08:00
# @Email: ykaiwan@163.com
import sys
import math
import bisect
from collections import defaultdict
MOD = int(1e9+7)
# n = map(int, raw_input().split())
n = int(raw_input())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
ck = defaultdict(int)
def gcd(x, y):
while (y):
x, y = y, x % y
return x
tt = 0
for i, j in zip(a,b):
if i == 0:
if j == 0:
tt += 1
else:
k = gcd(i, j)
ck[(i/k, j/k)] += 1
if not ck:
print 0+tt
else:
print max(ck.values())+tt
| Python | [
"math",
"number theory"
] | 398 | 603 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,014 |
f48ddaf1e1db5073d74a2aa318b46704 | Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean. | ['brute force', 'greedy', 'strings'] | n = int(input())
l = [input() for i in range(n)]
m = 0
for i in range(0,len(l)):
mi = 1
for j in range(i+1,len(l)):
if l[i] == l[j]:
mi += 1
m = max(m,mi)
print(m)
| Python | [
"strings"
] | 604 | 172 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,507 |
2e1ab01d4d4440f33c840c4564a20a60 | Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo? | ['two pointers', 'number theory', 'math', 'implementation', 'sortings', 'data structures', 'brute force'] | import itertools
import time
unfold = itertools.chain.from_iterable
t = time.time() + 1900
def jumps(a):
d = speedup
if time.time() > t:
print(anss)
exit(0)
try:
while True:
c = (a + d - 1) // d
d = (a + c - 2) // (c - 1)
yield d
except:
return
# while d < a - 1:
# c = (a + d - 1) // d
# d = (a + c - 2) // (c - 1)
# yield d
def calc(d):
return (d - 1) * len(a) - sum(i % d for i in a)
def ans1(D):
for d in D:
d -= 1
if calc(d) <= k:
return d
return 1
def ans():
for d, pd in zip(D, D[1:]):
if time.time() > t:
return anss
d -= 1
cd = calc(d)
if cd <= k:
return d
if d == pd:
continue
cpd = calc(pd)
if (d - pd) * (cd - cpd) >= ((cd - k) * (d - pd) + cd - cpd - 1):
return d - ((cd - k) * (d - pd) + cd - cpd - 1) // (cd - cpd)
return anss
n, k = map(int, input().split())
a = list(map(int, input().split()))
speedup = int(2 * max(a) ** 0.55)
lb = int(max(a) ** 0.1 + 10)
a = [i - 1 for i in a]
anss = ans1(sorted(range(2, lb + 1), reverse=True))
if anss <= lb / 2:
print(anss)
exit(0)
a = [i + 1 for i in a]
D = sorted(set(range(lb + 1, speedup + 1)).union(set([speedup, max(a) + k + 1]).union(set(
unfold(map(jumps, a))))), reverse=True)
a = [i - 1 for i in a]
print(int(ans())) | Python | [
"number theory",
"math"
] | 941 | 1,465 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 891 |
a44cba5685500b16e24b8fba30451bc5 | Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability \frac{1}{2} he solves the crossword in exactly t_i seconds, and with probability \frac{1}{2} he has to spend an additional second to finish the crossword). All these events are independent.After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = \sum \limits_{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction \frac{P}{Q} with Q > 0. To give the answer, you should print P \cdot Q^{-1} \bmod (10^9 + 7). | ['dp', 'combinatorics', 'two pointers', 'number theory', 'probabilities'] | MOD = 10 ** 9 + 7
MAX = 5 * 10 ** 5
fac, ifac, ipow2 = [1] * MAX, [1] * MAX, [1] * MAX
for i in range(1, MAX):
fac[i] = fac[i - 1] * i % MOD
ifac[i] = pow(fac[i], MOD - 2, MOD)
ipow2[i] = ipow2[i - 1] * (MOD + 1) // 2 % MOD
choose = lambda n, k: fac[n] * ifac[k] % MOD * ifac[n - k] % MOD
n, t = map(int, raw_input().split())
a = list(map(int, raw_input().split()))
s = 0
p = [1] + [0] * (n + 1)
k = cur = 0
for i in range(n):
s += a[i]
if s > t: break
if s + i + 1 <= t:
p[i + 1] = 1
continue
newk = t - s
cur = cur * 2 - choose(i, k) if cur else sum(choose(i + 1, j) for j in range(newk + 1))
if newk < k:
cur -= sum(choose(i + 1, x) for x in range(k, newk, -1))
cur %= MOD
p[i + 1] = cur * ipow2[i + 1] % MOD
k = newk
print(sum((p[i] - p[i + 1]) * i % MOD for i in range(1, n + 1)) % MOD) | Python | [
"math",
"number theory",
"probabilities"
] | 2,205 | 863 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 2,466 |
c313a305cc229ec23b19c6e4dd46b57b | 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. | ['constructive algorithms', 'geometry', 'greedy', 'implementation', 'strings'] | 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")
| Python | [
"strings",
"geometry"
] | 1,536 | 1,219 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,716 |
2ed58a84bd705e416cd25f139f904d68 | You have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows: For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree. Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect. Now let's define following things: Rubber band a includes rubber band b, if and only if rubber band b is in rubber band a's area, and they don't intersect each other. Sequence of rubber bands a_{1}, a_{2}, \ldots, a_{k} (k \ge 2) are nested, if and only if for all i (2 \le i \le k), a_{i-1} includes a_{i}. This is an example of conversion. Note that rubber bands 5 and 6 are nested. It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it. | ['dp', 'constructive algorithms', 'math', 'dfs and similar', 'trees'] | FAST_IO = 1
if FAST_IO:
import io, sys, atexit
rr = iter(sys.stdin.read().splitlines()).next
sys.stdout = _OUTPUT_BUFFER = io.BytesIO()
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
###
def solve(N, graph):
VISIT, DO = 0, 1
stack = [[DO, 0, -1], [VISIT, 0, -1]]
res = [None] * N
ans = 0
while stack:
cmd, node, par = stack.pop()
if cmd == VISIT:
for nei in graph[node]:
if nei != par:
stack.append([DO, nei, node])
stack.append([VISIT, nei, node])
else:
white = black = 0
best = []
bestb = []
for nei in graph[node]:
if nei != par:
w, b = res[nei]
white = max(white, b)
black = max(black, w, b)
best.append(max(w, b))
best.sort(reverse=True)
if len(best) >= 3: best.pop()
bestb.append(b)
bestb.sort(reverse=True)
if len(bestb) >= 3: bestb.pop()
white += 1
black += len(graph[node]) - 2
ans = max(ans, sum(bestb) + 1,
sum(best) + len(graph[node]) - 2)
res[node] = [white, black]
return ans
N = rri()
graph = [[] for _ in xrange(N)]
for _ in xrange(N-1):
u, v=rrm()
u -= 1
v -= 1
graph[u].append(v)
graph[v].append(u)
print solve(N, graph)
| Python | [
"math",
"graphs",
"trees"
] | 1,136 | 1,644 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 3,709 |
f0633a45bf4dffda694d0b8041a6d743 | Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like. In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also — to make things even funnier — the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law "the angle of incidence equals the angle of reflection". | ['implementation', 'geometry'] | #!/usr/bin/python
import sys
L = 100000
a = 50.0
def getScore(uSide, lSide, uScore, lScore, d1, d2):
mok = 1
finalScore = 0
for k in range(1, 2*min(len(uScore), len(lScore))+1):
thisScore = 0
uValid = [1 for x in range(len(uScore))]
lValid = [1 for x in range(len(lScore))]
mok = - mok
for j in range(1, k+1):
x = ((-2*j+1)*a - d1) * L / (-2*k*a + mok * d2 - d1)
if j % 2 == 1:
side = lSide
score = lScore
valid = lValid
else:
side = uSide
score = uScore
valid = uValid
pos = int(x)
if side[pos] == -1 or valid[side[pos]] == 0:
break
else:
valid[side[pos]] = 0
thisScore += score[side[pos]]
else:
finalScore = max(finalScore, thisScore)
return finalScore
h1, h2, n = [int(x) for x in raw_input().split()]
upperSide = [-1 for x in range(L)]
lowerSide = [-1 for x in range(L)]
upperScore = []
lowerScore = []
for i in range(n):
x = sys.stdin.readline().split()
if x[1] == 'F':
score = lowerScore
side = lowerSide
else:
score = upperScore
side = upperSide
score.append(int(x[0]))
for i in range(int(x[2]), int(x[3])):
side[i] = len(score)-1
d1 = h1 - a
d2 = h2 - a
score1 = getScore(upperSide, lowerSide, upperScore, lowerScore, d1, d2)
score2 = getScore(lowerSide, upperSide, lowerScore, upperScore, -d1, -d2)
print max(score1, score2)
| Python | [
"geometry"
] | 916 | 1,331 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,256 |
0d70984ab8bd7aecd68c653adf54fc08 | When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types: transform lowercase letters to uppercase and vice versa; change letter «O» (uppercase latin letter) to digit «0» and vice versa; change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones. | ['*special', 'strings'] | import sys
def canonize(s):
return s.lower().replace('0', 'o').replace('l', '1').replace('i', '1')
wanted = sys.stdin.readline().strip()
n = int(sys.stdin.readline().strip())
L = set()
for i in range(n):
login = sys.stdin.readline().strip()
L.add(canonize(login))
print('No' if (canonize(wanted) in L) else 'Yes')
| Python | [
"strings"
] | 1,228 | 330 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 280 |
2b37188c17b7cbc3e533e9ad341441b2 | When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i ≤ j).Then the simple prettiness of s is defined by the formula:The prettiness of s equals Find the prettiness of the given song title.We assume that the vowels are I, E, A, O, U, Y. | ['math', 'strings'] | from itertools import accumulate
vowels = set('AIUEOY')
s = input()
n = len(s)
vs = list(accumulate(0 if i == 0 else 1 / i for i in range(n + 1)))
r = 0
v = 0
for i in range(n):
v += vs[n - i] - vs[i]
if s[i] in vowels:
r += v
print(r) | Python | [
"math",
"strings"
] | 1,001 | 251 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,253 |
9ab7d1142ede6fe3b642ac73a307cdd5 | This is an interactive problem.A city has n^2 buildings divided into a grid of n rows and n columns. You need to build a road of some length D(A,B) of your choice between each pair of adjacent by side buildings A and B. Due to budget limitations and legal restrictions, the length of each road must be a positive integer and the total length of all roads should not exceed 48\,000.There is a thief in the city who will start from the topmost, leftmost building (in the first row and the first column) and roam around the city, occasionally stealing artifacts from some of the buildings. He can move from one building to another adjacent building by travelling through the road which connects them.You are unable to track down what buildings he visits and what path he follows to reach them. But there is one tracking mechanism in the city. The tracker is capable of storing a single integer x which is initially 0. Each time the thief travels from a building A to another adjacent building B through a road of length D(A,B), the tracker changes x to x\oplus D(A,B). Each time the thief steals from a building, the tracker reports the value x stored in it and resets it back to 0.It is known beforehand that the thief will steal in exactly k buildings but you will know the values returned by the tracker only after the thefts actually happen. Your task is to choose the lengths of roads in such a way that no matter what strategy or routes the thief follows, you will be able to exactly tell the location of all the buildings where the thefts occurred from the values returned by the tracker. | ['bitmasks', 'constructive algorithms', 'divide and conquer', 'greedy', 'interactive', 'math'] |
def gray(k):
if k==1:return [0,1]
res=gray(k-1)
res2=res[::-1]
for i in range(len(res2)):
res2[i]+=2**(k-1)
return res+res2
g=gray(5)
memo=dict()
def ps(i,j):
return memo[i,j]
memo2=dict()
def inv(x):
return memo2[x]
for i in range(32):
for j in range(32):
nodi,nodj=g[i],g[j]
res=0
resi=[]
resj=[]
for _ in range(5):
resi.append(nodi%2)
nodi//=2
resj.append(nodj%2)
nodj//=2
for _ in range(5):
res*=2
res+=resi.pop()
res*=2
res+=resj.pop()
memo[i,j]=res
memo2[memo[i,j]]=(i,j)
n,k=map(int,input().split())
s=0
for i in range(n):
res=[]
for j in range(n-1):
res.append(ps(i,j)^ps(i,j+1))
print(*res)
s+=sum(res)
for i in range(n-1):
res=[]
for j in range(n):
res.append(ps(i,j)^ps(i+1,j))
print(*res)
s+=sum(res)
i,j=0,0
now=0
import sys
for _ in range(k):
x=int(input())
sys.stdout.flush()
now^=x
ni,nj=inv(now)
print(ni+1,nj+1)
| Python | [
"math"
] | 1,694 | 1,119 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,399 |
7c0ffbba9e61a25e51c91b1f89c35532 | You are given a matrix a, consisting of 3 rows and n columns. Each cell of the matrix is either free or taken.A free cell y is reachable from a free cell x if at least one of these conditions hold: x and y share a side; there exists a free cell z such that z is reachable from x and y is reachable from z. A connected component is a set of free cells of the matrix such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule.You are asked q queries about the matrix. Each query is the following: l r — count the number of connected components of the matrix, consisting of columns from l to r of the matrix a, inclusive. Print the answers to all queries. | ['brute force', 'data structures', 'dp', 'dsu', 'math', 'trees'] | import sys
def Column2Num( m, idx ):
return int(m[0][idx] != 0) | (int(m[1][idx]) << 1) | (int(m[2][idx]) << 2)
def QColumn( m, bits, idx ):
if bits[idx] == 5:
if m[0][idx] == m[2][idx]:
return True
return False
def GetIntegratedCount( m ):
ret, curr = [ 0 ], set()
for c in range( len( m[0] ) ):
if m[0][c] != 0: curr.add( m[0][c] )
if m[1][c] != 0: curr.add( m[1][c] )
if m[2][c] != 0: curr.add( m[2][c] )
ret.append( len( curr ) )
ret.append( len( curr ) )
return ret
def Print( tm ):
print( '\n', tm[0], '\n', tm[1], '\n', tm[2] )
def PrintIndexed( tm ):
for i in range( len( tm[0] ) ):
print( i+1, ':', tm[0][i], tm[1][i], tm[2][i] )
def next( b, next ):
b &= next
if b == 0:
return b
if b & 1 or b & 4:
if next & 2:
b |= 2
if b & 2:
if next & 1:
b |= 1
if next & 4:
b |= 4
return b
def setCompNumber( b, m, i, compNumber ):
if b & 1:
m[0][i] = compNumber
if b & 2:
m[1][i] = compNumber
if b & 4:
m[2][i] = compNumber
def goLeft( start, compNumber, size, m, bits, fullColumn ):
b = bits[start]
fc = start
for i in range( start - 1, -1, -1 ):
b = next( b, bits[i] )
if b == 7:
fc = i
break
if b == 0:
break
setCompNumber( b, m, i, compNumber )
if b == 5:
fullColumn[ i ] = fc
def goRight( start, compNumber, size, m, bits, fullColumn ):
b = bits[start]
for i in range( start, size ):
b = next( b, bits[i] )
if b == 7:
fc = i
if b == 0:
break
setCompNumber( b, m, i, compNumber )
if b == 5:
fullColumn[ i ] = fc
def goRight12( b, start, compNumber, size, m, bits ):
for i in range( start, size ):
b = next( b, bits[i] )
if b == 0:
break
setCompNumber( b, m, i, compNumber )
def get3Components( compNumber, size, m, bits, leftFullColumn, rightFullColumn ):
for i in range( size ):
if bits[i] == 7:
if m[ 0 ][ i ] == 1:
compNumber += 1
goRight( i, compNumber, size, m, bits, leftFullColumn )
goLeft ( i, compNumber, size, m, bits, rightFullColumn )
return compNumber
def get12Components( compNumber, size, m, bits ):
for i in range( size ):
if m[ 0 ][ i ] == 1:
compNumber += 1
goRight12( 1, i, compNumber, size, m, bits )
if m[ 1 ][ i ] == 1:
compNumber += 1
goRight12( 2, i, compNumber, size, m, bits )
if m[ 2 ][ i ] == 1:
compNumber += 1
goRight12( 4, i, compNumber, size, m, bits )
def SolveBB( m, bits, integratedCount, s, e, leftFullColumn, rightFullColumn ):
#debug = 0
#print( 'start,end =',s, e )
#if debug: Print( [ m[0][s-1:e], m[1][s-1:e], m[2][s-1:e] ] )
sol1 = 0
if s-1 == 0:
sol1 = integratedCount[e]
else:
startCnt = 1
if bits[s-1] == 0:
startCnt = 0
elif bits[s-1] == 5:
if m[0][s-1] != m[2][s-1]:
startCnt = 2
sol1 = startCnt + integratedCount[e] - integratedCount[s]
sQ = QColumn( m, bits, s - 1)
eQ = QColumn( m, bits, e - 1)
if sQ and eQ:
if m[0][s-1] == m[2][s-1]:
if rightFullColumn[s-1] == rightFullColumn[e-1]:
sol1 += 1
return sol1
elif leftFullColumn[s-1] == leftFullColumn[e-1]:
sol1 += 1
return sol1
if sQ:
if rightFullColumn[s-1] != -1:
if rightFullColumn[s-1] > e-1:
sol1 += 1
else:
sol1 += 1
if eQ:
if leftFullColumn[e-1] != -1:
if leftFullColumn[e-1] < s-1:
sol1 += 1
else:
sol1 += 1
return sol1
def mainBB():
debug = 0
input = sys.stdin
if len( sys.argv ) >= 2:
input = open( sys.argv[1], 'r' )
size = int( input.readline() )
m = []
for i in range( 3 ):
m.append( [ int( t ) for t in list( input.readline().strip() ) ] )
bits = [ Column2Num( m, i ) for i in range( size ) ]
leftFullColumn = [ -1 for i in range( size ) ]
rightFullColumn = list( leftFullColumn )
compNumber = get3Components( 1, size, m, bits, leftFullColumn, rightFullColumn )
get12Components( compNumber, size, m, bits )
integratedCount = GetIntegratedCount( m )
if debug: PrintIndexed( m )
if debug: Print( m )
if debug: print( integratedCount )
if debug: print( leftFullColumn )
if debug: print( rightFullColumn )
n = int( input.readline() )
for i in range( n ):
ln = input.readline().strip().split()
s = int( ln[0] )
e = int( ln[1] )
if debug: print( s, e, m )
print( SolveBB( m, bits, integratedCount, s, e, leftFullColumn, rightFullColumn ) )
if __name__ == "__main__":
mainBB()
| Python | [
"graphs",
"math",
"trees"
] | 825 | 5,373 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 576 |
8c33618363cacf005e4735cecfdbe2eb | You are given a tree consisting of n vertices, and q triples (x_i, y_i, s_i), where x_i and y_i are integers from 1 to n, and s_i is a string with length equal to the number of vertices on the simple path from x_i to y_i.You want to write a lowercase Latin letter on each vertex in such a way that, for each of q given triples, at least one of the following conditions holds: if you write out the letters on the vertices on the simple path from x_i to y_i in the order they appear on this path, you get the string s_i; if you write out the letters on the vertices on the simple path from y_i to x_i in the order they appear on this path, you get the string s_i. Find any possible way to write a letter on each vertex to meet these constraints, or report that it is impossible. | ['2-sat', 'dfs and similar', 'dsu', 'graphs', 'trees'] | class _csr:
def __init__(self, n, edges):
self.start = [0] * (n + 1)
self.elist = [0] * len(edges)
for v, _ in edges:
self.start[v + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = self.start.copy()
for v, e in edges:
self.elist[counter[v]] = e
counter[v] += 1
class scc_graph:
"""It calculates the strongly connected components of directed graphs.
"""
def __init__(self, n):
"""It creates a directed graph with n vertices and 0 edges.
Constraints
-----------
> 0 <= n <= 10 ** 8
Complexity
----------
> O(n)
"""
self.n = n
self.edges = []
def add_edge(self, from_, to):
"""It adds a directed edge from the vertex `from_` to the vertex `to`.
Constraints
-----------
> 0 <= from_ < n
> 0 <= to < n
Complexity
----------
> O(1) amortized
"""
# assert 0 <= from_ < self.n
# assert 0 <= to < self.n
self.edges.append((from_, to))
def _scc_ids(self):
g = _csr(self.n, self.edges)
now_ord = 0
group_num = 0
visited = []
low = [0] * self.n
order = [-1] * self.n
ids = [0] * self.n
parent = [-1] * self.n
stack = []
for i in range(self.n):
if order[i] == -1:
stack.append(i)
stack.append(i)
while stack:
v = stack.pop()
if order[v] == -1:
low[v] = order[v] = now_ord
now_ord += 1
visited.append(v)
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i]
if order[to] == -1:
stack.append(to)
stack.append(to)
parent[to] = v
else:
low[v] = min(low[v], order[to])
else:
if low[v] == order[v]:
while True:
u = visited.pop()
order[u] = self.n
ids[u] = group_num
if u == v:
break
group_num += 1
if parent[v] != -1:
low[parent[v]] = min(low[parent[v]], low[v])
for i, x in enumerate(ids):
ids[i] = group_num - 1 - x
return group_num, ids
def scc(self):
"""It returns the list of the "list of the vertices" that satisfies the following.
> Each vertex is in exactly one "list of the vertices".
> Each "list of the vertices" corresponds to the vertex set of a strongly connected component.
The order of the vertices in the list is undefined.
> The list of "list of the vertices" are sorted in topological order,
i.e., for two vertices u, v in different strongly connected components,
if there is a directed path from u to v,
the list contains u appears earlier than the list contains v.
Complexity
----------
> O(n + m), where m is the number of added edges.
"""
group_num, ids = self._scc_ids()
groups = [[] for _ in range(group_num)]
for i, x in enumerate(ids):
groups[x].append(i)
return groups
class two_sat:
"""It solves 2-SAT.
For variables x[0], x[1], ..., x[n-1] and clauses with form
> ((x[i] = f) or (x[j] = g)),
it decides whether there is a truth assignment that satisfies all clauses.
"""
def __init__(self, n):
"""It creates a 2-SAT of n variables and 0 clauses.
Constraints
-----------
> 0 <= n <= 10 ** 8
Complexity
----------
> O(n)
"""
self.n = n
self._answer = [False] * n
self.scc = scc_graph(2 * n)
def add_clause(self, i, f, j, g):
"""It adds a clause ((x[i] = f) or (x[j] = g)).
Constraints
-----------
> 0 <= i < n
> 0 <= j < n
Complexity
----------
> O(1) amortized
"""
# assert 0 <= i < self.n
# assert 0 <= j < self.n
self.scc.add_edge(2 * i + (f == 0), 2 * j + (g == 1))
self.scc.add_edge(2 * j + (g == 0), 2 * i + (f == 1))
def satisfiable(self):
"""If there is a truth assignment that satisfies all clauses, it returns `True`.
Otherwise, it returns `False`.
Constraints
-----------
> You may call it multiple times.
Complexity
----------
> O(n + m), where m is the number of added clauses.
"""
_, ids = self.scc._scc_ids()
for i in range(self.n):
if ids[2 * i] == ids[2 * i + 1]:
return False
self._answer[i] = (ids[2*i] < ids[2*i+1])
return True
def answer(self):
"""It returns a truth assignment that satisfies all clauses of the last call of `satisfiable`.
If we call it before calling `satisfiable` or when the last call of `satisfiable` returns `False`,
it returns the list of length n with undefined elements.
Complexity
----------
> O(n)
"""
return self._answer.copy()
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
N,Q = mi()
edge = [[] for v in range(N)]
for _ in range(N-1):
u,v = mi()
edge[u-1].append(v-1)
edge[v-1].append(u-1)
parent = [[-1]*19 for i in range(N)]
depth = [0] * N
deq = deque([0])
while deq:
v = deq.popleft()
for nv in edge[v]:
if nv==parent[v][0]:
continue
parent[nv][0] = v
depth[nv] = depth[v] + 1
deq.append(nv)
for k in range(1,19):
for v in range(N):
if parent[v][k-1]==-1:
parent[v][k] = -1
else:
pv = parent[v][k-1]
parent[v][k] = parent[pv][k-1]
def lca(u,v):
if depth[u] > depth[v]:
u,v = v,u
dd = depth[v] - depth[u]
for k in range(19)[::-1]:
if dd>>k & 1:
v = parent[v][k]
if u==v:
return u
for k in range(19)[::-1]:
pu,pv = parent[u][k],parent[v][k]
if pu!=pv:
u,v = pu,pv
return parent[u][0]
def path(u,v):
L = lca(u,v)
res0 = [u]
pos = u
while pos!=L:
pos = parent[pos][0]
res0.append(pos)
res1 = [v]
pos = v
while pos!=L:
pos = parent[pos][0]
res1.append(pos)
res1.pop()
return res0 + res1[::-1]
cand = [None for v in range(N)]
string = []
for i in range(Q):
u,v,s = input().split()
u,v = int(u)-1,int(v)-1
p = path(u,v)
n = len(s)
for j in range(n):
v = p[j]
if cand[v] is None:
cand[v] = set([s[j],s[-j-1]])
else:
cand[v] &= set([s[j],s[-j-1]])
string.append((u,v,s))
for v in range(N):
if cand[v] is None:
cand[v] = ["a","b"]
else:
cand[v] = list(cand[v]) + ["(",")"][:2-len(cand[v])]
#print(cand)
G = two_sat(N+Q)
for i in range(Q):
u,v,s = string[i]
p = path(u,v)
n = len(s)
for j in range(n):
if s[j]==s[-j-1]:
continue
v = p[j]
t = s[j]
if t==cand[v][0]:
G.add_clause(i+N,1,v,0)
elif t==cand[v][1]:
G.add_clause(i+N,1,v,1)
else:
G.add_clause(i+N,1,i+N,1)
t = s[-j-1]
if t==cand[v][0]:
G.add_clause(i+N,0,v,0)
elif t==cand[v][1]:
G.add_clause(i+N,0,v,1)
else:
G.add_clause(i+N,0,i+N,0)
check = G.satisfiable()
if not check:
exit(print("NO"))
ans = G.answer()
res = []
for v in range(N):
if ans[v]:
res.append(cand[v][1])
else:
res.append(cand[v][0])
#print(res,ans)
for i in range(Q):
u,v,s = string[i]
p = path(u,v)
n = len(s)
if any(res[p[j]]!=s[j] for j in range(n)) and any(res[p[j]]!=s[-j-1] for j in range(n)):
exit(print("NO"))
print("YES")
print("".join(res))
| Python | [
"graphs",
"trees"
] | 880 | 9,134 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,445 |
48946ede1147b630992157ffcc9403e1 | Given n strings, each of length 2, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices (i, j) such that i < j and the i-th string and the j-th string differ in exactly one position.In other words, count the number of pairs (i, j) (i < j) such that the i-th string and the j-th string have exactly one position p (1 \leq p \leq 2) such that {s_{i}}_{p} \neq {s_{j}}_{p}.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow. | ['data structures', 'math', 'strings'] | from collections import Counter
for cases in range(int(input())):
n=int(input())
ls=[]
k=0
for i in range(n):
ls.append(input())
t=Counter (ls)
s=list(set(ls))
for i in range(0,len(s)-1):
for j in range(i+1,len(s)):
if(s[i]!=s[j] and(s[i][0]==s[j][0] or s[i][1]==s[j][1])):
k+=t[s[i]]*t[s[j]]
print(k)
| Python | [
"math",
"strings"
] | 634 | 410 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,403 |
4770fb8fb5c0663bef38ae0385a2d8c0 | Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.Help Ciel to make a valid plan, and if it's impossible, output "Impossible!". | ['greedy', 'constructive algorithms', 'divide and conquer', 'dfs and similar', 'trees'] | import sys
range = xrange
def decomp(coupl, root = 0):
n = len(coupl)
visible_labels = [0] * n
bfs = [root]
for node in bfs:
for nei in coupl[node]:
coupl[nei].remove(node)
bfs += coupl[node]
for node in reversed(bfs):
seen = seen_twice = 0
for nei in coupl[node]:
seen_twice |= seen & visible_labels[nei]
seen |= visible_labels[nei]
tmp = ~seen & -(1 << seen_twice.bit_length())
label = tmp & -tmp
visible_labels[node] = (label | seen) & -label
return [(seen & -seen).bit_length() - 1 for seen in visible_labels]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
print ' '.join(chr(ord('Z') - x) for x in decomp(coupl)) | Python | [
"graphs",
"trees"
] | 819 | 943 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 3,632 |
bcd34e88bcd70ad36acbe6c3b70aa45d | Multiset —is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. Two multisets are equal when each value occurs the same number of times. For example, the multisets \{2,2,4\} and \{2,4,2\} are equal, but the multisets \{1,2,2\} and \{1,1,2\} — are not.You are given two multisets a and b, each consisting of n integers.In a single operation, any element of the b multiset can be doubled or halved (rounded down). In other words, you have one of the following operations available for an element x of the b multiset: replace x with x \cdot 2, or replace x with \lfloor \frac{x}{2} \rfloor (round down). Note that you cannot change the elements of the a multiset.See if you can make the multiset b become equal to the multiset a in an arbitrary number of operations (maybe 0).For example, if n = 4, a = \{4, 24, 5, 2\}, b = \{4, 1, 6, 11\}, then the answer is yes. We can proceed as follows: Replace 1 with 1 \cdot 2 = 2. We get b = \{4, 2, 6, 11\}. Replace 11 with \lfloor \frac{11}{2} \rfloor = 5. We get b = \{4, 2, 6, 5\}. Replace 6 with 6 \cdot 2 = 12. We get b = \{4, 2, 12, 5\}. Replace 12 with 12 \cdot 2 = 24. We get b = \{4, 2, 24, 5\}. Got equal multisets a = \{4, 24, 5, 2\} and b = \{4, 2, 24, 5\}. | ['constructive algorithms', 'data structures', 'greedy', 'math', 'number theory'] | #!/usr/bin/env python3
import io, os, sys
from sys import stdin, stdout
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def input(): return stdin.readline().strip()
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
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from bisect import bisect_left
from functools import lru_cache
import random
### CODE HERE
import sys
import array
class BinaryTrie_pool:
def __repr__(self) -> str:
return f"{self.num_words, self.starts, self.child0, self.child1}"
def alloc(self):
self.num_words.append(0)
self.starts.append(0)
self.child0.append(-1)
self.child1.append(-1)
self.next_alloc += 1
return self.next_alloc - 1
def __init__(self):
self.num_words = array.array('L')
self.starts = array.array('L')
self.child0 = array.array('l')
self.child1 = array.array('l')
self.next_alloc = 0
self.root = self.alloc()
def anyChild(self, node):
if self.child0[node] != -1 and self.starts[self.child0[node]] > 0:
return self.child0[node]
if self.child1[node] != -1 and self.starts[self.child1[node]] > 0:
return self.child1[node]
def insert(self, word):
word = list(map(int, word))
node=self.root
for i in word:
self.starts[node] += 1
if i == 0 and self.child0[node] == -1: self.child0[node] = self.alloc()
if i == 1 and self.child1[node] == -1: self.child1[node] = self.alloc()
node = self.child0[node] if i == 0 else self.child1[node]
self.num_words[node] += 1
self.starts[node] += 1
def findAnyWithPrefix(self, prefix):
prefix = list(map(int, prefix))
node = self.findNode(prefix)
if node == -1 or node is None:
return None
if self.starts[node] == 0:
return None
while self.num_words[node] == 0:
node = self.anyChild(node)
return node
def containsWord(self, word):
word = list(map(int, word))
node = self.findNode(word)
if node == -1: return False
return node.num_words > 0
def remove(self, word):
word = list(map(int, word))
node=self.root
self.starts[node] -= 1
for i in word:
if i == 0 and self.child0[node] == -1: return None
if i == 1 and self.child1[node] == -1: return None
node = self.child0[node] if i == 0 else self.child1[node]
self.starts[node] -= 1
self.num_words[node] -= 1
def removeAnyWithPrefix(self, prefix):
prefix = list(map(int, prefix))
node=self.root
for i in prefix:
self.starts[node] -= 1
node = self.child0[node] if i == 0 else self.child1[node]
if self.num_words[node] > 0:
self.starts[node] -= 1
self.num_words[node] -= 1
return
self.starts[node] -= 1
while self.num_words[node] == 0:
node = self.anyChild(node)
self.starts[node] -= 1
self.num_words[node] -= 1
def findNode(self, word):
word = list(map(int, word))
node=self.root
for i in word:
if i == 0 and self.child0[node] == -1: return None
if i == 1 and self.child1[node] == -1: return None
node = self.child0[node] if i == 0 else self.child1[node]
return node
def startsWith(self, prefix):
prefix = list(map(int, prefix))
node = self.findNode(prefix)
if node == -1: return False
return self.starts[node] > 0
def clean(arr):
ret = []
for a in arr:
x = a
while x > 0 and x % 2 == 0:
x //= 2
ret += [x]
return sorted(ret)[::-1]
def bin(x):
return "{0:b}".format(x)
def ans(A, B):
A = clean(A)
B = clean(B)
A = [bin(x) for x in A]
B = [bin(x) for x in B]
t = BinaryTrie_pool()
for b in B:
t.insert(b)
for a in A:
w = t.findAnyWithPrefix(a)
if w is None:
return "NO"
t.removeAnyWithPrefix(a)
return "YES"
if False:
t = BinaryTrie_pool()
t.insert("10")
t.insert("100")
print(t)
print(t.anyChild(0))
else:
for _ in range(read_int()):
input()
A = read_int_list()
B = read_int_list()
print(ans(A, B))
| Python | [
"math",
"number theory"
] | 1,479 | 4,951 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,437 |
02a0b3cb995f954b216130d703dfc856 | Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.Before beginning the game, a special integer k is chosen. The game proceeds as follows: Alice begins the game, with moves alternating each turn; in any move, the current player may choose some node (for example, i) which has depth at least k. Then, the player picks some positive number of presents hanging from that node, let's call it m (1 \le m \le a_i); the player then places these m presents on the k-th ancestor (let's call it j) of the i-th node (the k-th ancestor of vertex i is a vertex j such that i is a descendant of j, and the difference between the depth of j and the depth of i is exactly k). Now, the number of presents of the i-th node (a_i) is decreased by m, and, correspondingly, a_j is increased by m; Alice and Bob both play optimally. The player unable to make a move loses the game.For each possible root of the tree, find who among Alice or Bob wins the game.Note: The depth of a node i in a tree with root r is defined as the number of edges on the simple path from node r to node i. The depth of root r itself is zero. | ['bitmasks', 'data structures', 'dfs and similar', 'dp', 'games', 'math', 'trees'] | '''
Hala Madrid!
https://www.zhihu.com/people/li-dong-hao-78-74
'''
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
#------------------------------FastIO---------------------------------
from bisect import *
from heapq import *
from collections import *
from functools import *
from itertools import *
from time import *
from random import *
from math import log, gcd, sqrt, ceil
class TopSort_Tree:
def __init__(self, n) -> None:
self.n = n
self.graph = defaultdict(set)
self.parent = [n + 1 for _ in range(self.n)]
def add_edge(self, a, b):
self.graph[a].add(b)
self.graph[b].add(a)
def sort(self, root):
graphlist = []
q = deque()
q.append((root, -1))
while q:
cur, fa = q.popleft()
graphlist.append(cur)
for e in self.graph[cur]:
if e == fa:
continue
else:
self.parent[e] = cur
q.append((e, cur))
return graphlist[::-1]
def solve():
n, k = MI()
gl = TopSort_Tree(n)
xorsum = [[0 for _ in range(k << 1)] for _ in range(n)]
win = [0 for _ in range(n)]
for _ in range(n - 1):
x, y = MI()
x -= 1
y -= 1
gl.add_edge(x, y)
nums = LII()
graphlist = gl.sort(0)
for node in graphlist:
xorsum[node][0] ^= nums[node]
if node == 0:
break
fa = gl.parent[node]
for depth in range(k << 1):
xorsum[fa][depth] ^= xorsum[node][depth - 1]
#print(xorsum)
q = deque()
q.append((0, -1, [0 for _ in range(k << 1)]))
while q:
node, fa, prev_xors = q.popleft()
final_xors = [x ^ y for x, y in zip(prev_xors, xorsum[node])]
for e in gl.graph[node]:
if e == fa:
continue
send_xors = final_xors[:]
for i in range(k << 1):
send_xors[i] ^= xorsum[e][i - 1]
send_xors = [send_xors[-1]] + send_xors[:-1]
q.append((e, node, send_xors))
odd_xors = 0
for i in range(k, k << 1):
odd_xors ^= final_xors[i]
win[node] = 1 if odd_xors else 0
print(*win)
for _ in range(1):solve() | Python | [
"graphs",
"math",
"trees",
"games"
] | 1,458 | 4,372 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | {
"games": 1,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 3,770 |
98fd00d3c83d4b3f0511d8afa6fdb27b | Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k. | ['implementation', 'number theory', 'greedy', 'math'] | n = int(input())
print n >> 1
while n > 0:
if n % 2 > 0:
print 3,
n -= 3
else:
print 2,
n -= 2
| Python | [
"number theory",
"math"
] | 334 | 107 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,316 |
4fb83b890e472f86045981e1743ddaac | For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum ai she finds among those k nodes.Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following: Print v. Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u. | ['dp', 'greedy', 'graphs', 'binary search', 'dfs and similar', 'trees'] | import sys
input = sys.stdin.readline
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [[] for _ in range(n)]
for i in range(n - 1):
u, v = map(int, input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
stack = [0]
done = [False] * n
par = [0] * n
order = []
while len(stack) > 0:
x = stack.pop()
done[x] = True
order.append(x)
for i in g[x]:
if done[i] == False:
par[i] = x
stack.append(i)
order = order[::-1]
sub = [0] * n
for i in order:
sub[i] = 1
for j in g[i]:
if par[j] == i:
sub[i] += sub[j]
def good(guess):
cnt = [0] * n
for i in order:
if a[i] < guess:
continue
cnt[i] = 1
opt = 0
for j in g[i]:
if par[j] == i:
if cnt[j] == sub[j]:
cnt[i] += cnt[j]
else:
opt = max(opt, cnt[j])
cnt[i] += opt
if cnt[0] >= k:
return True
up = [0] * n
for i in order[::-1]:
if a[i] < guess:
continue
opt, secondOpt = 0, 0
total = 1
for j in g[i]:
val, size = 0, 0
if par[j] == i:
val = cnt[j]
size = sub[j]
else:
val = up[i]
size = n - sub[i]
if val == size:
total += val
else:
if opt < val:
opt, secondOpt = val, opt
elif secondOpt < val:
secondOpt = val
for j in g[i]:
if par[j] == i:
up[j] = total
add = opt
if sub[j] == cnt[j]:
up[j] -= cnt[j]
elif cnt[j] == opt:
add = secondOpt
up[j] += add
for i in range(n):
if a[i] < guess:
continue
total, opt = 1, 0
for j in g[i]:
val, size = 0, 0
if par[j] == i:
val = cnt[j]
size = sub[j]
else:
val = up[i]
size = n - sub[i]
if val == size:
total += val
else:
opt = max(opt, val)
if total + opt >= k:
return True
return False
l, r = 0, max(a)
while l < r:
mid = (l + r + 1) // 2
if good(mid):
l = mid
else:
r = mid - 1
print(l) | Python | [
"graphs",
"trees"
] | 1,205 | 1,826 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,560 |
c7ec7c379ef924497cd742a5b4795d4f | Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.Vasya has n problems to choose from. They are numbered from 1 to n. The difficulty of the i-th problem is d_i. Moreover, the problems are given in the increasing order by their difficulties. The difficulties of all tasks are pairwise distinct. In order to add the i-th problem to the contest you need to pay c_i burles to its author. For each problem in the contest Vasya gets a burles.In order to create a contest he needs to choose a consecutive subsegment of tasks.So the total earnings for the contest are calculated as follows: if Vasya takes problem i to the contest, he needs to pay c_i to its author; for each problem in the contest Vasya gets a burles; let gap(l, r) = \max\limits_{l \le i < r} (d_{i + 1} - d_i)^2. If Vasya takes all the tasks with indices from l to r to the contest, he also needs to pay gap(l, r). If l = r then gap(l, r) = 0. Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks. | ['dp', 'constructive algorithms', 'dsu', 'data structures', 'binary search'] | import sys
range = xrange
input = raw_input
# A very nice implementation of a maximum segment tree with
# some inspiration taken from https://codeforces.com/blog/entry/18051
# This implementation should be able to be modified to do pretty
# much anything one would want to do with segment trees apart from
# persistance.
# Note that especially in python this implementation is much much better
# than most other approches because how slow python can be with function
# calls.
# Currently it allows for two operations, both running in O(log n),
# 'add(l,r,value)' adds value to [l,r)
# 'maxi(l,r)' returns the biggest value on l:r
class super_seg:
def __init__(self,data):
n = len(data)
m = 1
while m<n: m *= 2
self.n = n
self.m = m
self.data = [0]*(2*m)
for i in range(n):
self.data[i+m] = data[i]
for i in reversed(range(m)):
self.data[i] = max(self.data[2*i], self.data[2*i+1])
self.query = [0]*(2*m)
# Push the query on seg_ind to its children
def push(self,seg_ind):
# Let the children know of the queries
q = self.query[seg_ind]
self.query[2*seg_ind] += q
self.query[2*seg_ind+1] += q
self.data[2*seg_ind] += q
self.data[2*seg_ind+1] += q
# Remove queries from seg_ind
self.data[seg_ind] = max(self.data[2*seg_ind],self.data[2*seg_ind+1])
self.query[seg_ind] = 0
# Updates the node seg_ind to know of all queries
# applied to it via its ancestors
def update(self,seg_ind):
# Find all indecies to be updated
seg_ind //= 2
inds = []
while seg_ind>0:
inds.append(seg_ind)
seg_ind//=2
# Push the queries down the segment tree
for ind in reversed(inds):
self.push(ind)
# Make the changes to seg_ind be known to its ancestors
def build(self,seg_ind):
seg_ind//=2
while seg_ind>0:
self.data[seg_ind] = max(self.data[2*seg_ind], self.data[2*seg_ind+1]) + self.query[seg_ind]
seg_ind //= 2
# Lazily add value to [l,r)
def add(self,l,r,value):
l += self.m
r += self.m
l0 = l
r0 = r
while l<r:
if l%2==1:
self.query[l]+= value
self.data[l] += value
l+=1
if r%2==1:
r-=1
self.query[r]+= value
self.data[r] += value
l//=2
r//=2
# Tell all nodes above of the updated
# area of the updates
self.build(l0)
self.build(r0-1)
# Max of data[l,r)
def maxi(self,l,r):
l += self.m
r += self.m
# Apply all the lazily stored queries
self.update(l)
self.update(r-1)
segs = []
while l<r:
if l%2==1:
segs.append(l)
l+=1
if r%2==1:
r-=1
segs.append(r)
l//=2
r//=2
return max(self.data[ind] for ind in segs)
n,a = [int(x) for x in input().split()]
inp = [int(x) for x in sys.stdin.read().split()]
D = inp[::2]
D.append(D[-1])
C = inp[1::2]
C = [a-c for c in C]
Ccum = [0]
for c in C:
Ccum.append(Ccum[-1]+c)
seg = super_seg(Ccum)
stack = []
besta = 0
for i in reversed(range(n)):
val = (D[i+1]-D[i])**2
while stack and stack[-1][0]<=val:
# The previous difference is smaller, remove all knowledge of it
old_val,l,r = stack.pop()
seg.add(l,r,+old_val)
# Add new val to seg
l = i+2
r = stack[-1][1] if stack else n+1
if l<r:
stack.append((val,l,r))
seg.add(l,r,-val)
# Use maxi with the segmenttree to calc the best choice of r
cur_maxi = seg.maxi(i,n+1) - Ccum[i]
besta = max(besta,cur_maxi)
print besta
| Python | [
"graphs"
] | 1,199 | 3,983 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 593 |
40d1ea98aa69865143d44432aed4dd7e | Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. | ['data structures', 'trees'] | #------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,k=map(int,input().split())
l=list(map(int,input().split()))
tree=[0]*2*(2**n)
y=0
def build(arr,start,end,treenode):
if start==end:
#print(end,treenode)
tree[treenode]=arr[end]
#print(tree,end)
return 0
else:
mid=(start+end)//2
y=build(arr,start,mid,2*treenode)
y=build(arr,mid+1,end,2*treenode+1)
y+=1
if (y)%2==0:
tree[treenode]=tree[2*treenode]^tree[2*treenode+1]
else:
tree[treenode]=tree[2*treenode]|tree[2*treenode+1]
#print(tree)
return y
def update1(treenode,k):
if treenode==0:
return
if k%2==0:
tree[treenode]=tree[2*treenode]^tree[2*treenode+1]
else:
tree[treenode]=tree[2*treenode]|tree[2*treenode+1]
update1(treenode//2,k+1)
def update(n,ind,le):
ind=ind+2**(le)-1
#print(ind,)
tree[ind]=n
update1(ind//2,1)
#print(n)
y=build(l,0,2**n-1,1)
#print(tree)
for j in range(k):
p,b=map(int,input().split())
update(b,p,n)
print(tree[1])
| Python | [
"trees"
] | 1,440 | 2,931 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 3,353 |
281b95c3686c94ae1c1e4e2a18b7fcc4 | There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes. | ['math'] | n, a, b, c, t = map(int, raw_input().split(" "))
ts = map(int, raw_input().split(" "))
total = a*n
if b <= c:
for i in xrange(n):
total += (t-ts[i])*(c-b)
print total
| Python | [
"math"
] | 757 | 183 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,428 |
94e58f3f7aa4d860b95d34c7c9f89058 | Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (\forall) and existential (\exists). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: \forall x,x<100 is read as: for all real numbers x, x is less than 100. This statement is false. \forall x,x>x-1 is read as: for all real numbers x, x is greater than x-1. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: \exists x,x<100 is read as: there exists a real number x such that x is less than 100. This statement is true. \exists x,x>x-1 is read as: there exists a real number x such that x is greater than x-1. This statement is true. Moreover, these quantifiers can be nested. For example: \forall x,\exists y,x<y is read as: for all real numbers x, there exists a real number y such that x is less than y. This statement is true since for every x, there exists y=x+1. \exists y,\forall x,x<y is read as: there exists a real number y such that for all real numbers x, x is less than y. This statement is false because it claims that there is a maximum real number: a number y larger than every x. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are n variables x_1,x_2,\ldots,x_n, and you are given some formula of the form f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), where \land denotes logical AND. That is, f(x_1,\ldots, x_n) is true if every inequality x_{j_i}<x_{k_i} holds. Otherwise, if at least one inequality does not hold, then f(x_1,\ldots,x_n) is false.Your task is to assign quantifiers Q_1,\ldots,Q_n to either universal (\forall) or existential (\exists) so that the statement Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if f(x_1,x_2):=(x_1<x_2) then you are not allowed to make x_2 appear first and use the statement \forall x_2,\exists x_1, x_1<x_2. If you assign Q_1=\exists and Q_2=\forall, it will only be interpreted as \exists x_1,\forall x_2,x_1<x_2. | ['dp', 'graphs', 'dfs and similar', 'math'] | import sys
range = xrange
input = raw_input
def toposort(graph):
res = []; found = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# Check for cycle
for node in res:
if any(found[nei] for nei in graph[node]):
return None
found[node] = 0
return res[::-1]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
coupl1 = [[] for _ in range(n)]
coupl2 = [[] for _ in range(n)]
for _ in range(m):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl1[u].append(v)
coupl2[v].append(u)
order = toposort(coupl1)
if order is None:
print -1
sys.exit()
seen1 = list(range(n))
seen2 = list(range(n))
for node in order:
for nei in coupl1[node]:
seen1[nei] = min(seen1[node], seen1[nei])
for node in reversed(order):
for nei in coupl2[node]:
seen2[nei] = min(seen2[node], seen2[nei])
seen = [+(seen1[node] == seen2[node] == node) for node in range(n)]
print sum(seen)
print ''.join('A' if c else 'E' for c in seen) | Python | [
"graphs",
"math"
] | 2,923 | 1,289 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,739 |
e27cff5d681217460d5238bf7ef6a876 | NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles n and the radius of the inner circle r. NN thinks that, using this information, you can exactly determine the radius of the outer circles R so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture. | ['binary search', 'geometry', 'math'] | import math
def quadratic(a, b, c):
return (-1 * b + math.sqrt(b * b - 4 * a * c))/(2 * a)
PI = 3.14159265
x = input().split()
n = int(x[0])
r = int(x[1])
k = 360.0/n;
R = quadratic((2/(1-math.cos(k * PI/180)))-1, - 2 * r, - r * r);
print(R) | Python | [
"math",
"geometry"
] | 820 | 247 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 560 |
e3dcb1cf2186bf7e67fd8da20c1242a9 | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie. | ['strings'] | n=int(input())
map=dict()
l=list()
for i in range(n):
x=input()
l.append(x)
map[l[i]]=map.get(l[i],0)+1
tmp=list()
for k,v in map.items():
tmp.append((v,k))
x,ans=sorted(tmp,reverse=True)[0]
print(ans)
| Python | [
"strings"
] | 498 | 218 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,348 |
de2e2e12be4464306beb0217875f66c7 | The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if a\cdot d = b\cdot c. For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' — 2:1, for 'DKK' — 1:2, and for 'KKKKDD' — 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings. | ['data structures', 'dp', 'hashing', 'number theory'] | import itertools
from bisect import bisect, bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from math import *
from random import *
from heapq import *
from sys import stdin, stdout
import io
import os
import string
def write(s='', end='\n'): stdout.write(s); stdout.write(end)
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
MOD = 10**9+7
def inp(): return int(input())
def inlt(): return (list(map(int, input().split())))
def floatl(): return (list(map(float, input().split())))
def insr(): s = input(); return (list(s[:len(s)-1]))
def ins(): s = input(); return s
def invr(): return (map(int, input().split()))
def yesno(predicate): print("Yes" if predicate else "No")
def add(a, b): return a+b-MOD if a+b > MOD else a+b
def sub(a, b): return a-b+MOD if a-b < 0 else a-b
def read(l, r):
if l == r:
return -1
print("? {} {}".format(l, r))
stdout.flush()
return inp()
def print_arr(arr):
for v in arr:
print(v, end=' ')
print()
def solve():
_ = inp()
s = ins()
cnt = Counter()
ds = ks = 0
for c in s:
if c == 'D':
ds += 1
else:
ks += 1
g = gcd(ds, ks)
ratio = ds//g, ks//g
cnt[ratio] += 1
print(cnt[ratio], end=' ')
print()
# t = 1
t = inp()
for _ in range(t):
solve()
| Python | [
"number theory"
] | 1,502 | 1,427 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,897 |
1f5f5ccbdfcbe5cb2d692475f0726bfd | Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squares diagonally down and to the right. The player who can’t move the piece loses. The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size. | ['games'] | #!/usr/bin/python
c = ['-', '+']
infile = open("input.txt")
outfile = open("output.txt", 'w')
t, k = map(lambda x: int(x), infile.readline().split())
for i in range(t):
n, m = map(lambda x: int(x)-1, infile.readline().split())
if n > m:
n, m = m, n
if k >= 2:
r = n % (2*k + 2)
if r == k or r == 2*k+1:
outfile.write('+\n')
elif r <= k-1:
outfile.write(c[(m+n)%2]+'\n')
else:
outfile.write(c[(m+n+1)%2]+'\n')
else:
if n % 2 == 1:
outfile.write('+\n')
else:
outfile.write(c[(m+n)%2]+'\n')
| Python | [
"games"
] | 596 | 524 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,696 |
b75ec87dcc25fdd04c3388a0051b8719 | After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team "Hemose 3al shagra" (Hemose on the tree).You are given a tree of n vertices where n is a power of 2. You have to give each node and edge an integer value in the range [1,2n -1] (inclusive), where all the values are distinct.After giving each node and edge a value, you should select some root for the tree such that the maximum cost of any simple path starting from the root and ending at any node or edge is minimized.The cost of the path between two nodes u and v or any node u and edge e is defined as the bitwise XOR of all the node's and edge's values between them, including the endpoints (note that in a tree there is only one simple path between two nodes or between a node and an edge). | ['bitmasks', 'constructive algorithms', 'dfs and similar', 'trees'] | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(2**27)
sys.setrecursionlimit(300000)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
def main():
for ik in range(int(input())):
n = int(input())
graph = defaultdict(list)
ind = defaultdict(int)
n = 2 ** n
node = [0] * n
edge = [0] * (n - 1)
for i in range(n - 1):
a, b = map(int, input().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
ind[(a - 1, b - 1)] = i
ind[(b - 1, a - 1)] = i
t = [0]
x = [n]
def dfs(v, p, lev):
if lev%2 == 1:
edge[ind[(v, p)]] = x[0] + t[0]
node[v] = t[0]
else:
node[v] = x[0] + t[0]
if p != -1:
edge[ind[(v, p)]] = t[0]
t[0] += 1
for i in graph[v]:
if i != p:
dfs(i, v, lev + 1)
dfs(0, -1, 0)
print(1)
print(*node)
print(*edge)
t = threading.Thread(target=main)
t.start()
t.join() | Python | [
"graphs",
"trees"
] | 947 | 18,117 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,201 |
5a0f578ef7e9e9f28ee0b5b19be2ca76 | Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex.He needs to remain not more than \lceil \frac{n+m}{2} \rceil edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that \lceil \frac{d_i}{2} \rceil \leq f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges! | ['implementation', 'dfs and similar', 'greedy', 'graphs'] | from __future__ import print_function
from sys import stdin
inp = [int(x) for x in stdin.read().split()]
n, m = inp[0], inp[1]
in_idx = 2
n += 1
adj = [[] for _ in range(n)]
edge_index = [[] for _ in range(n)]
for i in range(m):
a = inp[in_idx]
in_idx += 1
b = inp[in_idx]
in_idx += 1
adj[a].append(b)
edge_index[a].append(i)
adj[b].append(a)
edge_index[b].append(i)
deg = [len(adj[node]) for node in range(n)]
for x in range(n):
if deg[x] & 1:
adj[0].append(x)
edge_index[0].append(m)
deg[0] += 1
adj[x].append(0)
edge_index[x].append(m)
deg[x] += 1
m += 1
used_edge = [False] * m
out = []
for node in range(n):
if deg[node]:
path = []
while deg[node]:
path.append(node)
while deg[node]:
deg[node] -= 1
nxt_node = adj[node].pop()
idx = edge_index[node].pop()
if used_edge[idx] == False:
used_edge[idx] = True
node = nxt_node
break
pre = False
for i in range(1, len(path)):
b = path[i]
a = path[i - 1]
removed = False
if not a or not b:
removed = True
elif i + 1 < len(path) and not path[i + 1]:
removed = False
elif not pre and i & 1 == 0:
removed = True
if removed == False:
out.append('%d %d' % (a, b))
pre = removed
print(len(out))
print('\n'.join(out))
| Python | [
"graphs"
] | 596 | 1,286 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,110 |
5ef966b7d9fbf27e6197b074eca31b15 | You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 0 and n-2 inclusive. All the written labels are distinct. The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. | ['constructive algorithms', 'greedy', 'dfs and similar', 'trees'] |
data = input().rstrip().split()
n = int(data[0])
edges = []
g = {i+1: [] for i in range(n)}
leafes = set()
for _ in range(n-1):
data = input().rstrip().split()
a, b = int(data[0]), int(data[1])
a, b = sorted([a, b])
edges.append((a, b))
g[a].append(b)
g[b].append(a)
for k, v in g.items():
if len(leafes) == 3:
break
if len(v) == 1:
e = sorted([k, v[0]])
leafes.add(tuple(e))
counter = len(leafes)
l_counter = 0
to_print = []
for edge in edges:
a, b = edge
if edge in leafes:
to_print.append(l_counter)
l_counter += 1
else:
to_print.append(counter)
counter += 1
for p in to_print:
print(p)
| Python | [
"graphs",
"trees"
] | 502 | 706 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 2,885 |
3815d18843dbd15a73383d69eb6880dd | Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix. | ['constructive algorithms', 'flows', 'math'] | from functools import reduce
n, m = list(map(int, input().split()))
ns = list(map(int, input().split()))
ms = list(map(int, input().split()))
xn = reduce(lambda acc, cur: acc ^ cur, ns, 0)
xm = reduce(lambda acc, cur: acc ^ cur, ms, 0)
if xn ^ xm != 0:
print('NO')
else:
print('YES')
print(xm ^ ns[0] ^ ms[0], *ms[1:])
for i in range(1, n):
print(ns[i], *[0] * (m - 1))
| Python | [
"graphs",
"math"
] | 678 | 396 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,262 |
ffdef277d0ff8e8579b113f5bd30f52a | Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times k, so they got k+1 pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using 3 cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome s find such minimum k, that you can cut this string into k + 1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. It there is no answer, then print "Impossible" (without quotes). | ['constructive algorithms', 'brute force', 'strings'] | s = input()
l = len(s)
c = s[0]
diff = False
for i in range(0,int(l/2)):
if s[i] != c:
diff = True
if not diff:
print('Impossible')
exit()
s_2 = s + s
for i in range(1,l):
is_palendrome = True
for j in range(int(l/2)):
if s_2[j + i] != s_2[i + l - j-1]:
is_palendrome = False
if is_palendrome and s_2[i:i+l] != s:
print(1)
exit()
print(2)
| Python | [
"strings"
] | 1,683 | 417 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,294 |
c0eec5938787a63fce3052b7e209eda3 | Jamie has recently found undirected weighted graphs with the following properties very interesting: The graph is connected and contains exactly n vertices and m edges. All edge weights are integers and are in range [1, 109] inclusive. The length of shortest path from 1 to n is a prime number. The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. The graph contains no loops or multi-edges. If you are not familiar with some terms from the statement you can find definitions of them in notes section. Help Jamie construct any graph with given number of vertices and edges that is interesting! | ['constructive algorithms', 'graphs', 'shortest paths'] | def main():
n, m = map(int, raw_input().split())
if n == 2:
print 2, 2
print 1, 2, 2
quit()
else:
print 2, 100003
for i in xrange(2, n - 1):
print 1, i, 1
print 1, n - 1, 100003 - n + 1
print 1, n, 2
c, d = 2, 3
for _ in xrange(m - n + 1):
print c, d, 1000000000
if d == n:
c += 1
d = c + 1
else:
d += 1
main()
| Python | [
"graphs"
] | 637 | 443 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,605 |
b46244f39e30c0cfab592a97105c60f4 | Let's consider all integers in the range from 1 to n (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of \mathrm{gcd}(a, b), where 1 \leq a < b \leq n.The greatest common divisor, \mathrm{gcd}(a, b), of two positive integers a and b is the biggest integer that is a divisor of both a and b. | ['implementation', 'number theory', 'greedy', 'math'] |
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
from collections import *
for _ in range(ii()):
n=ii()
if(n%2==0):
print(n//2)
elif(n<=3):
print(1)
else:
print((n-1)//2) | Python | [
"number theory",
"math"
] | 466 | 386 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,179 |
e8ba3fb95800806465386ecbfbe924e9 | Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.You are given two integers l and r. Find two integers x and y such that l \le x < y \le r and l \le LCM(x, y) \le r. | ['constructive algorithms', 'number theory', 'greedy', 'math'] |
# def hcf(a,b):
# if(b==0):
# return a
# else:
# return hcf(b,a%b)
#
#
# def lcm(a,b):
# return (a*b)//hcf(a,b)
#
# x=int(input())
# for i in range(x):
# a,b=map(int,input().split())
# for i in range(a,b+1):
# for j in range(a+1,b+1):
# if(lcm(i,j)*2<=r):
# print(lcm(i,j),lcm(i,j)*2)
# break
# else:
# print('-1 -1')
# break
#
# # # Two separate lists
# # cars = ["Aston", "Audi", "McLaren"]
# # accessories = ["GPS kit", "Car repair-tool kit"]
# #
# # # Single dictionary holds prices of cars and
# # # its accessories.
# # # First three items store prices of cars and
# # # next two items store prices of accessories.
# # prices = {1:"570000$", 2:"68000$", 3:"450000$",
# # 4:"8900$", 5:"4500$"}
# #
# # # Printing prices of cars
# # for index, c in enumerate(cars, start=1):
# # print ("Car: %s Price: %s"%(c, prices[index]))
# #
# # # Printing prices of accessories
# # for index, a in enumerate(accessories,start=1):
# # print ("Accessory: %s Price: %s" \
# # %(a,prices[index+len(cars)]))
# #
# #
# #
# #
# # # a=[1,2,3,4,5,6,7,8,9]
# # # b=0
# # # c=[]
# # # for i in a:
# # # b+=i
# # # c.append(b)
# # # print(c)
# # #
# # #
# # # # a=3.547498
# # # # print('%.5f'%a)
# # #
# # # # #input
# # # # a=list(map(int,input().split()))
# # # #
# # # # #output
# # # # for i in a:
# # # # print(i)
# # # #
# # # #
# # # #
# # # # # try:
# # # # # a=int(input())
# # # # # for i in range(a):
# # # # # b,c=map(int,input().split())
# # # # # e=[]
# # # # # d=list(map(int,input().split()))
# # # # # for k in d:
# # # # # if(k%c==0):
# # # # # e.append('1')
# # # # # else:
# # # # # e.append('0')
# # # # #
# # # # #
# # # # # f=''.join(e)
# # # # # print(str(f))
# # # # #
# # # # # except:
# # # # # pass
# # # #
# # # #
# # # #
# # # #
# # # # # a=int(input())
# # # # # b=list(map(int,input().split()))
# # # # #
# # # # # c=set(b)
# # # # #
# # # # # c.remove(max(c))
# # # # # print(max(c))
# # # # # a=['rahul','ayush','ayush ki bndi',2,6,5,7]
# # # # # with open ('a.txt','w') as b:
# # # # # for i in a:
# # # # # print(i,file=b)
# # # # #
# # # # #
# # # # #
# # # # # # a,b=input()
# # # # # #
# # # # # # # try:
# # # # # # # a=int(input())
# # # # # # # for i in range(a):
# # # # # # # b=int(input())
# # # # # # # c=input()
# # # # # # # d=set(c)
# # # # # # # for j in d:
# # # # # # # if(c.count(j)%2==0):
# # # # # # # b-=c.count(j)
# # # # # # #
# # # # # # # if(b==0):
# # # # # # # print('YES')
# # # # # # # else:
# # # # # # # print('NO')
# # # # # # # except:
# # # # # # # pass
# # # # # #
# # # # # #
# # # # # # # a={'rahul','ram','ayush','akansha','holi','lodaram'}
# # # # # # # print(a)
# # # # # # # print(a)
# # # # # # # print(sorted(a))
# # # # # # #
# # # # # # # # a=int(input())
# # # # # # # #
# # # # # # # # while(a!=0):
# # # # # # # # x=0
# # # # # # # # y=[]
# # # # # # # # l,r,m=map(int,input().split())
# # # # # # # # for i in range(min(l,r),max(l,r)+1):
# # # # # # # # for j in range(min(l,r),max(l,r)+1):
# # # # # # # # for k in range(min(l,r),max(l,r)):
# # # # # # # # n=(m+j-k)//i
# # # # # # # # if(n>0):
# # # # # # # # x+=1
# # # # # # # # y.append((i,j,k))
# # # # # # # #
# # # # # # # #
# # # # # # # # print(y)
# # # # # # # # for i in y:
# # # # # # # # if(len(set(i))==3):
# # # # # # # # print(i)
# # # # # # # # break
# # # # # # # #
# # # # # # # #
# # # # # # # # a-=1
# # # # # # #
# # # # # # #
# # # # # # # # a=int(input())
# # # # # # # #
# # # # # # # # while(a!=0):
# # # # # # # # x=0
# # # # # # # # l,r,m=map(int,input().split())
# # # # # # # # for i in range(min(l,r),max(l,r)+1):
# # # # # # # # for j in range(min(l,r),max(l,r)+1):
# # # # # # # # for k in range(min(l,r),max(l,r)):
# # # # # # # # n=(m+j-k)//i
# # # # # # # # if(n>0):
# # # # # # # # x+=1
# # # # # # # # print(i,j,k)
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # else:
# # # # # # # # continue
# # # # # # # #
# # # # # # # # a-=1
# # # # # # #
# # # # # # # # t = int(input().strip())
# # # # # # # # for _ in range(t):
# # # # # # # # l, r, m = map(int, input().split())
# # # # # # # # max_diff = r - l
# # # # # # # # for i in range(l, r + 1):
# # # # # # # # temp = m - (m - m % i)
# # # # # # # # if temp <= max_diff:
# # # # # # # # if m < l:
# # # # # # # # print('{} {} {}'.format(i, l, l + temp))
# # # # # # # # else:
# # # # # # # # print('{} {} {}'.format(i, l + temp, l))
# # # # # # # # break
# # # # # # #
# # # # # # #
# # # # # # # ##░░░░░░░░░░░░░░░░░░░░░░░░░░░░╔═══╗╔╗╔═══╦═══╗
# # # # # # # # ░░░░░░░░░░░░░░░░░░░░░░░░░░░░║╔═╗╠╝║║╔═╗║╔═╗║
# # # # # # # # ╔══╦═╗╔══╦═╗╔╗░╔╦╗╔╦══╦╗╔╦══╬╝╔╝╠╗║║║║║╠╝╔╝║
# # # # # # # # ║╔╗║╔╗╣╔╗║╔╗╣║░║║╚╝║╔╗║║║║══╬╗╚╗║║║║║║║║░║╔╝
# # # # # # # # ║╔╗║║║║╚╝║║║║╚═╝║║║║╚╝║╚╝╠══║╚═╝╠╝╚╣╚═╝║░║║░
# # # # # # # # ╚╝╚╩╝╚╩══╩╝╚╩═╗╔╩╩╩╩══╩══╩══╩═══╩══╩═══╝░╚╝░
# # # # # # # # ░░░░░░░░░░░░╔═╝║░░░░░░░░░░░░░░░░░░░░░░░░░░░░
# # # # # # # # ░░░░░░░░░░░░╚══╝░░░░░░░░░░░░░░░░░░░░░░░░░░░░
# # # # # # #
# # # # # # # # # try:
# # # # # # # # # a=int(input())
# # # # # # # # # while(a!=0):
# # # # # # # # #
# # # # # # # # # b=int(input())
# # # # # # # # # c,d=map(int,input().split())
# # # # # # # # # e=int(input())
# # # # # # # # # for i in range(e):
# # # # # # # # # f=list(map(int,input().split()))
# # # # # # # # # if(f[0]+f[1]<c):
# # # # # # # # # print(0)
# # # # # # # # # elif(c<f[0]+f[1]<d):
# # # # # # # # # print(c)
# # # # # # # # # elif(f[0]+f[1]>d):
# # # # # # # # # print(d-c)
# # # # # # # # # elif(f[0]+f[1]==c or f[0]+f[1]==d):
# # # # # # # # # print(-1)
# # # # # # # # #
# # # # # # # # # a-=1
# # # # # # # # # except:
# # # # # # # # # pass
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # try:
# # # # # # # # # a=int(input())
# # # # # # # # # while(a!=0):
# # # # # # # # # b=int(input())
# # # # # # # # # c=list(map(int,input().split()))
# # # # # # # # # d=1
# # # # # # # # # for i in c:
# # # # # # # # # d*=i
# # # # # # # # #
# # # # # # # # # if(d%2==0):
# # # # # # # # # print('NO')
# # # # # # # # # else:
# # # # # # # # # print('Yes')
# # # # # # # # # a-=1
# # # # # # # # # except:
# # # # # # # # # pass
# # # # # # # #
# # # # # # # # a={'A':1,'B':2}
# # # # # # # # b=2
# # # # # # # # c=[]
# # # # # # # # for i in a.keys():
# # # # # # # # c.append(i)
# # # # # # # # for i in c:
# # # # # # # # if(a.get(i)==b):
# # # # # # # # print(i)
# # # # # # # # break
# # # # # # # # else:
# # # # # # # # print('no such value :P')
# # # # # # # #
# # # # # # # # # a={'A':1,'B':2}
# # # # # # # # # print(a)
# # # # # # # # # a={x:key for key , x in a.items()}
# # # # # # # # # print(a)
# # # # # # # # # print(a.get(1))
# # # # # # # #
# # # # # # # #
# # # # # # # # # from pytube import YouTube
# # # # # # # # # from pytube import extract
# # # # # # # # # from pytube.streams import Stream
# # # # # # # # #
# # # # # # # # # YouTube("Your link here").streams.first().download()
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # def getPairsCount(arr, n, sum):
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # for i in range(0, n):
# # # # # # # # # for j in range(i + 1, n):
# # # # # # # # # if arr[i] + arr[j] == sum:
# # # # # # # # # c=[]
# # # # # # # # # c.append(str(arr[i]))
# # # # # # # # # c.append(str(arr[j]))
# # # # # # # # #
# # # # # # # # # print(' '.join(c))
# # # # # # # # #
# # # # # # # # # a=int(input())
# # # # # # # # # d=[]
# # # # # # # # # for i in range(1,(a**2)+1):
# # # # # # # # # d.append(i)
# # # # # # # # # arr = d
# # # # # # # # # n = len(arr)
# # # # # # # # # sum = arr[0]+arr[len(arr)-1]
# # # # # # # # # y=getPairsCount(arr,n,sum)
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # #
# # # # # # # # # a=int(input())
# # # # # # # # # for i in range(a):
# # # # # # # # # b,c=map(int,input().split())
# # # # # # # # # print(min(b,c,(b+c)//3))
# # # # # # # #
# # # # # # # #
# # # # # # # # # if a == 0:
# # # # # # # # # return b
# # # # # # # # # return gcd(b % a, a)
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # def lcm(a,b):
# # # # # # # # # return (a*b) // gcd(a,b)
# # # # # # # # #
# # # # # # # # # def getPairsCount(arr, n, sum):
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # c=[]
# # # # # # # # # for i in range(0, n):
# # # # # # # # # for j in range(i + 1, n):
# # # # # # # # # if arr[i] + arr[j] == sum:
# # # # # # # # #
# # # # # # # # # c.append(arr[i])
# # # # # # # # # c.append(arr[j])
# # # # # # # # # return c
# # # # # # # # #
# # # # # # # # # n=int(input())
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # for i in range(n):
# # # # # # # # # x=int(input())
# # # # # # # # # d=[]
# # # # # # # # # for i in range(x):
# # # # # # # # # d.append(i)
# # # # # # # # # arr = d
# # # # # # # # # n = len(arr)
# # # # # # # # # sum = x
# # # # # # # # # y=getPairsCount(arr,n,sum)
# # # # # # # # #
# # # # # # # # # if(x%2==0):
# # # # # # # # # print(x//2,x//2)
# # # # # # # # # else:
# # # # # # # # # e=[]
# # # # # # # # # for i in range(len(y)):
# # # # # # # # # if(i%2==0):
# # # # # # # # # e.append(lcm(y[i],y[i+1]))
# # # # # # # # #
# # # # # # # # # z=(e.index(min(e)))
# # # # # # # # # print(y[z*2],y[(z*2)+1])
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # # for i in range(a):
# # # # # # # # # # b=int(input())
# # # # # # # # # # for j in range(b):
# # # # # # # # # # print('1',end=' ')
# # # # # # # # # # print()
# # # # # # # # #
# # # # # # # # # # a=int(input())
# # # # # # # # # #
# # # # # # # # # # c=[]
# # # # # # # # # #
# # # # # # # # # # while(a!=0):
# # # # # # # # # # b=int(input())
# # # # # # # # # # if(b<=2):
# # # # # # # # # # for j in range(1000):
# # # # # # # # # # c.append(j)
# # # # # # # # # # else:
# # # # # # # # # # for k in range(b):
# # # # # # # # # # for l in range(1000):
# # # # # # # # # # if(k>=2):
# # # # # # # # # # for m in range(k):
# # # # # # # # # # if(c[m]+c[m+1]==c[m+2]):
# # # # # # # # # # pass
# # # # # # # # # # else:
# # # # # # # # # # c.append(l)
# # # # # # # # # # else:
# # # # # # # # # # c.append(l)
# # # # # # # # # # print(c)
# # # # # # # # # # a-=1
# # # # # # # # #
# # # # # # # # # # while(True):
# # # # # # # # # # import random
# # # # # # # # # # #
# # # # # # # # # # # a,b=map(int,input().split())
# # # # # # # # # # #
# # # # # # # # # # # c=random.randint(1,6)
# # # # # # # # # # #
# # # # # # # # # # # print(c)
# # # # # # # # # #
# # # # # # # # # # # while(True):
# # # # # # # # # # # a=[1,2,3]
# # # # # # # # # # #
# # # # # # # # # # # i=int(input('Enter any number to check thatt it is present in list or not'))
# # # # # # # # # # #
# # # # # # # # # # # if(i in a):
# # # # # # # # # # # print('Yes')
# # # # # # # # # # # else:
# # # # # # # # # # # print('No')
# # # # # # # # # # # #there are two w
# # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #for i in range(len(b))
# # # # # # # # # # #print(9n-1)
# # # # # # # # # #
# # # # # # # # # # #prin(n-1)# for i in range(a):
# # # # # # # # # #
# # # # # # # # # # # b = list(map(int,input().split()))
# # # # # # # # # # # if b[0]>3 and b[1]>3 and b[2]>3:
# # # # # # # # # # # print(7)
# # # # # # # # # # # else:
# # # # # # # # # # # if 1 in b:
# # # # # # # # # # # c = b.count(1)
# # # # # # # # # # # if c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(2)
# # # # # # # # # # # elif c==1:
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif c==2 and b.count(0)==1:
# # # # # # # # # # # print(2)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif 2 in b:
# # # # # # # # # # # c = b.count(2)
# # # # # # # # # # # if c==3:
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif c==2 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(5)
# # # # # # # # # # # elif 3 in b:
# # # # # # # # # # # if c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(6)
# # # # # # # # # # # else:
# # # # # # # # # # # if b.count(0)==3:
# # # # # # # # # # # print(0)
# # # # # # # # # # # elif b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #
# # # # # # # # # # # for i in range(a):
# # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # #
# # # # # # # # # # # if(b[0]>3 and b[1]>3 and b[2]>3):
# # # # # # # # # # # print(7)
# # # # # # # # # # #
# # # # # # # # # # # else:
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # if(1 in b):
# # # # # # # # # # # c=b.count(1)
# # # # # # # # # # # if(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(2)
# # # # # # # # # # # elif(c==1):
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif(c==2 and b.count(0)==1):
# # # # # # # # # # # print(2)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # elif(2 in b):
# # # # # # # # # # # c=b.count(2)
# # # # # # # # # # # if(c==2 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif(c==3):
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(5)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # elif(3 in b):
# # # # # # # # # # # c=b.count(3)
# # # # # # # # # # # if(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(6)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # else:
# # # # # # # # # # # if(b.count(0)==3):
# # # # # # # # # # # print(0)
# # # # # # # # # # # elif(b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # #a-=1
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #
# # # # # # # # # # # for i in range(a):
# # # # # # # # # # # b,c,d=map(int,input().split())
# # # # # # # # # # # if(a==0):
# # # # # # # # # # # if(b==0 and c==0):
# # # # # # # # # # # print(0)
# # # # # # # # # # # if(b==0 or c==0):
# # # # # # # # # # # print(1)
# # # # # # # # # # # if(b>=2 and c>=2):
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # # # # a=[1,3]
# # # # # # # # # # # #
# # # # # # # # # # # # b=[2]
# # # # # # # # # # # #
# # # # # # # # # # # # c=a+b
# # # # # # # # # # # # print(c)
# # # # # # # # # # # # print(id(c))
# # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # a='rahul'
# # # # # # # # # # # # # b=a
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # print()
# # # # # # # # # # # # #
# # # # # # # # # # # # # for i in range(5):
# # # # # # # # # # # # # a+='mahajan'
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # f
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # # a='rahul'+'mahajan'
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # b=a
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # def ckeckList(lst):
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # ele = lst[0]
# # # # # # # # # # # # # # # chk = True
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # Comparing each element with first item
# # # # # # # # # # # # # # # for item in lst:
# # # # # # # # # # # # # # # if ele != item:
# # # # # # # # # # # # # # # chk = False
# # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # if (chk == True):
# # # # # # # # # # # # # # # print("Equal")
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # print("Not equal")
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # Driver Code
# # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # ckeckList(a)
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # b=a[0]
# # # # # # # # # # # # # # # c=True
# # # # # # # # # # # # # # # for i in a:
# # # # # # # # # # # # # # # if(i!=b):
# # # # # # # # # # # # # # # c=False
# # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # if(c==True):
# # # # # # # # # # # # # # # print(1)
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # x=0
# # # # # # # # # # # # # # # y=0
# # # # # # # # # # # # # # # d=[]
# # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # for i in range(a):
# # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # c=[]
# # # # # # # # # # # # # # # for i in range(1,b+1):
# # # # # # # # # # # # # # # c.append(i)
# # # # # # # # # # # # # # # if(max(c)==1):
# # # # # # # # # # # # # # # print(1)
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # if(len(c)%2==0):
# # # # # # # # # # # # # # # for j in range(len(c)):
# # # # # # # # # # # # # # # if(j<((len(c)//2)-1)):
# # # # # # # # # # # # # # # x=c[j]+c[len(c)-2-j]
# # # # # # # # # # # # # # # d.append(x)
# # # # # # # # # # # # # # # print(len(d)+1)
# # # # # # # # # # # # # # # elif(len(c)//2!=0):
# # # # # # # # # # # # # # # print((len(c)//2)+1)
# # # # # # # # # # # # # # # # for k in range(len(c)):
# # # # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # # y=c[k]+c[len(c)-2-k]
# # # # # # # # # # # # # # # # e.append(y)
# # # # # # # # # # # # # # # # print(len(e)+1)
# # # # # # # # # # # # # # # d.clear()
# # # # # # # # # # # # # # # e.clear()
# # # # # # # # # # # # # # # # print(36+10)
# # # # # # # # # # # # # # # # print(36-8)
# # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # i=0
# # # # # # # # # # # # # # # # # while(a!=0):
# # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # if(b==1):
# # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # elif(b==2):
# # # # # # # # # # # # # # # # # print((-1))
# # # # # # # # # # # # # # # # # elif(b>2):
# # # # # # # # # # # # # # # # # while(c==1):
# # # # # # # # # # # # # # # # # if(b%6==0):
# # # # # # # # # # # # # # # # # c=(b%6)
# # # # # # # # # # # # # # # # # i+=1
# # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # c=b*2
# # # # # # # # # # # # # # # # # i+=1
# # # # # # # # # # # # # # # # # print(i)
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # while(a!=0):
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # b,c,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # # # # for i in range(d+1):
# # # # # # # # # # # # # # # # # # if(i%b==c):
# # # # # # # # # # # # # # # # # # e.append(i)
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # print(max(e))
# # # # # # # # # # # # # # # # # # a-=1
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # a="""Number 1\t The Larch
# # # # # # # # # # # # # # # # # # # Number 2\t the horse chestnut"""
# # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # a="""hello1\trahul
# # # # # # # # # # # # # # # # # # # # mahajan\tmahajana
# # # # # # # # # # # # # # # # # # # # """
# # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # #print(c)
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # d=min(c)
# # # # # # # # # # # # # # # # # # # # # e=c.count(d)
# # # # # # # # # # # # # # # # # # # # # f=0
# # # # # # # # # # # # # # # # # # # # # while(f!=e):
# # # # # # # # # # # # # # # # # # # # # c.remove(a[f])
# # # # # # # # # # # # # # # # # # # # # f+=1
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # z=sorted(c,reverse= 021)
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # g=max(z)
# # # # # # # # # # # # # # # # # # # # # h=z.count(g)
# # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # while(j!=h):
# # # # # # # # # # # # # # # # # # # # # z.remove(z[j])
# # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # #print(z)
# # # # # # # # # # # # # # # # # # # # # print(len(z))
# # # # # # # # # # # # # # # # # # # # # a=[1,1,2,3,3]
# # # # # # # # # # # # # # # # # # # # # for i in a:
# # # # # # # # # # # # # # # # # # # # # a.remove(min(a))
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # a=[1,1,1,2,2,3,4,3]
# # # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # d=min(c)
# # # # # # # # # # # # # # # # # # # # # # e=c.count(d)
# # # # # # # # # # # # # # # # # # # # # # f=0
# # # # # # # # # # # # # # # # # # # # # # while(f!=e):
# # # # # # # # # # # # # # # # # # # # # # c.remove(a[f])
# # # # # # # # # # # # # # # # # # # # # # f+=1
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # z=sorted(c,reverse=1)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # g=max(z)
# # # # # # # # # # # # # # # # # # # # # # h=z.count(g)
# # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # while(j!=h):
# # # # # # # # # # # # # # # # # # # # # # c.remove(a[j])
# # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # print(z)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # n,b,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # for i in range(n):
# # # # # # # # # # # # # # # # # # # # # # # if(a[i]>b):
# # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # if(len(a)==0):
# # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # c+=a[i]
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # if(c>d):
# # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # if(a[i]>=b):
# # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # #print(a)
# # # # # # # # # # # # # # # # # # # # # # # a=map(str,input().split())
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # c=set(a)
# # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # while(1):
# # # # # # # # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # c=b.count(1)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # d=b.count(2)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # e=b.count(3)
x=int(input())
for i in range(x):
a,b=map(int,input().split())
if(a*2<=b):
print(a,a*2)
else:
print('-1 -1')
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # if(c==0 or d==0 or e==0):
# # # # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # if(c<=d and c<=e):
# # # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # elif(d<=c and d<=e):
# # # # # # # # # # # # # # # # # # # # # # # # print(d)
# # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # print(e)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # while(1):
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # n,b,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(n):
# # # # # # # # # # # # # # # # # # # # # # # # # if(a[i]>b):
# # # # # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # if(len(a)==0):
# # # # # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # c+=a[i]
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # if(c>d):
# # # # # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # if(a[i]>=b):
# # # # # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # a=['r','b','g']
# # # # # # # # # # # # # # # # # # # # # # # # # c=len(a)
# # # # # # # # # # # # # # # # # # # # # # # # # #print(c)
# # # # # # # # # # # # # # # # # # # # # # # # # #print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # print(a[i-1])
# # # # # # # # # # # # # # # # # # # # # # # # # print('-'*20)
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # print(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # while(len(b)!=0):
# # # # # # # # # # # # # # # # # # # # # # # # # # # if(len(b)%2==0):
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(y)
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # # # if(len(b)==1):
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(y)
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[a-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[len(b)-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a=a-1
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # print('{0} {1}'.format(c,d))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # s=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+s[len(s)-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(maxi(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(x[a-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a=[]
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # for i in range(10):
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a.append(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(c[9])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # j=j+c[len(a)-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(a)-1)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(max(a)) | Python | [
"number theory",
"math"
] | 313 | 40,546 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,018 |
9115965ff3421230eac37b22328c6153 | Mr. F has n positive integers, a_1, a_2, \ldots, a_n.He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. | ['number theory'] | def gcd(a, b):
while b:
c = a%b
a = b
b = c
return a
import sys
raw_input = sys.stdin.readline
sieve = [0] * (15000001)
i = 2
while i <= 15000000:
sieve[i] = 2
i += 2
i = 3
while i < 15000000:
if sieve[i]:
i += 2
continue
sieve[i] = i
j = i*i
while j < 15000000:
if sieve[j] == 0:
sieve[j] = i
j += i
i += 2
n = int(raw_input())
l = [int(x) for x in raw_input().split()]
totalGCD = l[0]
for x in l:
totalGCD = gcd(x, totalGCD)
for i in xrange(n):
l[i] /= totalGCD
# TODO: defaultdict might be too slow?!
from collections import defaultdict
dp = defaultdict(int)
for x in l:
y = x
while y > 1:
lp = sieve[y]
dp[lp] += 1
while y % lp == 0:
y /= lp
highest = 0
for x in dp:
highest = max(highest, dp[x])
if highest == 0:
highest = -1
else:
highest = n - highest
print highest
| Python | [
"number theory"
] | 505 | 945 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,144 |
fb5c6182b9cad133d8b256f8e72e7e3b | The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country. | ['dp', 'dfs and similar', 'trees', 'graphs'] | n=int(input())
t=[0]*(n+1)
u,v=[[]for i in range(n+1)],[[]for i in range(n+1)]
for i in range(n-1):
x,y=map(int,input().split())
t[y]=1
u[x].append(y)
v[y].append(x)
d, s = u[1] + v[1], len(v[1])
for i in u[1]:
t[i]=1
v[i].remove(1)
for i in v[1]:
t[i]=-1
u[i].remove(1)
while d:
b=d.pop()
for i in u[b]:
t[i]=t[b]+1
v[i].remove(b)
for i in v[b]:
t[i]=t[b]-1
u[i].remove(b)
d+=u[b]+v[b]
s+=len(v[b])
m=min(t)
print(s+m)
print(' '.join(map(str,[i for i in range(1,n+1) if t[i]==m])))
| Python | [
"graphs",
"trees"
] | 890 | 567 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 4,040 |
f70ac2c4e0f62f9d6ad1e003aedd86b2 | Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times. | ['probabilities'] | n,m = map(int, input().split())
s=0
for i in range(n):
s+=(i+1)*(pow((i+1)/n,m)-pow(i/n,m))
print(s) | Python | [
"probabilities"
] | 613 | 104 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 990 |
55da4611bc78d55c228d0ce78bd02fd3 | Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly. | ['geometry', 'brute force'] | import itertools
from itertools import permutations as perm
l = [[int(x) for x in input().split()] for i in range(8)]
def dist2(p0,p1):
return sum([(p0[i]-p1[i])**2 for i in range(3)])
def check(c):
dists = [[(c[i][0]-c[j][0])**2+(c[i][1]-c[j][1])**2+(c[i][2]-c[j][2])**2 for i in range(8)] for j in range(8)]
s2 = min([min(l) for l in dists])
return all([sorted(l) == [0,s2,s2,s2,2*s2,2*s2,2*s2,3*s2] for l in dists])
def sub(p0,p1):
return [p0[i]-p1[i] for i in range(3)]
def add(p0,p1):
return [p0[i]+p1[i] for i in range(3)]
def div(p0,x):
return [p0[i]//x for i in range(3)]
def cross(p0,p1):
return [p0[(i+1)%3]*p1[(i+2)%3]-p0[(i+2)%3]*p1[(i+1)%3] for i in range(3)]
def match(p0,p1):
return sorted(p0) == sorted(p1)
def poss(i,prior,s):
if i == len(l): return check(prior)
for p in perm(l[i]):
if i == 1: print(p)
possible = True
for p2 in prior:
if dist2(p,p2) not in [s,2*s,3*s]:
possible = False
break
if possible:
if poss(i+1,prior+[p]): return True
return False
solved = False
for l2 in perm(l,3):
p0 = l2[0]
for p1 in perm(l2[1]):
s2 = dist2(p0,p1)
if s2 == 0: continue
s = round(s2**.5)
if s**2 != s2: continue
for p2 in perm(l2[2]):
if dist2(p0,p2) != s2 or dist2(p1,p2) != 2*s2: continue
p3 = sub(add(p1,p2),p0)
x = div(cross(sub(p1,p0),sub(p2,p0)),s)
p4,p5,p6,p7 = add(p0,x),add(p1,x),add(p2,x),add(p3,x)
l3 = [p0,p1,p2,p3,p4,p5,p6,p7]
if sorted([sorted(p) for p in l]) == sorted([sorted(p) for p in l3]):
print("YES")
used = [False for i in range(8)]
for p in l:
for i in range(8):
if used[i]: continue
if match(p,l3[i]):
print(l3[i][0],l3[i][1],l3[i][2])
used[i] = True
break
solved = True
break
if solved: break
if solved: break
if not solved: print("NO")
#if not poss(1,[l[0]]): print("NO")
| Python | [
"geometry"
] | 995 | 2,223 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,364 |
4c387ab2a0d028141634ade32ae97d03 | Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. | ['constructive algorithms', 'graphs', 'math'] | n=int(input())
f=[]
f1=s1=0
for i in range(n,0,-1):
if f1<=s1:
f1+=i
f.append(i)
else:
s1+=i
print(abs(f1-s1))
print(str(len(f)),*f)
| Python | [
"graphs",
"math"
] | 282 | 165 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,653 |
c98abd01f026df4254bd29cbeb09dd6f | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.Vasya drew several distinct points with integer coordinates on a plane and then drew an U-shaped parabola through each pair of the points that have different x coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.The internal area of an U-shaped parabola is the part of the plane that lies strictly above the parabola when the y axis is directed upwards. | ['data structures', 'geometry', 'math'] | import sys
def read(tp=int):
return tp(raw_input())
def readn(tp=int):
ln = raw_input().split()
return [tp(x) for x in ln]
def readf(*tp):
ln = raw_input().split()
return [x(y) for x,y in zip(tp,ln)]
################################################################################
def ori(p, q, r):
x1 = q[0] - p[0]
y1 = q[1] - p[1]
x2 = r[0] - p[0]
y2 = r[1] - p[1]
return x1 * y2 - x2 * y1
n = read()
pt = []
for i in range(n):
x, y = readn()
pt.append((x, y - x * x))
pt.sort(reverse=True)
qt = []
for p in pt:
while len(qt) >= 2 and ori(qt[-2], qt[-1], p) <= 0:
qt.pop()
qt.append(p)
if len(qt) >= 2 and qt[-1][0] == qt[-2][0]:
qt.pop()
if len(qt) < 2:
print 0
sys.exit(0)
p = qt[0]
q = qt[1]
s = 1
d = 1
for r in qt[2:]:
if ori(p, q, r) == 0:
d += 1
q = r
else:
d = 1
p = q
q = r
s += d
print s
| Python | [
"math",
"geometry"
] | 763 | 939 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,390 |
0682d5ee1b5b160ece449c4676a369a7 | Alice and Bob are playing a game. They have an array of positive integers a of size n.Before starting the game, Alice chooses an integer k \ge 0. The game lasts for k stages, the stages are numbered from 1 to k. During the i-th stage, Alice must remove an element from the array that is less than or equal to k - i + 1. After that, if the array is not empty, Bob must add k - i + 1 to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the k-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of k such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible. | ['binary search', 'data structures', 'games', 'greedy', 'implementation'] | import copy
t = int(input())
for _ in range(t):
n = int(input())
ass = sorted(list(map(int, input().split())))
for k in range(n, 0, -1):
l = copy.deepcopy(ass)
for i in range(1, k + 1):
while len(l) > 0 and l[-1] > k - i + 1:
l.pop()
if len(l) == 0:
break
else:
l.pop()
if len(l) > 0:
l.pop(0)
else:
print(k)
break
else:
print(0)
| Python | [
"games"
] | 882 | 543 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,038 |
39e7083c9d16a8cb92fc93bd8185fad2 | Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l, r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms: 1 l r x — Bash guesses that the gcd of the range [l, r] is x. Report if this guess is almost correct. 2 i y — Bash sets ai to y. Note: The array is 1-indexed. | ['data structures', 'number theory'] | #!/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
class dict(dict):
"""dict() -> new empty dictionary"""
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
return dict.iteritems(self)
def keys(self):
"""D.keys() -> a set-like object providing a view on D's keys"""
return dict.iterkeys(self)
def values(self):
"""D.values() -> an object providing a view on D's values"""
return dict.itervalues(self)
def gcd(x, y):
"""greatest common divisor of x and y"""
while y:
x, y = y, x % y
return x
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
def main():
a = [0] * (524288 << 1 | 1)
n, arr = int(input()), [int(num) for num in input().split()]
for i in range(n):
p = i + 524289
a[p] = arr[i]
while p != 1:
p >>= 1
a[p] = gcd(a[p << 1], a[p << 1 | 1])
for i in range(int(input())):
q = [int(num) for num in input().split()]
if q[0] == 1:
p = 524288 + q[1]
while p != 1 and (a[p] % q[3] == 0):
if p & (p + 1) == 0:
p = n + 524289
break
p = (p + 1) >> 1
while p < 524288:
p <<= 1
p += int(a[p] % q[3] == 0)
if p - 524288 >= q[2]:
print('YES')
else:
p += 1
while p != 1 and (a[p] % q[3] == 0):
if p & (p + 1) == 0:
p = n + 524289
break
p = (p + 1) >> 1
while p < 524288:
p <<= 1
p += int(a[p] % q[3] == 0)
print('YES' if p - 524288 > q[2] else 'NO')
else:
p = q[1] + 524288
a[p] = q[2]
while p != 1:
p >>= 1
a[p] = gcd(a[p << 1], a[p << 1 | 1])
if __name__ == '__main__':
main()
| Python | [
"number theory"
] | 1,043 | 2,451 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 161 |
a3c844e3ee6c9596f1ec9ab46c6ea872 | The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions: For any l and r (1 \leq l \leq r \leq n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} \ldots s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} \ldots t_{r}; The number of zeroes in t is the maximum possible.A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, \ldots, i_k such that i_1 < i_2 < \ldots < i_k and p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}. The length of the subsequence is k.If there are multiple substrings which satisfy the conditions, output any. | ['data structures', 'greedy', 'math', 'strings'] | data = [int(i) for i in input()]
n = len(data)
minval = [0]* n
minval[-1] = 2 * data[-1] - 1
for i in range(n-2, -1, -1):
if data[i] == 1:
minval[i] = min(1, minval[i+1] + 1)
else:
minval[i] = min(-1, minval[i+1] - 1)
ans = [i for i in data]
for i in range(n-1, -1, -1):
if minval[i] == 1:
ans[i] = 0
ans2 = [str(i) for i in ans]
print("".join(ans2))
# print(minval) | Python | [
"math",
"strings"
] | 1,059 | 407 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,344 |
54e9c6f24c430c5124d840b5a65a1bc4 | Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 \le i \le n-1 then a_i = c^i.Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change a_i to a_{p_i}), then Do the following operation any number of times: pick an index i and change a_i to a_i - 1 or a_i + 1 (i.e. increment or decrement a_i by 1) with a cost of 1. Find the minimum cost to transform a_0, a_1, ..., a_{n-1} into a power sequence. | ['number theory', 'sortings', 'brute force', 'math'] | import copy
import math
n = int(input())
nums = list(map(int,input().split()))
nums.sort()
f_1 = 0
for i in range(n):
f_1 += math.fabs(1 - nums[i])
term = f_1 + nums[-1]
max_c = math.floor(math.pow(term,1/(n-1)))
cost2 = float('inf')
prev_cost = 0
for c in range(1,max_c+1):
cost = 0
for i in range(n):
cost += math.fabs((c**i - nums[i]))
cost2 = min(cost,cost2)
print(int(cost2)) | Python | [
"math",
"number theory"
] | 688 | 416 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,828 |
933167c31c0f53a43e840cc6cf153f8d | Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that n\cdot m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. | ['constructive algorithms', 'number theory', 'math'] | k = input()
v = ["a", "e", "i", "o", "u"]
n = m = None
for i in xrange(5, int(k**0.5) + 1):
if k % i == 0:
n = i
m = k / i
break
if not n:
print -1
else:
ans = []
row = v * (n/5) + v[:n%5]
for i in xrange(m):
ans.extend(row[i:] + row[:i])
print "".join(ans) | Python | [
"number theory",
"math"
] | 693 | 271 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,756 |
3ac91d8fc508ee7d1afcf22ea4b930e4 | Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats! | ['dp', 'constructive algorithms', 'implementation', 'brute force', 'strings'] | import sys
t =sys.stdin.readline()
t = int(t)
for tttt in range(t) :
org=[]
dic={}
n =sys.stdin.readline()
n = int(n)
users=sys.stdin.readline().split()
users=['?']+users
for k in range(n+1):
dic[users[k]]=k
m = sys.stdin.readline()
m=int(m)
messusers=[]
messages=[]
for mmmm in range(m):
curr=[]
ms=sys.stdin.readline().strip()
org.append(ms)
pos=ms.find(':')
name=ms[:pos]
ms=' '+ms[pos+1:]+' '
ms=ms.replace('.',' ')
ms=ms.replace('?',' ')
ms=ms.replace(',',' ')
ms=ms.replace('!',' ')
messusers.append(dic[name])
for nm in users:
nmm=' '+nm+' '
if nmm in ms:
curr.append(dic[nm])
messages.append(curr)
m=len(messages)
found=True
for i in range(m):
if messusers[i]!=0:
continue
now=[]
if i > 0 :
now.append(messusers[i-1])
if i < m-1 and messusers[i+1]!=0:
now.append(messusers[i+1])
now+=messages[i]
cand=[]
for us in range(1,len(users)):
if us not in now:
cand.append(us)
if len(cand)==0 :
found=False
break
else:
messusers[i]=cand[0]
#filter
filter=[]
if i<m-1:
filter+=messages[i+1]
if i<m-2 and messusers[i+2]!=0:
filter.append(messusers[i+2])
for k in cand:
if k in filter:
messusers[i]=k
break
org[i]=users[messusers[i]]+org[i][1:]
if found:
for ms in org:
print ms
else:
print 'Impossible'
| Python | [
"strings"
] | 916 | 1,455 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 2,323 |
0e909868441b3af5be297f44d3459dac | Marin feels exhausted after a long day of cosplay, so Gojou invites her to play a game!Marin and Gojou take turns to place one of their tokens on an n \times n grid with Marin starting first. There are some restrictions and allowances on where to place tokens: Apart from the first move, the token placed by a player must be more than Manhattan distance k away from the previous token placed on the matrix. In other words, if a player places a token at (x_1, y_1), then the token placed by the other player in the next move must be in a cell (x_2, y_2) satisfying |x_2 - x_1| + |y_2 - y_1| > k. Apart from the previous restriction, a token can be placed anywhere on the matrix, including cells where tokens were previously placed by any player. Whenever a player places a token on cell (x, y), that player gets v_{x,\ y} points. All values of v on the grid are distinct. You still get points from a cell even if tokens were already placed onto the cell. The game finishes when each player makes 10^{100} moves.Marin and Gojou will play n^2 games. For each cell of the grid, there will be exactly one game where Marin places a token on that cell on her first move. Please answer for each game, if Marin and Gojou play optimally (after Marin's first move), who will have more points at the end? Or will the game end in a draw (both players have the same points at the end)? | ['data structures', 'dp', 'games', 'hashing', 'implementation', 'math', 'number theory', 'sortings'] | import heapq
import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def f(x, y, x1, y1, x2, y2):
return x1 + y1 <= x + y <= x2 + y2 and x1 - y1 <= x - y <= x2 - y2
def out(x, y, x1, y1, x2, y2):
return not (x1 + y1 <= x + y <= x2 + y2) and not (x1 - y1 <= x - y <= x2 - y2)
def merge(x1, y1, x2, y2, x3, y3, x4, y4):
new = [0] * 4
if f(x1, y1, x3, y3, x4, y4):
new[0], new[1] = x1, y1
elif out(x1, y1, x3, y3, x4, y4):
new[0], new[1] = x3, y4
else:
if x3 - y3 <= x1 - y1 <= x4 - y4:
num = ((x1 - y1) - (x3 - y3)) / 2
new[0], new[1] = x3 + num, y3 - num
else:
num = ((x1 + y1) - (x3 + y3)) / 2
new[0], new[1] = x3 + num, y3 + num
if f(x2, y2, x3, y3, x4, y4):
new[2], new[3] = x2, y2
elif out(x2, y2, x3, y3, x4, y4):
new[2], new[3] = x4, y4
else:
if x3 + y3 <= x2 + y2 <= x4 + y4:
num = (x4 + y4 - (x2 + y2)) / 2
new[2], new[3] = x4 - num, y4 - num
else:
num = ((x4 - y4) - (x2 - y2)) / 2
new[2], new[3] = x4 - num, y4 + num
return new
def main():
n, k = list(map(int, input().split(' ')))
v = [list(map(int, input().split(' '))) for _ in range(n)]
max_id = None
d = [0] *(n * n + 1)
for i in range(n):
for j in range(n):
d[v[i][j]] = i * (n + 1) + j
if v[i][j] == n * n:
max_id = [i, j]
valid = [(max_id[0] - k), max_id[1], (max_id[0] + k), max_id[1]]
for vnow in range(n * n, 0, -1):
x, y = d[vnow] // (n + 1), d[vnow] % (n + 1)
#print(valid, vnow, x, y)
if not f(x, y, valid[0], valid[1], valid[2], valid[3]):
continue
if f(valid[0], valid[1], x - k, y, x + k, y) and f(valid[2], valid[3], x - k, y, x + k, y):
continue
new = merge(valid[0], valid[1], valid[2], valid[3], x - k, y, x + k, y)
valid.clear()
valid = new
#print(valid)
for i in range(n):
res = ['G'] * n
for j in range(n):
if f(i, j, valid[0], valid[1], valid[2], valid[3]):
res[j] = 'M'
print(''.join(res))
return
main() | Python | [
"math",
"number theory",
"games"
] | 1,437 | 4,089 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,719 |
513480a6c7a715e237c3a63805208039 | This is an interactive problem.There is an unknown integer x (1\le x\le n). You want to find x.At first, you have a set of integers \{1, 2, \ldots, n\}. You can perform the following operations no more than 10000 times: A a: find how many numbers are multiples of a in the current set. B a: find how many numbers are multiples of a in this set, and then delete all multiples of a, but x will never be deleted (even if it is a multiple of a). In this operation, a must be greater than 1. C a: it means that you know that x=a. This operation can be only performed once. Remember that in the operation of type B a>1 must hold.Write a program, that will find the value of x. | ['interactive', 'number theory', 'math'] | n = int(input())
is_prime = [1] * (n + 1)
primes = [2]
i = 3
while i * i <= n:
if is_prime[i] == 1:
primes.append(i)
for j in range(i * i, n + 1, i * 2):
is_prime[j] = 0
i += 2
for j in range(i, n + 1, 2):
if is_prime[j]:
primes.append(j)
s = set(range(1, n + 1))
ans = 1
l = 0
while l < len(primes):
if ans * primes[l] > n:
break
r = min(l + min(400, max(50, (len(primes) - l) // 2)), len(primes))
for p in primes[l:r]:
if ans * p > n:
break
print(f'B {p}')
input()
for q in range(p, n + 1, p):
s.discard(q)
print(f'A 1')
res = int(input())
if res > len(s):
for p in primes[l:r]:
if ans * p > n:
break
print(f'A {p}')
res = int(input())
q = p
while res > 0:
ans *= p
q *= p
if ans * p > n:
break
print(f'A {q}')
res = int(input())
l = r
break
l = r
for p in primes[l:]:
if ans * p > n:
break
q = p
while ans * q <= n:
expected = 0
for i in range(q, n + 1, q):
if i in s:
expected += 1
print(f'A {q}')
res = int(input())
if res == expected:
break
ans *= p
q *= p
print(f'C {ans}')
| Python | [
"number theory",
"math"
] | 784 | 1,448 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 811 |
0ba97bcfb5f539c848f2cd097b34ff33 | You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to n - 1, but not the whole string). You need to calculate the minimum number of characters to be deleted from string s so that it becomes good. | ['implementation', 'strings'] | for _ in range(int(input())):
n = int(input())
s = input().strip()
ans = 0
i = 0
while(i < n and s[i] == "<"):
ans += 1
i += 1
ans1 = 0
i = n - 1
while(i > -1 and s[i] == ">"):
ans1 += 1
i -= 1
print(min(ans, ans1))
| Python | [
"strings"
] | 1,175 | 284 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,944 |
71dc07f0ea8962f23457af1d6509aeee | The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a. | ['constructive algorithms', 'number theory', 'greedy'] | def getDictionary(myList):
myDict = {}
for i in range(0, len(myList)):
if (myList[i] in myDict):
myDict[myList[i]] = myDict[myList[i]] + 1;
else:
myDict[myList[i]] = 1;
return myDict
def counting(sizeOfMother, myDict):
winTable = []
for i in range(0, sizeOfMother):
x = next(iter(myDict.keys()))
# Usun ten element
if (myDict[x] > 1):
myDict[x] = myDict[x] - 1;
else:
del myDict[x]
for j in range(0, len(winTable)):
gcd = searchNWD(x, winTable[j])
# Usun ten element
if (myDict[gcd] <= 2):
del myDict[gcd]
else:
myDict[gcd] = myDict[gcd] - 2;
winTable.append(x)
return winTable
def searchNWD(a, b):
temporary = 0
while(a != 0) and (b != 0):
if(a > b):
a = a % b
else:
b = b % a
if(a > 0):
return a
else:
return b
######################
sizeOfMotherG = int(input())
numberInMotherG = list(map(int, input().split()))
numberInMotherG.sort(reverse=True)
myDictG = getDictionary(numberInMotherG)
w = counting(sizeOfMotherG, myDictG)
for i in range(0, sizeOfMotherG):
print(w[i], end=" ") | Python | [
"number theory"
] | 415 | 1,304 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,730 |
1ee7ec135d957db2fca0aa591fc44b16 | Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. | ['greedy', 'graphs', 'constructive algorithms', 'dfs and similar', 'trees'] | #https://codeforces.com/problemset/problem/761/E
def solve():
def push(u, v, g):
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
n = int(input())
g = {}
for _ in range(n-1):
u, v = map(int, input().split())
push(u, v, g)
for u in g:
if len(g[u]) > 4:
return 'NO', None
d = {}
build(1, 0, 0, 0, 31, -1, d, g)
s = ''
for u in range(1, n+1):
x, y = d[u]
s += str(x) + ' ' + str(y)
s += '\n'
return 'YES', s
def cal_pos(dir_, cur_x, cur_y, cur_base):
if dir_ == 0:
return cur_x, cur_y + (1<<cur_base)
elif dir_ == 1:
return cur_x + (1<<cur_base), cur_y
elif dir_ == 2:
return cur_x, cur_y - (1<<cur_base)
else:
return cur_x - (1<<cur_base), cur_y
def build(u, p, cur_x, cur_y, cur_base, pre_dir, d, g):
d[u] = [cur_x, cur_y]
type_ = [0,1,2,3]
if pre_dir in type_:
type_.remove(pre_dir)
if u in g:
for v in g[u]:
if v != p:
dir_ = type_.pop()
next_x, next_y = cal_pos(dir_, cur_x, cur_y, cur_base)
build(v, u, next_x, next_y, cur_base-1, (dir_ - 2)%4, d, g)
ans ,s = solve()
if ans == 'NO':
print(ans)
else:
print(ans)
print(s) | Python | [
"graphs",
"trees"
] | 943 | 1,460 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 4,937 |
666b710742bb710dda112e4a6bbbe96b | You have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i.The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i units of water per second from junction x_i to junction y_i (if f_i is negative, then the pipe will distribute |f_i| units of water per second from junction y_i to junction x_i). It is allowed to set f_i to any integer from -2 \cdot 10^9 to 2 \cdot 10^9.In order for the system to work properly, there are some constraints: for every i \in [1, n], i-th junction has a number s_i associated with it meaning that the difference between incoming and outcoming flow for i-th junction must be exactly s_i (if s_i is not negative, then i-th junction must receive s_i units of water per second; if it is negative, then i-th junction must transfer |s_i| units of water per second to other junctions).Can you choose the integers f_1, f_2, ..., f_m in such a way that all requirements on incoming and outcoming flows are satisfied? | ['dp', 'dfs and similar', 'greedy', 'trees'] | import sys
from time import time
def i_ints():
return list(map(int, sys.stdin.readline().split()))
def main():
limit =10**10
n, = i_ints()
s = [0] + i_ints()
if sum(s):
print("Impossible")
return
print("Possible")
m, = i_ints()
es = [i_ints() for _ in range(m)]
nb = [[] for i in range(n+1)]
for i, (x, y) in enumerate(es):
nb[x].append((y, i, 1))
nb[y].append((x, i, -1))
path = []
def make_path():
stack = []
seen = [False] * (n+1)
stack.append(1)
seen[1] = True
while stack:
x = stack.pop()
for y, i, factor in nb[x]:
if not seen[y]:
seen[y] = True
stack.append(y)
path.append((x, y, i, factor))
make_path()
f = [0] * m
for x, y, i,factor in reversed(path):
f[i] = factor * s[y]
s[x] += s[y]
s[y] = 0
print("\n".join(map(str, f)))
return
main() | Python | [
"graphs",
"trees"
] | 1,336 | 1,041 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 970 |
bb071f1f4fc1c129a32064c1301f4942 | Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters s_i and s_{i+1}, and if s_i is 1 and s_{i + 1} is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string s as clean as possible. He thinks for two different strings x and y, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer t test cases: for the i-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings x and y of the same length then x is lexicographically smaller than y if there is a position i such that x_1 = y_1, x_2 = y_2,..., x_{i - 1} = y_{i - 1} and x_i < y_i. | ['implementation', 'greedy', 'strings'] | from sys import stdin
from collections import deque
# https://codeforces.com/contest/1354/status/D
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
from collections import Counter as cc
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f
# def ncr(x, y):
# return f(x) // (f(y) * f(x - y))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
import sys
# input = sys.stdin.readline
# LCA
# def bfs(na):
#
# queue = [na]
# boo[na] = True
# level[na] = 0
#
# while queue!=[]:
#
# z = queue.pop(0)
#
# for i in hash[z]:
#
# if not boo[i]:
#
# queue.append(i)
# level[i] = level[z] + 1
# boo[i] = True
# dp[i][0] = z
#
#
#
# def prec(n):
#
# for i in range(1,20):
#
# for j in range(1,n+1):
# if dp[j][i-1]!=-1:
# dp[j][i] = dp[dp[j][i-1]][i-1]
#
#
# def lca(u,v):
# if level[v] < level[u]:
# u,v = v,u
#
# diff = level[v] - level[u]
#
#
# for i in range(20):
# if ((diff>>i)&1):
# v = dp[v][i]
#
#
# if u == v:
# return u
#
#
# for i in range(19,-1,-1):
# # print(i)
# if dp[u][i] != dp[v][i]:
#
# u = dp[u][i]
# v = dp[v][i]
#
#
# return dp[u][0]
#
# dp = []
#
#
# n = int(input())
#
# for i in range(n + 10):
#
# ka = [-1]*(20)
# dp.append(ka)
# class FenwickTree:
# def __init__(self, x):
# """transform list into BIT"""
# self.bit = x
# for i in range(len(x)):
# j = i | (i + 1)
# if j < len(x):
# x[j] += x[i]
#
# def update(self, idx, x):
# """updates bit[idx] += x"""
# while idx < len(self.bit):
# self.bit[idx] += x
# idx |= idx + 1
#
# def query(self, end):
# """calc sum(bit[:end])"""
# x = 0
# while end:
# x += self.bit[end - 1]
# end &= end - 1
# return x
#
# def find_kth_smallest(self, k):
# """Find largest idx such that sum(bit[:idx]) <= k"""
# idx = -1
# for d in reversed(range(len(self.bit).bit_length())):
# right_idx = idx + (1 << d)
# if right_idx < len(self.bit) and k >= self.bit[right_idx]:
# idx = right_idx
# k -= self.bit[idx]
# return idx + 1
# import sys
# def rs(): return sys.stdin.readline().strip()
# def ri(): return int(sys.stdin.readline())
# def ria(): return list(map(int, sys.stdin.readline().split()))
# def prn(n): sys.stdout.write(str(n))
# def pia(a): sys.stdout.write(' '.join([str(s) for s in a]))
#
#
# import gc, os
#
# ii = 0
# _inp = b''
#
#
# def getchar():
# global ii, _inp
# if ii >= len(_inp):
# _inp = os.read(0, 100000)
# gc.collect()
# ii = 0
# if not _inp:
# return b' '[0]
# ii += 1
# return _inp[ii - 1]
#
#
# def input():
# c = getchar()
# if c == b'-'[0]:
# x = 0
# sign = 1
# else:
# x = c - b'0'[0]
# sign = 0
# c = getchar()
# while c >= b'0'[0]:
# x = 10 * x + c - b'0'[0]
# c = getchar()
# if c == b'\r'[0]:
# getchar()
# return -x if sign else x
# fenwick Tree
# n,q = map(int,input().split())
#
#
# l1 = list(map(int,input().split()))
#
# l2 = list(map(int,input().split()))
#
# bit = [0]*(10**6 + 1)
#
# def update(i,add,bit):
#
# while i>0 and i<len(bit):
#
# bit[i]+=add
# i = i + (i&(-i))
#
#
# def sum(i,bit):
# ans = 0
# while i>0:
#
# ans+=bit[i]
# i = i - (i & ( -i))
#
#
# return ans
#
# def find_smallest(k,bit):
#
# l = 0
# h = len(bit)
# while l<h:
#
# mid = (l+h)//2
# if k <= sum(mid,bit):
# h = mid
# else:
# l = mid + 1
#
#
# return l
#
#
# def insert(x,bit):
# update(x,1,bit)
#
# def delete(x,bit):
# update(x,-1,bit)
# fa = set()
#
# for i in l1:
# insert(i,bit)
#
#
# for i in l2:
# if i>0:
# insert(i,bit)
#
# else:
# z = find_smallest(-i,bit)
#
# delete(z,bit)
#
#
# # print(bit)
# if len(set(bit)) == 1:
# print(0)
# else:
# for i in range(1,n+1):
# z = find_smallest(i,bit)
# if z!=0:
# print(z)
# break
#
# service time problem
# def solve2(s,a,b,hash,z,cnt):
# temp = cnt.copy()
# x,y = hash[a],hash[b]
# i = 0
# j = len(s)-1
#
# while z:
#
# if s[j] - y>=x-s[i]:
# if temp[s[j]]-1 == 0:
# j-=1
# temp[s[j]]-=1
# z-=1
#
#
# else:
# if temp[s[i]]-1 == 0:
# i+=1
#
# temp[s[i]]-=1
# z-=1
#
# return s[i:j+1]
#
#
#
#
#
# def solve1(l,s,posn,z,hash):
#
# ans = []
# for i in l:
# a,b = i
# ka = solve2(s,a,b,posn,z,hash)
# ans.append(ka)
#
# return ans
#
# def consistent(input, window, min_entries, max_entries, tolerance):
#
# l = input
# n = len(l)
# l.sort()
# s = list(set(l))
# s.sort()
#
# if min_entries<=n<=max_entries:
#
# if s[-1] - s[0]<window:
# return True
# hash = defaultdict(int)
# posn = defaultdict(int)
# for i in l:
# hash[i]+=1
#
# z = (tolerance*(n))//100
# poss_window = set()
#
#
# for i in range(len(s)):
# posn[i] = l[i]
# for j in range(i+1,len(s)):
# if s[j]-s[i] == window:
# poss_window.add((s[i],s[j]))
#
# if poss_window!=set():
# print(poss_window)
# ans = solve1(poss_window,s,posn,z,hash)
# print(ans)
#
#
# else:
# pass
#
# else:
# return False
#
#
#
#
# l = list(map(int,input().split()))
#
# min_ent,max_ent = map(int,input().split())
# w = int(input())
# tol = int(input())
# consistent(l, w, min_ent, max_ent, tol)
# t = int(input())
#
# for i in range(t):
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# e,o = 0,0
#
# for i in l:
# if i%2 == 0:
# e+=1
# else:
# o+=1
#
# if e+o>=x and o!=0:
# z = e+o - x
# if z == 0:
# if o%2 == 0:
# print('No')
# else:
# print('Yes')
# continue
# if o%2 == 0:
# o-=1
# z-=1
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
#
# else:
#
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
# else:
# print('No')
#
#
#
#
#
#
#
# def dfs(n):
# boo[n] = True
# dp2[n] = 1
# for i in hash[n]:
# if not boo[i]:
#
# dfs(i)
# dp2[n] += dp2[i]
#
#
# n = int(input())
# x = 0
# l = list(map(int,input().split()))
# for i in range(n):
#
# x = l[i]|x
#
# z = list(bin(x)[2:])
# ha = z.copy()
# k = z.count('1')
# ans = 0
# # print(z)
# cnt = 0
# for i in range(20):
#
#
# maxi = 0
# idx = -1
#
# for j in range(n):
# k = bin(l[j])[2:]
# k = '0'*(len(z) -len(k)) + k
# cnt = 0
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# cnt+=1
#
# maxi = max(maxi,cnt)
# if maxi == cnt:
# idx = j
# if idx!=-1:
#
# k = bin(l[idx])[2:]
# k = '0'*(len(z) -len(k)) + k
#
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# z[i] = '0'
# l[idx] = 0
#
#
# ans = 0
# for i in range(len(z)):
# if z[i] == '0' and ha[i] == '1':
# ans+=1
# flip = 0
# for i in range(ans):
# flip+=2**i
#
#
#
# print(flip)
# def search(k,l,low):
#
# high = len(l)-1
# z = bisect_left(l,k,low,high)
#
# return z
#
#
#
#
#
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# prefix = [0]
# ha = [0]
# for i in l:
# prefix.append(i + prefix[-1])
# ha.append((i*(i+1))//2 + ha[-1])
# fin = 0
# print(prefix)
# for i in range(n):
# ans = 0
# if l[i]<x:
#
#
# if prefix[-1]-prefix[i]>=x:
#
# z = search(x+prefix[i],prefix,i+1)
# print(z)
# z+=i+1
# k1 = x-(prefix[z-1]-prefix[i])
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
# else:
# z1 = x - (prefix[-1]-prefix[i])
# z = search(z1,prefix,1)
#
# k1 = x-prefix[z-1]
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
#
#
# elif l[i]>x:
# z1 = ((l[i])*(l[i]+1))//2
# z2 = ((l[i]-x)*(l[i]-x+1))//2
# ans+=z1-z2
# else:
# ans+=(x*(x+1))//2
# t = int(input())
#
# for _ in range(t):
#
# s = list(input())
# ans = [s[0]]
#
# for i in range(1,len(s)-1,2):
# ans.append(s[i])
#
# ans.append(s[-1])
# print(''.join(ans))
#
#
#
# t = int(input())
#
# for _ in range(t):
#
# n = int(input())
# l = list(map(int,input().split()))
# ans = 0
# for i in range(n):
# if l[i]%2!=i%2:
# ans+=1
#
# if ans%2 == 0:
# print(ans//2)
# else:
# print(-1)
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# s = input()
#
#
# ans = 0
# ba = []
# for i in range(n):
# if s[i] == '1':
# ba.append(i)
# if ba == []:
# for i in range(0,n,k+1):
# ans+=1
#
# print(ans)
# continue
#
# i = s.index('1')
# c = 0
# for x in range(i-1,-1,-1):
# if c == k:
# c = 0
# ans+=1
# else:
# c+=1
#
#
# while i<len(s):
# count = 0
# dis = 0
# while s[i] == '0':
# dis+=1
# if dis == k:
# dis = 0
# count+=1
# if dis<k and s[i] == '1':
# count-=1
# break
# i+=1
# if i == n:
# break
# i+=1
#
# print(ans)
#
#
#
#
# q1
# def poss1(x):
# cnt = 1
# mini = inf
# for i in l:
# if cnt%2 != 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# mini = min()
# if cnt == k:
# return
#
# return -1
#
#
#
#
# def poss2(x):
# cnt = 1
# for i in l:
# if cnt%2 == 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# if cnt == k:
# return
#
# return -1
#
#
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# z1 = min(l)
# z2 = max(l)
#
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# l1 = list(map(int,input().split()))
# l.sort(reverse=True)
# l1.sort()
# for i in range(k):
# l1[i]-=1
#
# i = 0
# j = k
# x = 0
# ans = sum(l[:k])
# # print(l)
# # print(l1)
# # print(ans)
# while x<k:
# cnt = 1
# z = l1[x]
# while z>cnt:
# j+=1
# cnt+=1
#
# if z == 0:
# ans+=l[i]
# i+=1
# else:
# # print(j,z)
# ans+=l[j]
#
# i+=1
# j+=1
# x+=1
#
# print(ans)
#
#
t = int(input())
for _ in range(t):
n = int(input())
s = input()
if '1' not in s:
print(s)
continue
if '0' not in s:
print(s)
continue
if n == 1:
print(s)
continue
z1 = n-s[::-1].index('0')-1
z2 = s.index('1')
if z1>z2:
print(s[:z2] + '0' + s[z1+1:])
else:
print(s)
| Python | [
"strings"
] | 1,257 | 13,073 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,711 |
2b15a299c25254f265cce106dffd6174 | Let f(i) denote the minimum positive integer x such that x is not a divisor of i.Compute \sum_{i=1}^n f(i) modulo 10^9+7. In other words, compute f(1)+f(2)+\dots+f(n) modulo 10^9+7. | ['math', 'number theory'] | from math import gcd
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
i, smallest_divisor, ans = 1, 1, n
while n // i:
i = i * smallest_divisor // gcd(i, smallest_divisor)
ans += n // i
smallest_divisor += 1
print(ans % 1000000007)
| Python | [
"math",
"number theory"
] | 229 | 311 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 402 |
351c6fb0a9d1bbb29387c5b7ce8c7f28 | This is an interactive problem.Anton and Harris are playing a game to decide which of them is the king of problemsetting.There are three piles of stones, initially containing a, b, and c stones, where a, b, and c are distinct positive integers. On each turn of the game, the following sequence of events takes place: The first player chooses a positive integer y and provides it to the second player. The second player adds y stones to one of the piles, with the condition that he cannot choose the same pile in two consecutive turns. The second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if 1000 turns have passed without the second player losing.Feeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting! | ['math', 'constructive algorithms', 'games', 'interactive'] | l = list(map(int, input().split()))
def play(x):
global s
res = int(input(str(x)+'\n'))
if res == 0: exit(0)
l[res-1] += x
s = sorted(l)
BIG = 10**11
print("First")
play(BIG)
play(s[2]*2-s[1]-s[0])
play(s[1]-s[0])
| Python | [
"math",
"games"
] | 938 | 234 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,018 |
5c844c0dc0eb718aea7b2446e90ce250 | Suppose you have an integer v. In one operation, you can: either set v = (v + 1) \bmod 32768 or set v = (2 \cdot v) \bmod 32768. You are given n integers a_1, a_2, \dots, a_n. What is the minimum number of operations you need to make each a_i equal to 0? | ['bitmasks', 'brute force', 'dfs and similar', 'dp', 'graphs', 'greedy', 'shortest paths'] | from math import ceil, log
res =[]
int(input())
l = list(map(int, input().split()) )
c = 32768
def nexp(i, max):
exp = ceil(log(i, 2))
if 2**exp -i < 15 and 2**exp -i + 15 - exp < 15:
return 2**exp -i + 15 - exp
else:
tmp = i
steps=0
if i%2 !=0:
i+=1
steps+=1
while i % c != 0:
if steps > max:
return max +1
i*=2
steps +=1
return steps
def minsteps(i):
exp = ceil(log(i, 2))
if i==0:
return 0
else:
steps = 15
for j in range(15):
tmp = j+i
c =0
while tmp%2==0:
tmp /= 2
c+=1
steps = min(steps, j+ 15-c)
return steps
s =''
for i in l:
if i ==0:
s+="0 "#print("0",end=" ")
else:
steps=minsteps(i)
s+= str(steps)+ " "
print(s)
| Python | [
"graphs"
] | 299 | 1,011 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 709 |
13574507efa5089f3420cf002c3f8077 | After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts. | ['dp', 'greedy', 'strings'] | #
# http://codeforces.com/problemset/problem/655/E
MOD = 10 ** 9 + 7
def read_ints():
return map(int, raw_input().split())
N, K = read_ints()
counts, indexes = [0] * K, [-1] * K
count = 1
for i, c in enumerate(raw_input()):
c = ord(c) - ord('a')
counts[c], count, indexes[c] = count, (2 * count - counts[c]) % MOD, i
counts = [counts[i] for i in sorted(xrange(K), key=lambda _: indexes[_])]
for i in xrange(N):
counts[i % K], count = count, (2 * count - counts[i % K]) % MOD
print count
| Python | [
"strings"
] | 1,213 | 511 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,196 |
d8349ff9b695612473b2ba00d08e505b | One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer x, then choose one machine and reduce the power of its machine by x times, and at the same time increase the power of one another machine by x times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices i and j, and one integer x such that x is a divisor of a_i, and change powers as following: a_i = \frac{a_i}{x}, a_j = a_j \cdot xSasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him! | ['number theory', 'greedy'] | n=int(raw_input())
a=list(map(int,raw_input().split()))
a = sorted(a)
ans=99999999999999999999999999999999999999999999999999999999999999999999
i=n-1
total=sum(a)
if n > 1:
while i > 0:
for j in xrange(1,101):
if a[i]%j==0:
minn=a[0]*j
maxx=a[i]/j
ans=min(ans,total-a[0]-a[i]+minn+maxx)
i -= 1
print ans
else:
print sum(a) | Python | [
"number theory"
] | 1,169 | 409 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,173 |
91cfd24b8d608eb379f709f4509ecd2d | Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. | ['dp', 'strings'] | n = int(input())
ref = [int(x) for x in input().split()]
state = [[float('inf')]*2 for x in range(n)]
prev = input()
state[0][0] = 0
state[0][1] = ref[0]
flag = 0
for i in range(1,n):
cur = input()
if cur >= prev:
state[i][0] = min(state[i][0],state[i-1][0])
if cur >= prev[-1::-1]:
state[i][0] = min(state[i][0],state[i-1][1])
if cur[-1::-1] >= prev:
state[i][1] = min(state[i][1],state[i-1][0]+ref[i])
if cur[-1::-1] >= prev[-1::-1]:
state[i][1] = min(state[i][1],state[i-1][1]+ref[i])
prev = cur
if state[i][0] >= float('inf') and state[i][1] >= float('inf'):
flag = 1
break
if flag == 1:
print(-1)
else:
print(min(state[n-1][0],state[n-1][1]))
| Python | [
"strings"
] | 1,010 | 732 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,367 |
d66e55ac7fa8a7b57ccd57d9242fd2a2 | Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only. | ['data structures', 'sortings', 'strings'] | def magic():
string=['1']*10000005
n=input()
m_index=0
till=0
for _ in xrange(n):
arr=raw_input().split()
s=arr[0]
times=int(arr[1])
arr=map(int,arr[2:])
l=len(s)
m_index=max(m_index,arr[-1]+l)
start=end=0
for index in arr:
if index==1 and till==0:
till=l
upto=index+l-1
if upto<till or upto<end:
continue
elif index<end:
m=end+1
j=end-index+1
else:
m=index
j=0
for i in xrange(m,upto+1):
string[i]=s[j]
j+=1
end=max(end,upto)
while till<3000000:
if string[till]!='1':
till+=1
else:
break
for i in xrange(1,m_index):
if string[i]=='1':
string[i]='a'
print ''.join(string[1:m_index])
magic() | Python | [
"strings"
] | 651 | 1,032 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 342 |
55bd1849ef13b52788a0b5685c4fcdac | You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. | ['implementation', 'number theory', 'math'] | n,k,m = map(int,input().split())
arr = list(map(int,input().split()))
ans = {}
for i in arr:
if i%m not in ans:
ans[i%m] = [i]
else:
ans[i%m].append(i)
check = False
for i in ans:
if len(ans[i]) >= k:
check = True
break
if check:
print('Yes')
j = 0
while j<=k-1:
print(ans[i][j],end = ' ')
j+=1
else:
print('No')
| Python | [
"number theory",
"math"
] | 419 | 389 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,837 |
b1ef19d7027dc82d76859d64a6f43439 | Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text. | ['implementation', 'strings'] | import collections
l=list(input())
p=list(input())
#print(p)
#print(l)
cl=collections.Counter(l)
pl=collections.Counter(p)
#print(cl)
#print(pl)
plk=list(pl.keys())
#print(plk)
if ' ' in plk:
plk.remove(' ')
else:
pass
n=len(plk)
i=0
er=0
#print(cl['s'])
while i<n:
h=plk[i]
t=cl[h]
q=pl[h]
#print(t)
#print(q)
if t>=q:
er+=1
else:
pass
i+=1
#print(n)
#print(er)
if er==n:
print('YES')
else:
print('NO')
| Python | [
"strings"
] | 375 | 471 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 3,629 |
0c9030689394ad4e126e5b8681f1535c | There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game. | ['dp', 'games'] |
for _ in range(int(input())):
n = input()
arr = input().split()
#
idx = 0
for v in arr:
if v != '1':
break
idx += 1
#
if idx != len(arr):
print('First' if (idx+1)%2==1 else 'Second')
else:
print('First' if len(arr)%2==1 else 'Second')
| Python | [
"games"
] | 461 | 312 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,271 |
42d0350a0a18760ce6d0d7a4d65135ec | Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost. | ['dp', 'number theory', 'math', 'shortest paths', 'data structures'] | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
import math
import random
import operator
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
getcontext().prec = 100
def gcd(a, b):
while b:
a, b = b, a % b
return a
MOD = 10**9 + 7
INF = float("+inf")
n = int(raw_input())
arr = map(int, raw_input().split())
arr_costs = map(int, raw_input().split())
costs = {}
for i, c in enumerate(arr):
costs[c] = min(arr_costs[i], costs.get(c, INF))
min_cost = sum(arr_costs)
for i in xrange(100):
lst = arr[::]
random.shuffle(lst)
r = 0
cost = 0
for x in lst:
r0 = r
r = gcd(r, x)
if r != r0:
cost += costs[x]
if r == 1:
break
if cost < min_cost:
min_cost = cost
if reduce(gcd, arr, 0) != 1:
print -1
quit()
g_min_cost = {0: 0}
from Queue import PriorityQueue
q = PriorityQueue()
q.put((0, 0))
checked = set()
while not q.empty():
cost, g = q.get()
# print cost, g
if g_min_cost[g] != cost:
continue
checked.add((cost, g))
for x in arr:
cost2 = cost + costs[x]
if cost2 >= min_cost:
continue
g2 = int(abs(gcd(g, x)))
if g2 == g:
continue
if g2 == 1:
min_cost = min(min_cost, cost2)
continue
if g_min_cost.get(g2, INF) > cost2:
g_min_cost[g2] = cost2
q.put((cost2, g2))
# if (cost2, g2) not in checked:
print min_cost
| Python | [
"number theory",
"math",
"graphs"
] | 668 | 1,578 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,786 |
107773724bd8a898f9be8fb3f9ee9ac9 | In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.More precisely, two different numbers a and b are friends if gcd(a,b), \frac{a}{gcd(a,b)}, \frac{b}{gcd(a,b)} can form sides of a triangle.Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.In a group of numbers, a number is lonely if it doesn't have any friends in that group.Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely? | ['two pointers', 'binary search', 'number theory', 'math'] | from sys import stdin
def count_prime(n):
for i in range(2, n):
if prim[i] == 1:
if i * i < Max:
prim[i * i] = -1
for j in range(i * i + i, n, i):
prim[j] = 0
for i in range(2, n):
prim[i] += prim[i - 1]
n, a, Max = int(input()), [int(x) for x in stdin.readline().split()], 1000001
prim = [1] * Max
count_prime(Max)
print('\n'.join(map(str, [prim[i] for i in a])))
| Python | [
"number theory",
"math"
] | 627 | 450 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 752 |
6c0ed9fe0a104fc9380c199003a22e90 | This is an interactive problem.Khanh has n points on the Cartesian plane, denoted by a_1, a_2, \ldots, a_n. All points' coordinates are integers between -10^9 and 10^9, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation p_1, p_2, \ldots, p_n of integers from 1 to n such that the polygon a_{p_1} a_{p_2} \ldots a_{p_n} is convex and vertices are listed in counter-clockwise order.Khanh gives you the number n, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh 4 integers t, i, j, k; where either t = 1 or t = 2; and i, j, k are three distinct indices from 1 to n, inclusive. In response, Khanh tells you: if t = 1, the area of the triangle a_ia_ja_k multiplied by 2. if t = 2, the sign of the cross product of two vectors \overrightarrow{a_ia_j} and \overrightarrow{a_ia_k}. Recall that the cross product of vector \overrightarrow{a} = (x_a, y_a) and vector \overrightarrow{b} = (x_b, y_b) is the integer x_a \cdot y_b - x_b \cdot y_a. The sign of a number is 1 it it is positive, and -1 otherwise. It can be proven that the cross product obtained in the above queries can not be 0.You can ask at most 3 \cdot n queries.Please note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation a_{p_1}a_{p_2}\ldots a_{p_n}, p_1 should be equal to 1 and the indices of vertices should be listed in counter-clockwise order. | ['geometry', 'interactive'] | import sys
range = xrange
input = raw_input
def query1(a,b,c):
print 1, a+1, b+1, c+1
return int(input())
def query2(a,b,c):
print 2, a+1, b+1, c+1
return int(input())
def ans(order):
print 0,' '.join(str(x + 1) for x in order)
sys.exit()
n = int(input())
a = 0
b = 1
for i in range(2,n):
if query2(a,b,i) < 0:
b = i
A = [-1]*n
for i in range(1,n):
if i != b:
A[i] = query1(a,b,i)
order = sorted(range(n), key = A.__getitem__)
j = order[-1]
left = []
right = [a,b]
for i in order:
if i != a and i != b and i != j:
(left if query2(a,j,i) >= 0 else right).append(i)
right.append(j)
right += reversed(left)
ans(right)
| Python | [
"geometry"
] | 1,832 | 682 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 964 |
ec09b2df4ed3abbca4c47f48f12010ca | You are given an array A, consisting of n positive integers a_1, a_2, \dots, a_n, and an array B, consisting of m positive integers b_1, b_2, \dots, b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can choose 1 from A and 4 from B, as number 5 = 1 + 4 doesn't belong to A and doesn't belong to B. However, we can't choose 2 from A and 1 from B, as 3 = 2 + 1 belongs to B.It can be shown that such a pair exists. If there are multiple answers, print any.Choose and print any such two numbers. | ['sortings', 'math'] | n = int(input())
a = [int(num) for num in input().split()]
m = int(input())
b = [int(num) for num in input().split()]
print(max(a), max(b)) | Python | [
"math"
] | 777 | 139 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,929 |
43a65d1cfe59931991b6aefae1ecd10e | You are given a string s=s_1s_2\dots s_n of length n, which only contains digits 1, 2, ..., 9.A substring s[l \dots r] of s is a string s_l s_{l + 1} s_{l + 2} \ldots s_r. A substring s[l \dots r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some substrings are equal as strings, but have different l and r, they are counted as different substrings. | ['implementation', 'strings'] | def f():
a=input()
b=str(input())
n=0
for i in range(len(b)):
if int(b[i])%2==0:
n+=i+1
print(n)
return n
f() | Python | [
"strings"
] | 503 | 154 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,588 |
8590f40e7509614694486165ee824587 | This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of n vertices (3 \le n \le 10^{18}). A cyclic graph is an undirected graph of n vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly n. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where 1 \le a, b \le 10^{18} and a \neq b. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex a to vertex b, or -1 if \max(a, b) > n. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number n) by making no more than 50 queries.Note that the interactor is implemented in such a way that for any ordered pair (a, b), it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is 50. | ['interactive', 'probabilities'] | for i in range(3, 26):
print(f"? 1 {i}", flush=True)
a = int(input())
if (a == -1):
print(f'! {i - 1}')
exit()
print(f"? {i} 1", flush=True)
b = int(input())
if a != b:
print(f'! {a + b}')
exit() | Python | [
"probabilities"
] | 1,332 | 261 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 1,306 |
198b6e6b91c7b4655d133a78421ac249 | Note that the memory limit is unusual.You are given an integer n and two sequences a_1, a_2, \dots, a_n and b_1, b_2, \dots, b_n.Let's call a set of integers S such that S \subseteq \{1, 2, 3, \dots, n\} strange, if, for every element i of S, the following condition is met: for every j \in [1, i - 1], if a_j divides a_i, then j is also included in S. An empty set is always strange.The cost of the set S is \sum\limits_{i \in S} b_i. You have to calculate the maximum possible cost of a strange set. | ['flows', 'math'] | from collections import deque
class Dinic:
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
# 1方向
def add_edge(self, fr, to, cap):
forward = [to, cap, None]
forward[2] = backward = [fr, 0, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
# 両方向
def add_multi_edge(self, v1, v2, cap1, cap2):
edge1 = [v2, cap1, None]
edge1[2] = edge2 = [v1, cap2, edge1]
self.G[v1].append(edge1)
self.G[v2].append(edge2)
def bfs(self, s, t):
self.level = level = [None]*self.N
deq = deque([s])
level[s] = 0
G = self.G
while deq:
v = deq.popleft()
lv = level[v] + 1
for w, cap, _ in G[v]:
if cap and level[w] is None:
level[w] = lv
deq.append(w)
return level[t] is not None
def dfs(self, v, t, f):
if v == t:
return f
level = self.level
for e in self.it[v]:
w, cap, rev = e
if cap and level[v] < level[w]:
d = self.dfs(w, t, min(f, cap))
if d:
e[1] -= d
rev[1] += d
return d
return 0
def flow(self, s, t):
flow = 0
INF = 10**9 + 7
G = self.G
while self.bfs(s, t):
*self.it, = map(iter, self.G)
f = INF
while f:
f = self.dfs(s, t, INF)
flow += f
return flow
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
# s:n+1,g:0
f = Dinic(n+2)
INF = 10**15
for i in range(n):
if b[i] > 0:
f.add_edge(n+1,i+1,b[i])
elif b[i] < 0:
f.add_edge(i+1,0,-b[i])
for i in range(n):
used = [False]*101
for j in reversed(range(i)):
if a[i] % a[j] == 0 and not used[a[j]]:
f.add_edge(i+1,j+1,INF)
used[a[j]] = True
ans = sum(b[i]*(b[i] > 0) for i in range(n)) - f.flow(n+1,0)
print(ans) | Python | [
"graphs",
"math"
] | 585 | 2,230 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,479 |
c9225c915669e183cbd8c20b848d96e5 | Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated from 1 to n from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with n digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of t matches find out, which agent wins, if both of them want to win and play optimally. | ['implementation', 'greedy', 'games'] | '''
# CodeForce Equalize Prices 900 points
# a = old price / b = new price / k =value input
def Computer_Game():
for _ in range(int(input())):
k, n, a, b = map(int, input().split()) # init charge, num turns in game, a,b bat value
max_turns=0
for turns in range(n):
if k/b > n and (k-a)/b < n-1 and turns == 0:
max_turns=0
break
else:
if k > a:
k -= a
max_turns += 1
elif k > b:
k -= b
if k/b == n-turns:
max_turns = 1
break
else:
max_turns = -1
break
print(max_turns)
return
def bit_plus_plus():
summe = 0
for _ in range(int(input())):
statement = input()
if '+' in statement:
summe += 1
else:
summe -= 1
print(summe)
return
def petya_and_strings():
str_a, str_b = input().lower(), input().lower()
a=(str_a<str_b)
print((str_a>str_b)-(str_a<str_b))
return
def beautiful_matrix():
for idx in range(5):
row_input = list(map(int,input().split()))
if 1 in row_input:
row = idx+1
for idx1, elem in enumerate(row_input):
if elem == 1:
column = idx1+1
output = abs(3 - row) + abs(3 - column)
print(output)
#for row_num in range(4):
# if 1 in row(row_num)
return
def helpful_maths():
string = sorted(list(input().split('+')))
print('+'.join(string))
return
def word_capitalization():
string = input()
string_new = string[0].upper()+string[1:]
print(string_new)
return
def Stones_on_the_Table():
_ = input()
string=list(input())
color_old = ''
color_old_old = ''
take = 0
for color in string:
if color == color_old:
take += 1
else:
color_old = color
print(take)
return
def Boy_or_girl():
print([{*input()}])
string = input()
new_string = ''
for _ in string:
if _ not in new_string:
new_string = new_string + _
if len(new_string) % 2 != 0:
print('IGNORE HIM!')
else:
print('CHAT WITH HER!')
return
def soldier_and_bananas():
k,n,w = map(int,input().split())
prize = 0
for num in range(w):
prize = prize + (num+1)*k
print(prize-n if prize-n > 0 else 0)
return
def bear_and_big_brother():
a,b = map(int, input().split())
years = 0
while a <= b:
a = a*3
b = b*2
years += 1
print(years)
return
def Tram():
passenger = []
cur_pass = 0
for _ in range(int(input())):
exit_passenger, enter_passenger = map(int,input().split())
cur_pass = cur_pass - exit_passenger + enter_passenger
passenger.append(cur_pass)
print(max(passenger))
return
def subtract_one(number):
if float(number)%10 == 0:
result = number / 10
else:
result = number - 1
return int(result)
def wrong_subtraction():
n, k = map(int, input().split())
for _ in range(k):
n = subtract_one(n)
print(n)
return
def wet_shark_and_odd_and_even():
odd = []
even = []
odd_cnt = 0
n = input()
numbers = list(map(int,input().split()))
for number in numbers:
if number%2 == 0:
even.append(number)
else:
odd.append(number)
odd_cnt += 1
odd.sort()
k = int(odd_cnt/2)*2
if k > 0:
summe = sum(even) + sum(odd[-k:])
else:
summe = sum(even)
print(summe)
return
def sorting(volumes):
sorting_steps = 0
idx = 0
cnt = 0
while(idx < len(volumes)-1):
a = volumes[idx]
b = volumes[idx+1]
# print(volumes)
if a > b:
volumes[idx] = b
volumes[idx+1] = a
sorting_steps += 1
if idx > 0:
idx -= 1
else:
cnt = cnt+1
idx = cnt
else:
idx += 1
return sorting_steps
def cubes_sorting():
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
max_sort = n*(n-1)/2-1
sorting_steps = sorting(a)
if sorting_steps > max_sort:
print('NO')
else:
print('YES')
return
def elephant():
coord = int(input())
steps_taken = 0
for steps in range(5,0,-1):
if (coord / steps) >= 1:
steps_taken = int(coord / steps) + steps_taken
coord = int(coord % steps)
print(steps_taken)
return
def queue_at_the_school():
number, time = map(int,input().split())
queue=list(input())
i = 0
while i < time:
idx = 0
while idx < len(queue)-1:
if queue[idx] == 'B' and queue[idx+1] == 'G':
queue[idx] = 'G'
queue[idx+1] = 'B'
idx += 2
else:
idx += 1
i += 1
print(''.join(queue))
return
def nearly_lucky_number():
number = input()
l_number = 0
bla=[sum(i in '47' for i in number) in [4, 7]]
print('4' in number)
for elem in number:
if elem == '7' or elem == '4':
l_number += 1
print('YES' if l_number == 4 or l_number == 7 else 'NO')
return
def word():
string = input()
count = 0
for elem in string:
if elem.isupper():
count += 1
print(string.upper() if count > len(string)/2 else string.lower())
return
'''
def translation():
word_1 = input()
word_2 = input()[::-1]
print(["NO", "YES"] [word_1 == word_2])
return
def anton_and_danik():
games = int(input())
wins=input()
anton_wins = sum(i == 'A' for i in wins)
if anton_wins*2 > len(wins):
print('Anton')
elif anton_wins*2 == len(wins):
print('Friendship')
else:
print('Danik')
return
def acoomodation():
cnt = 0
for _ in range(int(input())):
p, q = map(int, input().split())
if q - p >= 2:
cnt +=1
print(cnt)
return
def juicer():
n, b, d = map(int, input().split())
sum_orange = 0
cnt_empty = 0
for orange in list(map(int, input().split())):
if orange <= b:
sum_orange += orange
if sum_orange > d:
cnt_empty += 1
sum_orange = 0
print(cnt_empty)
return
def digit_game():
for game in range(int(input())):
breach_odd_cnt = 0
breach_even_cnt = 0
raze_odd_cnt = 0
raze_even_cnt = 0
n = int(input())
number = input()
breach_numbers = ''
raze_numbers = ''
len_number = len(number)
idx = 1
for digit in number:
if idx%2 == 0:
breach_numbers += digit
if digit in '13579':
breach_odd_cnt += 1
else:
breach_even_cnt += 1
else:
raze_numbers += digit
if digit in '13579':
raze_odd_cnt += 1
else:
raze_even_cnt += 1
idx += 1
if len_number == 1:
if int(number)%2 == 0:
print(2)
else:
print(1)
elif len_number%2 == 0: # last pick from raze raze lässt eins übrig
if breach_even_cnt >= 1:
print(2)
else:
print(1)
else: # last pick from breach breach lässt übrig
if raze_odd_cnt >= 1:
print(1)
else:
print(2)
# raze only odd breach only even 1 = odd 0 = even raze starts
# 1 raze wins
# 2 breach wins
return
if __name__ == '__main__':
digit_game()
'''
if __name__ == '__main__':
num_queries = int(input())
for querie in range(num_queries):
num_products, value_products = map(int, input().split())
price_products = list(map(int, input().split()))
B_Max = min(price_products)+value_products
B_Min = max(price_products)-value_products
if B_Max >= B_Min:
print(B_Max)
else:
print(-1)
'''
| Python | [
"games"
] | 1,196 | 8,551 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 549 |
f14e81618a81946dcaab281e1aa1ff9f | You are given n distinct points p_1, p_2, \ldots, p_n on the plane and a positive integer R. Find the number of pairs of indices (i, j) such that 1 \le i < j \le n, and for every possible k (1 \le k \le n) the distance from the point p_k to the segment between points p_i and p_j is at most R. | ['geometry'] | from math import atan2, asin
def dist(a, b):
return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5
def check(R, p, i, dp):
left, right = float("-inf"), float("inf")
for j in range(len(p)):
if j == i:
continue
d = dist(p[i], p[j])
if R >= d:
continue
delta = asin(R/d)
angle = atan2(p[j][1]-p[i][1], p[j][0]-p[i][0])
l, r = angle-delta, angle+delta
if l > right:
l, r = l-2*PI, r-2*PI
elif r < left:
l, r = l+2*PI, r+2*PI
left, right = max(left, l), min(right, r)
if left > right:
return
for j in range(len(p)):
if j == i:
continue
angle = atan2(p[j][1]-p[i][1], p[j][0]-p[i][0])
if angle > right:
angle -= 2*PI
elif angle < left:
angle += 2*PI
if left <= angle <= right:
dp[i][j] = 1
def solution():
n, R = list(map(int, input().strip().split()))
p = [list(map(int, input().strip().split())) for _ in range(n)]
dp = [[0]*n for _ in range(n)]
for i in range(n):
check(R, p, i, dp)
return sum(dp[i][j] and dp[j][i] for i in range(n) for j in range(i, n))
PI = 2*atan2(1, 0)
print(solution()) | Python | [
"geometry"
] | 362 | 1,300 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 313 |
e9079292d6bb328d8fe355101028cc6a | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.You are given a string t consisting of n lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string s consisting of n lowercase Latin letters. Then they applied a sequence of no more than n (possibly zero) operations. i-th operation is denoted by two integers a_i and b_i (1 \le a_i, b_i \le n), and means swapping two elements of the string with indices a_i and b_i. All operations were done in the order they were placed in the sequence. For example, if s is xyz and 2 following operations are performed: a_1 = 1, b_1 = 2; a_2 = 2, b_2 = 3, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so t is yzx.You are asked to restore the original string s. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is n, and get the resulting string after those operations.Can you guess the original string s asking the testing system to run the sequence of swaps no more than 3 times?The string s and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution. | ['constructive algorithms', 'bitmasks', 'math', 'chinese remainder theorem', 'interactive'] | t = [tmp for tmp in input().strip()]
n = len(t)
az = 'abcdefghijklmnopqrstuvwxyz'
s1 = [tmp for tmp in az] * (n // 26 + 1)
s1 = s1[:n]
s2 = []
for ch in az:
s2 += [ch] * 26
s2 *= (n // 26 + 1)
s2 = s2[:n]
s3 = []
for ch in az:
s3 += [ch] * 676
s3 *= (n // 676 + 1)
s3 = s3[:n]
print("? ", *s1, sep='', flush=True)
t1 = input()
print("? ", *s2, sep='', flush=True)
t2 = input()
print("? ", *s3, sep='', flush=True)
t3 = input()
tc = []
orda = ord('a')
for i in range(n):
m1 = ord(t1[i]) - orda
m26 = ord(t2[i]) - orda
m676 = ord(t3[i]) - orda
tc.append(m676 * 676 + m26 * 26 + m1)
s = ['a'] * n
for pos2, pos1 in enumerate(tc):
s[pos1] = t[pos2]
print("! ", *s, sep='', flush=True)
| Python | [
"math",
"number theory"
] | 1,880 | 718 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,739 |
f217337f015224231e64a992329242e8 | Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?There are n stores numbered from 1 to n in Nlogonia. The i-th of these stores offers a positive integer a_i.Each day among the last m days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.Dora considers Swiper to be her rival, and she considers that she beat Swiper on day i if and only if the least common multiple of the numbers she bought on day i is strictly greater than the least common multiple of the numbers that Swiper bought on day i.The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.However, Dora forgot the values of a_i. Help Dora find out if there are positive integer values of a_i such that she beat Swiper on every day. You don't need to find what are the possible values of a_i though.Note that it is possible for some values of a_i to coincide in a solution. | ['constructive algorithms', 'number theory', 'bitmasks', 'math', 'brute force'] | # https://codeforces.com/problemset/problem/1166/E
def push(d, x):
if x not in d:
d[x]=0
d[x]+=1
def check(a, i, j):
for x in a[i]:
d[x]+=1
for x in a[j]:
d[x]+=1
for val in d:
if val==2:
refresh()
return True
refresh()
return False
def refresh():
for i in range(len(d)):
d[i]=0
m, n = map(int, input().split())
d = [0] * 10010
arr=[]
for _ in range(m):
arr.append(list(map(int, input().split()))[1:])
flg=True
for i in range(m):
for j in range(i+1, m):
if check(arr, i, j)==False:
flg=False
break
if flg==True:
print('possible')
else:
print('impossible') | Python | [
"number theory",
"math"
] | 1,225 | 755 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,963 |
f17445aca588e5fbc1dc6a595c811bd6 | After rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters). Errorgorn can change Anton's DNA into string b which must be a permutation of a. However, Anton's body can defend against this attack. In 1 second, his body can swap 2 adjacent characters of his DNA to transform it back to a. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string B. Can you help him? | ['brute force', 'constructive algorithms', 'data structures', 'math', 'strings'] | from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return list(map(str,input().strip().split(" ")))
def le(): return list(map(int,input().split()))
def rc(): return map(float,input().split())
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def joron(L):
return('\n'.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
boi=int(998244353)
doi=int(1e9+7)
hoi=int(1e5+50)
poi=int(10+2**20)
y="YES"
n="NO"
def gosa(x, y):
while(y):
x, y = y, x % y
return x
L=[0]*hoi
M=[0]*hoi
def bulli(x):
return bin(x).count('1')
def iu():
import sys
import math as my
import functools
input=sys.stdin.readline
from collections import deque, defaultdict
bec=-1
e=[]
t=list(st())
de=""
U=[]
V=[]
zs=defaultdict(int)
m=len(t)
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
for h in range(1,5):
if(i!=j and i!=k and h!=i and j!=k and j!=h and h!=k):
df=0
for p in range(1,6):
M[p]=0
L[ord('A')]=i
L[ord('N')]=j
L[ord('T')]=k
L[ord('O')]=h
for fg in range(1,1+m):
df=df+M[L[ord(t[fg-1])]+1]
for dg in range(1,1+L[ord(t[fg-1])]):
M[dg]=1+M[dg]
if(bec<df):
pp=i
qq=j
rr=k
ss=h
bec=df
L[ord('A')]=pp
L[ord('N')]=qq
L[ord('T')]=rr
L[ord('O')]=ss
e.append([L[ord('A')],'A'])
e.append([L[ord('N')],'N'])
e.append([L[ord('T')],'T'])
e.append([L[ord('O')],'O'])
e.sort()
#print(e)
for i in e:
de+=(t.count(i[1]))*i[1]
print(de)
def main():
for i in range(so()):
#print("Case #"+str(i+1)+": ",end="")
iu()
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read() | Python | [
"math",
"strings"
] | 854 | 9,165 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,459 |
89687dcbf37fc776b508252ddac8e8d4 | Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.n employees numbered from 1 to n take part in the event. Each employee i is assigned a different employee b_i, to which employee i has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all b_i must be distinct integers between 1 and n, and for any i, b_i \ne i must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee i has said that they wish to make a gift to employee a_i.Find a valid assignment b that maximizes the number of fulfilled wishes of the employees. | ['graphs', 'greedy', 'math'] | from collections import defaultdict
def first(U):
if len(U) == 0:
return None
it = iter(U)
return next(it)
def solve(A):
N = len(A)
for i in range(N):
A[i] -= 1
r = 0
B = [None] * N
U = {}
empty = []
for i in range(N):
if A[i] not in U:
B[i] = A[i]
U[A[i]] = i
r += 1
else:
empty.append(i)
if len(empty) == 1:
e = empty[0]
if e not in U:
B[e] = A[e]
B[U[A[e]]] = e
else:
for z in range(N):
if z not in U:
B[e] = z
break
elif len(empty) > 1:
src = empty
src.sort(lambda x: 0 if x not in U else 1)
dst = []
G = {i for i in range(N) if i not in U}
for s in src:
if s not in U:
dst.append(s)
G.discard(s)
dst.extend(G)
size = len(src)
for i in range(size):
B[src[i]] = dst[(i + 1) % size]
print(r)
print(" ".join(str(e + 1) for e in B))
T = int(input())
for _ in range(T):
n = int(input())
A = [int(e) for e in input().split(' ')]
solve(A) | Python | [
"graphs",
"math"
] | 902 | 1,317 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,255 |
87f64b4d5baca4b80162ae6075110b00 | This is the easy version of the problem. The only difference is the constraints on n and k. You can make hacks only if all versions of the problem are solved.You have a string s, and you can do two types of operations on it: Delete the last character of the string. Duplicate the string: s:=s+s, where + denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly k that can be obtained by doing these operations on string s.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a\ne b; In the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. | ['binary search', 'brute force', 'dp', 'greedy', 'hashing', 'implementation', 'string suffix structures', 'strings', 'two pointers'] | import sys
data1 = sys.stdin.read()
import copy
import math
data = data1.split("\n")
f1 = data[0].split(' ')
n = int(f1[0])
k = f1[1]
string1 = list(data[1])
string1.append(" ")
final = list()
def check():
for t in range(0, n - 1):
if t == n-1:
return t
if ord(string1[t]) >= ord(string1[t + 1]) :
final.extend(string1[t])
else:
return t
return n-1
##already get initial array
def check1(x):
flag = True
if x == 0:
final.append(string1[0])
return final
for t in range(x, n):
if flag == False:
if p1 >= int(n):
return final
p1 += 1
t = copy.copy(p1)
if ord(string1[0]) > ord(string1[t]):
final.extend(string1[t])
elif ord(string1[0]) == ord(string1[t]):
p2 = 0
while ord(string1[p2]) == ord(string1[t]):
p2+=1
t+=1
p1 = copy.copy(t)
if(string1[p2] > string1[t]):
final.extend(string1[t - p2:t+1])
flag = False
else:
return final
#compare the second number
elif ord(string1[0]) < ord(string1[t]):
return final
return final
p3 = check1(check())
if ' ' in p3:
p3.remove(' ')
if len(p3) > 1:
if p3[0]==p3[len(p3)-1]:
p5 = 0
p6 = copy.copy(p3[0])
while p3[p5] == p6 and p3[len(p3)-1-p5]== p6 and p5<math.ceil(len(p3)/2):
p5 +=1
p3 = p3[0:len(p3)-p5]
p3 = p3*math.ceil(int(k)/len(p3))
p4 = ''.join(p3[0:int(k)])
print(p4)
| Python | [
"strings"
] | 903 | 1,699 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,382 |
1f4c3f5e7205fe556b50320cecf66c89 | The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the i-th figure equals t_i. The example of the carousel for n=9 and t=[5, 5, 1, 15, 1, 5, 5, 1, 1]. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly k distinct colors, then the colors of figures should be denoted with integers from 1 to k. | ['dp', 'greedy', 'graphs', 'constructive algorithms', 'math'] | from __future__ import division, print_function
import sys
# sys.setrecursionlimit(10**6)
from sys import stdin, stdout
import bisect #c++ upperbound
import math
import heapq
def modinv(n,p):
return pow(n,p-2,p)
def cin():
return map(int,sin().split())
def ain(): #takes array as input
return list(map(int,sin().split()))
def sin():
return input()
def inin():
return int(input())
import math
def Divisors(n) :
l = []
for i in range(1, int(math.sqrt(n) + 1)) :
if (n % i == 0) :
if (n // i == i) :
l.append(i)
else :
l.append(i)
l.append(n//i)
return l
"""*******************************************************"""
def main():
t=inin()
for _ in range(t):
x=0
n=inin()
a=ain()
d={}
x=0
b=[]
b.append(0)
l=-1
f=1
for i in range(1,n):
if(a[i]!=a[i-1]):
x+=1
f=2
x=x%2
else:
if(l==-1):
l=i
b.append(x)
if(a[n-1]!=a[0]):
if(b[n-1]==b[0]):
# print(l)
if(l==-1):
b[n-1]=2
f=3
else:
b[l]=(b[l]+1)%2
x=b[l]
for j in range(l+1,n):
# print(a[j],a[j-1],x)
if(a[j]!=a[j-1]):
x+=1
x=x%2
# print(x)
b[j]=x
for i in range(n):
b[i]=b[i]+1
print(f)
print(*b)
######## 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() | Python | [
"graphs",
"math"
] | 1,052 | 4,714 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,615 |
18cf79b50d0a389e6c3afd5d2f6bd9ed | Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were a_i citizens on the i-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught? | ['greedy', 'graphs', 'binary search', 'dfs and similar', 'trees'] | n = int(input())
p = list(map(int, input().split()))
a = list(map(int, input().split()))
tree = {}
for i, pp in enumerate(p, start=2):
tree.setdefault(pp, []).append(i)
cache = {}
for s in range(n, 0, -1):
children = tree.get(s, [])
if len(children) == 0:
cache[s] = (a[s - 1], a[s - 1], 1)
continue
ch_p = [cache[c] for c in children]
ch_max = max(pp[0] for pp in ch_p)
ch_sum = sum(pp[1] for pp in ch_p)
ch_l = sum(pp[2] for pp in ch_p)
sm = ch_sum + a[s - 1]
m = sm // ch_l
if sm % ch_l != 0:
m += 1
cache[s] = (max(ch_max, m), sm, ch_l)
print(cache[1][0]) | Python | [
"graphs",
"trees"
] | 1,236 | 640 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 39 |
a569cd5f8bf8aaf011858f839e91848a | You are given a tree with n vertices numbered from 1 to n. The height of the i-th vertex is h_i. You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency e costs e coins, where e > 0.It is considered that a vertex x gets a signal if for some pair of towers at the vertices u and v (u \neq v, but it is allowed that x = u or x = v) with efficiencies e_u and e_v, respectively, it is satisfied that \min(e_u, e_v) \geq h_x and x lies on the path between u and v.Find the minimum number of coins required to set up towers so that you can get a signal at all vertices. | ['constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees'] | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
def solve():
n = ri()
H = rl()
G = dd(list)
P = dd(lambda:-1)
for i in range(n - 1):
u, v = rl()
u -= 1
v -= 1
G[u].append(v)
G[v].append(u)
root = 0
highest = 0
for i in range(n):
if H[i] > highest:
root = i
highest = H[i]
P[root] = root
curr = [root]
while curr:
node = curr.pop()
for nbr in G[node]:
if P[nbr] == -1:
P[nbr] = node
curr.append(nbr)
maxbelow = [0] * n
# def dfs(u):
# for v in G[u]:
# if v != P[u]:
# dfs(v)
# maxbelow[u] = max(maxbelow[u], maxbelow[v], H[v])
#
#
# dfs(root)
layers = [root]
curr = [root]
while curr:
nxt = []
for node in curr:
for nbr in G[node]:
if nbr != P[node]:
nxt.append(nbr)
layers += nxt
curr = nxt
for u in layers[::-1]:
for v in G[u]:
if v != P[u]:
maxbelow[u] = max(maxbelow[u], maxbelow[v], H[v])
ans = 0
for i in range(n):
if i == root: continue
ans += max(0, H[i] - maxbelow[i])
paths = []
for v in G[root]:
paths.append(max(H[v], maxbelow[v]))
if len(paths) == 1:
ans += H[root] + H[root] - paths[0]
else:
paths.sort()
ans += 2 * H[root] - paths[-1] - paths[-2]
print (ans)
mode = 's'
if mode == 'T':
t = ri()
for i in range(t):
solve()
else:
solve()
| Python | [
"graphs",
"trees"
] | 806 | 3,650 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 367 |
29f891dc2fa4012cce8cc4b894ae4742 | Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs .Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t.Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as , , ... | ['hashing', 'string suffix structures', 'implementation', 'data structures', 'strings'] | def ziped(a):
p = []
for i in a:
x = int(i.split('-')[0])
y = i.split('-')[1]
if len(p) > 0 and p[-1][1] == y:
p[-1][0] += x
else:
p.append([x, y])
return p
def solve(a, b , c):
ans = 0
if len(b) == 1:
for token in a:
#print("token",token)
if c(token, b[0]):
ans += token[0] - b[0][0] + 1
return ans
if len(b) == 2:
for i in range(len(a) - 1):
if c(a[i], b[0]) and c(a[i + 1], b[-1]):
ans += 1
return ans
v = b[1 : -1] + [[100500, '#']] + a
p = [0] * len(v)
for i in range(1, len(v)):
j = p[i - 1]
while j > 0 and v[i] != v[j]:
j = p[j - 1]
if v[i] == v[j]:
j += 1
p[i] = j
for i in range(len(v) - 1):
if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]):
ans += 1
return ans
n, m = map(int, input().split())
a = ziped(input().split())
b = ziped(input().split())
print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0]))
| Python | [
"strings"
] | 1,432 | 1,143 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 1,202 |
cf28ab7f4c20b6b914c2c58951319b14 | This is an interactive problem.Consider a fixed positive integer n. Two players, First and Second play a game as follows: First considers the 2n numbers 1, 2, \dots, 2n, and partitions them as he wants into n disjoint pairs. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants). To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of 2n, then Second wins. Otherwise, First wins.You are given the integer n. Your task is to decide which player you wish to play as and win the game. | ['constructive algorithms', 'number theory', 'math', 'interactive', 'dfs and similar'] | import sys
input = sys.stdin.readline
import random
n=int(input())
if n%2==0:
print("First",flush=True)
ANS=[0]*(2*n)
for i in range(2*n):
ANS[i]=i%n+1
print(*ANS,flush=True)
END=int(input())
sys.exit()
else:
print("Second",flush=True)
A=[0]+list(map(int,input().split()))
C=[[] for i in range(n+1)]
for i in range(1,2*n+1):
C[A[i]].append(i)
def rev(x):
if x<=n:
return x+n
else:
return x-n
def calc():
USE=[-1]*(2*n+1)
Q=[]
for i in range(1,n+1):
if USE[i]==-1 and USE[i+n]==-1:
Q.append(random.choice([i,i+n]))
while Q:
#print(Q)
x=Q.pop()
USE[x]=1
USE[rev(x)]=0
#print(USE)
for to in C[A[rev(x)]]:
#print(to)
if USE[to]==-1:
USE[to]=1
Q.append(to)
#print(Q)
for to in C[A[x]]:
if USE[to]==-1:
USE[to]=0
Q.append(rev(to))
#print(Q)
S=0
#print(USE)
ANS=[]
for i in range(1,2*n+1):
if USE[i]==1:
S+=i
ANS.append(i)
if S%(2*n)==0:
return ANS
else:
return -1
while True:
x=random.randint(1,2*n)
#print(x)
k=calc()
if k!=-1:
break
print(*k,flush=True)
END=int(input())
sys.exit()
| Python | [
"number theory",
"math",
"graphs"
] | 661 | 1,695 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.